@mastra/code-sdk 1.21.0-alpha.6 → 1.21.0-alpha.7

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 (580) hide show
  1. package/dist/acp/agent.js +0 -2
  2. package/dist/acp/errors.js +0 -2
  3. package/dist/acp/event-mapper.js +0 -2
  4. package/dist/acp/index.js +0 -2
  5. package/dist/acp/runtime.js +0 -2
  6. package/dist/acp/server.js +0 -2
  7. package/dist/acp/skills.js +0 -2
  8. package/dist/agent-connections/messaging-processor.js +0 -2
  9. package/dist/agent-connections/ownership.js +0 -2
  10. package/dist/agent-connections/registry.js +0 -2
  11. package/dist/agent-connections/session-advertisement.js +0 -2
  12. package/dist/agent-connections/signal-provider.js +0 -2
  13. package/dist/agent-connections/state-processor.js +0 -2
  14. package/dist/agent-connections/thread-state.js +0 -2
  15. package/dist/agent-connections/tools.js +0 -2
  16. package/dist/agent-connections/types.js +0 -2
  17. package/dist/agent-connections/untrusted-text.js +0 -2
  18. package/dist/agents/background-completion-events.js +0 -2
  19. package/dist/agents/background-completion.js +0 -2
  20. package/dist/agents/context-audit.js +0 -2
  21. package/dist/agents/credential-resolver.js +0 -2
  22. package/dist/agents/custom-provider-source.js +0 -2
  23. package/dist/agents/fastembed-subprocess.d.ts +21 -0
  24. package/dist/agents/fastembed-subprocess.js +88 -8
  25. package/dist/agents/instructions.js +0 -2
  26. package/dist/agents/mastracode-gateway.js +0 -2
  27. package/dist/agents/memory.js +0 -2
  28. package/dist/agents/model.js +0 -2
  29. package/dist/agents/modes/build.js +0 -2
  30. package/dist/agents/modes/explore.js +0 -2
  31. package/dist/agents/modes/plan.js +0 -2
  32. package/dist/agents/prompts/agent-instructions.js +0 -2
  33. package/dist/agents/prompts/build.js +0 -2
  34. package/dist/agents/prompts/fast.js +0 -2
  35. package/dist/agents/prompts/index.js +0 -2
  36. package/dist/agents/prompts/model.js +0 -2
  37. package/dist/agents/prompts/plan.js +0 -2
  38. package/dist/agents/prompts/tool-guidance.js +0 -2
  39. package/dist/agents/sandbox-filesystem.js +0 -2
  40. package/dist/agents/subagents/execute.js +0 -2
  41. package/dist/agents/subagents/explore.js +0 -2
  42. package/dist/agents/subagents/index.js +0 -2
  43. package/dist/agents/subagents/plan.js +0 -2
  44. package/dist/agents/thread-caveman-state.js +0 -2
  45. package/dist/agents/tool-availability.js +0 -2
  46. package/dist/agents/tools.js +0 -2
  47. package/dist/agents/workflow-builder-agent.js +0 -2
  48. package/dist/agents/workspace.js +0 -2
  49. package/dist/analytics.js +0 -2
  50. package/dist/auth/account-rotation-processor.js +0 -2
  51. package/dist/auth/account-routing-context.js +0 -2
  52. package/dist/auth/authorization-input.js +0 -2
  53. package/dist/auth/device-code.js +0 -2
  54. package/dist/auth/pkce.js +0 -2
  55. package/dist/auth/provider-auth-error.js +0 -2
  56. package/dist/auth/providers/anthropic.js +0 -2
  57. package/dist/auth/providers/github-copilot.js +0 -2
  58. package/dist/auth/providers/kimi-coding.js +0 -2
  59. package/dist/auth/providers/openai-codex.js +0 -2
  60. package/dist/auth/providers/xai.js +0 -2
  61. package/dist/auth/storage.js +0 -2
  62. package/dist/clipboard/index.js +0 -2
  63. package/dist/constants.js +0 -2
  64. package/dist/error-classification.js +0 -2
  65. package/dist/evals/context-builder.js +0 -2
  66. package/dist/evals/scorers/classify-command.js +0 -2
  67. package/dist/evals/scorers/efficiency.js +0 -2
  68. package/dist/evals/scorers/extract-tools.js +0 -2
  69. package/dist/evals/scorers/outcome.js +0 -2
  70. package/dist/experimental-agent.js +0 -2
  71. package/dist/factory/client.js +0 -2
  72. package/dist/factory/remote-controller.js +0 -2
  73. package/dist/factory/remote-session.js +0 -2
  74. package/dist/goal-manager.js +0 -2
  75. package/dist/goal-signal.js +0 -2
  76. package/dist/headless/cli.js +5 -2
  77. package/dist/headless/flags.js +0 -2
  78. package/dist/headless/format.js +0 -2
  79. package/dist/headless/policy.js +0 -2
  80. package/dist/headless/run-mc.js +0 -2
  81. package/dist/headless/types.js +0 -2
  82. package/dist/hooks/config.js +0 -2
  83. package/dist/hooks/executor.js +0 -2
  84. package/dist/hooks/manager.js +0 -2
  85. package/dist/hooks/types.js +0 -2
  86. package/dist/index.js +0 -2
  87. package/dist/ipc/ipc-reporter.js +0 -2
  88. package/dist/knowledge-inspector.js +0 -2
  89. package/dist/knowledge-scope-id.js +0 -2
  90. package/dist/knowledge-scope.js +0 -2
  91. package/dist/lsp/client.js +0 -2
  92. package/dist/lsp/language.js +0 -2
  93. package/dist/lsp/manager.js +0 -2
  94. package/dist/lsp/server.js +0 -2
  95. package/dist/lsp/workspace.js +0 -2
  96. package/dist/mcp/config.js +0 -2
  97. package/dist/mcp/manager.js +0 -2
  98. package/dist/mcp/state.js +0 -2
  99. package/dist/onboarding/custom-packs.js +0 -2
  100. package/dist/onboarding/custom-providers.js +0 -2
  101. package/dist/onboarding/om-settings.js +0 -2
  102. package/dist/onboarding/pack-activation.js +0 -2
  103. package/dist/onboarding/packs.js +0 -2
  104. package/dist/onboarding/settings.js +0 -2
  105. package/dist/permissions.js +0 -2
  106. package/dist/platform/index.js +0 -2
  107. package/dist/plugin.js +0 -2
  108. package/dist/plugins/dependencies.js +0 -2
  109. package/dist/plugins/install.js +0 -2
  110. package/dist/plugins/loader.js +0 -2
  111. package/dist/plugins/manager.js +0 -2
  112. package/dist/plugins/manifest.js +0 -2
  113. package/dist/plugins/package-link.js +0 -2
  114. package/dist/plugins/paths.js +0 -2
  115. package/dist/plugins/registry.js +0 -2
  116. package/dist/plugins/scaffold.js +0 -2
  117. package/dist/plugins/signal-lane.js +0 -2
  118. package/dist/process-memory-diagnostics.js +0 -2
  119. package/dist/processors/plan-rejection-abort.js +0 -2
  120. package/dist/providers/amazon-bedrock-gateway.js +0 -2
  121. package/dist/providers/amazon-bedrock.js +0 -2
  122. package/dist/providers/anthropic-prompt-cache.js +0 -2
  123. package/dist/providers/anthropic-thinking.js +0 -2
  124. package/dist/providers/claude-max.js +0 -2
  125. package/dist/providers/github-copilot-gateway.js +0 -2
  126. package/dist/providers/github-copilot.js +0 -2
  127. package/dist/providers/google-thinking.js +0 -2
  128. package/dist/providers/google-vertex-gateway.js +0 -2
  129. package/dist/providers/google-vertex.js +0 -2
  130. package/dist/providers/kimi-coding.js +0 -2
  131. package/dist/providers/model-ids.js +0 -2
  132. package/dist/providers/openai-codex.js +0 -2
  133. package/dist/providers/provider-thinking.js +0 -2
  134. package/dist/providers/thinking-request.js +0 -2
  135. package/dist/providers/xai.js +0 -2
  136. package/dist/schedules/interval.js +0 -2
  137. package/dist/schedules/prompt.js +0 -2
  138. package/dist/schedules/run-script.js +0 -2
  139. package/dist/schedules/scheduler.js +0 -2
  140. package/dist/schedules/tools.js +0 -2
  141. package/dist/schema.js +0 -2
  142. package/dist/theme-palette.js +0 -2
  143. package/dist/thinking-catalog.js +0 -2
  144. package/dist/thinking.js +0 -2
  145. package/dist/tool-names.js +0 -2
  146. package/dist/tools/request-sandbox-access.js +0 -2
  147. package/dist/tools/utils.js +0 -2
  148. package/dist/tools/web-search.js +0 -2
  149. package/dist/tools/workflows/create-workflow.js +0 -2
  150. package/dist/tools/workflows/delete-workflow.js +0 -2
  151. package/dist/tools/workflows/ephemeral-memory.js +0 -2
  152. package/dist/tools/workflows/extract-json-schema.js +0 -2
  153. package/dist/tools/workflows/get-workflow.js +0 -2
  154. package/dist/tools/workflows/list-available-agents.js +0 -2
  155. package/dist/tools/workflows/list-available-classifiers.js +0 -2
  156. package/dist/tools/workflows/list-available-tools.js +0 -2
  157. package/dist/tools/workflows/list-available-workflows.js +0 -2
  158. package/dist/tools/workflows/list-workflows.js +0 -2
  159. package/dist/tools/workflows/run-workflow.js +0 -2
  160. package/dist/tools/workflows/save-workflow.js +0 -2
  161. package/dist/tools/workflows/tool-ids.js +0 -2
  162. package/dist/utils/binaries.js +0 -2
  163. package/dist/utils/debug-log.js +0 -2
  164. package/dist/utils/discarding-scores-storage.js +0 -2
  165. package/dist/utils/errors.js +0 -2
  166. package/dist/utils/gateway-sync.js +0 -2
  167. package/dist/utils/local-observability.js +0 -2
  168. package/dist/utils/maintenance-lock.js +0 -2
  169. package/dist/utils/notification-dispatch.js +0 -2
  170. package/dist/utils/open-url.js +0 -2
  171. package/dist/utils/path-security.js +0 -2
  172. package/dist/utils/plan-diff.js +0 -2
  173. package/dist/utils/plans.js +0 -2
  174. package/dist/utils/project.js +0 -2
  175. package/dist/utils/prune-cli.js +0 -2
  176. package/dist/utils/signals-pubsub.js +0 -2
  177. package/dist/utils/slash-command-loader.js +0 -2
  178. package/dist/utils/slash-command-processor.js +0 -2
  179. package/dist/utils/stdin-pipe.js +0 -2
  180. package/dist/utils/storage-factory.js +0 -2
  181. package/dist/utils/storage-maintenance.js +0 -2
  182. package/dist/utils/thread-lock.js +0 -2
  183. package/dist/utils/token-estimator.js +0 -2
  184. package/dist/utils/update-check.js +0 -2
  185. package/dist/utils/wake-session.js +0 -2
  186. package/dist/voice/stt-registry.js +0 -2
  187. package/dist/voice/transcribe.js +0 -2
  188. package/dist/workflows/register-primitives.js +0 -2
  189. package/dist/workflows/service.js +0 -2
  190. package/package.json +23 -22
  191. package/dist/acp/agent.d.ts.map +0 -1
  192. package/dist/acp/agent.js.map +0 -1
  193. package/dist/acp/errors.d.ts.map +0 -1
  194. package/dist/acp/errors.js.map +0 -1
  195. package/dist/acp/event-mapper.d.ts.map +0 -1
  196. package/dist/acp/event-mapper.js.map +0 -1
  197. package/dist/acp/index.d.ts.map +0 -1
  198. package/dist/acp/index.js.map +0 -1
  199. package/dist/acp/runtime.d.ts.map +0 -1
  200. package/dist/acp/runtime.js.map +0 -1
  201. package/dist/acp/server.d.ts.map +0 -1
  202. package/dist/acp/server.js.map +0 -1
  203. package/dist/acp/skills.d.ts.map +0 -1
  204. package/dist/acp/skills.js.map +0 -1
  205. package/dist/acp.d.ts.map +0 -1
  206. package/dist/agent-connections/messaging-processor.d.ts.map +0 -1
  207. package/dist/agent-connections/messaging-processor.js.map +0 -1
  208. package/dist/agent-connections/ownership.d.ts.map +0 -1
  209. package/dist/agent-connections/ownership.js.map +0 -1
  210. package/dist/agent-connections/registry.d.ts.map +0 -1
  211. package/dist/agent-connections/registry.js.map +0 -1
  212. package/dist/agent-connections/session-advertisement.d.ts.map +0 -1
  213. package/dist/agent-connections/session-advertisement.js.map +0 -1
  214. package/dist/agent-connections/signal-provider.d.ts.map +0 -1
  215. package/dist/agent-connections/signal-provider.js.map +0 -1
  216. package/dist/agent-connections/state-processor.d.ts.map +0 -1
  217. package/dist/agent-connections/state-processor.js.map +0 -1
  218. package/dist/agent-connections/thread-state.d.ts.map +0 -1
  219. package/dist/agent-connections/thread-state.js.map +0 -1
  220. package/dist/agent-connections/tools.d.ts.map +0 -1
  221. package/dist/agent-connections/tools.js.map +0 -1
  222. package/dist/agent-connections/types.d.ts.map +0 -1
  223. package/dist/agent-connections/types.js.map +0 -1
  224. package/dist/agent-connections/untrusted-text.d.ts.map +0 -1
  225. package/dist/agent-connections/untrusted-text.js.map +0 -1
  226. package/dist/agents/background-completion-events.d.ts.map +0 -1
  227. package/dist/agents/background-completion-events.js.map +0 -1
  228. package/dist/agents/background-completion.d.ts.map +0 -1
  229. package/dist/agents/background-completion.js.map +0 -1
  230. package/dist/agents/context-audit.d.ts.map +0 -1
  231. package/dist/agents/context-audit.js.map +0 -1
  232. package/dist/agents/credential-resolver.d.ts.map +0 -1
  233. package/dist/agents/credential-resolver.js.map +0 -1
  234. package/dist/agents/custom-provider-source.d.ts.map +0 -1
  235. package/dist/agents/custom-provider-source.js.map +0 -1
  236. package/dist/agents/fastembed-subprocess.d.ts.map +0 -1
  237. package/dist/agents/fastembed-subprocess.js.map +0 -1
  238. package/dist/agents/instructions.d.ts.map +0 -1
  239. package/dist/agents/instructions.js.map +0 -1
  240. package/dist/agents/mastracode-gateway.d.ts.map +0 -1
  241. package/dist/agents/mastracode-gateway.js.map +0 -1
  242. package/dist/agents/memory.d.ts.map +0 -1
  243. package/dist/agents/memory.js.map +0 -1
  244. package/dist/agents/model.d.ts.map +0 -1
  245. package/dist/agents/model.js.map +0 -1
  246. package/dist/agents/modes/build.d.ts.map +0 -1
  247. package/dist/agents/modes/build.js.map +0 -1
  248. package/dist/agents/modes/explore.d.ts.map +0 -1
  249. package/dist/agents/modes/explore.js.map +0 -1
  250. package/dist/agents/modes/plan.d.ts.map +0 -1
  251. package/dist/agents/modes/plan.js.map +0 -1
  252. package/dist/agents/prompts/agent-instructions.d.ts.map +0 -1
  253. package/dist/agents/prompts/agent-instructions.js.map +0 -1
  254. package/dist/agents/prompts/build.d.ts.map +0 -1
  255. package/dist/agents/prompts/build.js.map +0 -1
  256. package/dist/agents/prompts/fast.d.ts.map +0 -1
  257. package/dist/agents/prompts/fast.js.map +0 -1
  258. package/dist/agents/prompts/index.d.ts.map +0 -1
  259. package/dist/agents/prompts/index.js.map +0 -1
  260. package/dist/agents/prompts/model.d.ts.map +0 -1
  261. package/dist/agents/prompts/model.js.map +0 -1
  262. package/dist/agents/prompts/plan.d.ts.map +0 -1
  263. package/dist/agents/prompts/plan.js.map +0 -1
  264. package/dist/agents/prompts/tool-guidance.d.ts.map +0 -1
  265. package/dist/agents/prompts/tool-guidance.js.map +0 -1
  266. package/dist/agents/sandbox-filesystem.d.ts.map +0 -1
  267. package/dist/agents/sandbox-filesystem.js.map +0 -1
  268. package/dist/agents/subagents/execute.d.ts.map +0 -1
  269. package/dist/agents/subagents/execute.js.map +0 -1
  270. package/dist/agents/subagents/explore.d.ts.map +0 -1
  271. package/dist/agents/subagents/explore.js.map +0 -1
  272. package/dist/agents/subagents/index.d.ts.map +0 -1
  273. package/dist/agents/subagents/index.js.map +0 -1
  274. package/dist/agents/subagents/plan.d.ts.map +0 -1
  275. package/dist/agents/subagents/plan.js.map +0 -1
  276. package/dist/agents/thread-caveman-state.d.ts.map +0 -1
  277. package/dist/agents/thread-caveman-state.js.map +0 -1
  278. package/dist/agents/tool-availability.d.ts.map +0 -1
  279. package/dist/agents/tool-availability.js.map +0 -1
  280. package/dist/agents/tools.d.ts.map +0 -1
  281. package/dist/agents/tools.js.map +0 -1
  282. package/dist/agents/workflow-builder-agent.d.ts.map +0 -1
  283. package/dist/agents/workflow-builder-agent.js.map +0 -1
  284. package/dist/agents/workspace.d.ts.map +0 -1
  285. package/dist/agents/workspace.js.map +0 -1
  286. package/dist/analytics.d.ts.map +0 -1
  287. package/dist/analytics.js.map +0 -1
  288. package/dist/auth/account-rotation-processor.d.ts.map +0 -1
  289. package/dist/auth/account-rotation-processor.js.map +0 -1
  290. package/dist/auth/account-routing-context.d.ts.map +0 -1
  291. package/dist/auth/account-routing-context.js.map +0 -1
  292. package/dist/auth/authorization-input.d.ts.map +0 -1
  293. package/dist/auth/authorization-input.js.map +0 -1
  294. package/dist/auth/device-code.d.ts.map +0 -1
  295. package/dist/auth/device-code.js.map +0 -1
  296. package/dist/auth/index.d.ts.map +0 -1
  297. package/dist/auth/pkce.d.ts.map +0 -1
  298. package/dist/auth/pkce.js.map +0 -1
  299. package/dist/auth/provider-auth-error.d.ts.map +0 -1
  300. package/dist/auth/provider-auth-error.js.map +0 -1
  301. package/dist/auth/providers/anthropic.d.ts.map +0 -1
  302. package/dist/auth/providers/anthropic.js.map +0 -1
  303. package/dist/auth/providers/github-copilot.d.ts.map +0 -1
  304. package/dist/auth/providers/github-copilot.js.map +0 -1
  305. package/dist/auth/providers/kimi-coding.d.ts.map +0 -1
  306. package/dist/auth/providers/kimi-coding.js.map +0 -1
  307. package/dist/auth/providers/openai-codex.d.ts.map +0 -1
  308. package/dist/auth/providers/openai-codex.js.map +0 -1
  309. package/dist/auth/providers/xai.d.ts.map +0 -1
  310. package/dist/auth/providers/xai.js.map +0 -1
  311. package/dist/auth/storage.d.ts.map +0 -1
  312. package/dist/auth/storage.js.map +0 -1
  313. package/dist/auth/types.d.ts.map +0 -1
  314. package/dist/clipboard/index.d.ts.map +0 -1
  315. package/dist/clipboard/index.js.map +0 -1
  316. package/dist/constants.d.ts.map +0 -1
  317. package/dist/constants.js.map +0 -1
  318. package/dist/error-classification.d.ts.map +0 -1
  319. package/dist/error-classification.js.map +0 -1
  320. package/dist/evals/context-builder.d.ts.map +0 -1
  321. package/dist/evals/context-builder.js.map +0 -1
  322. package/dist/evals/index.d.ts.map +0 -1
  323. package/dist/evals/scorers/classify-command.d.ts.map +0 -1
  324. package/dist/evals/scorers/classify-command.js.map +0 -1
  325. package/dist/evals/scorers/efficiency.d.ts.map +0 -1
  326. package/dist/evals/scorers/efficiency.js.map +0 -1
  327. package/dist/evals/scorers/extract-tools.d.ts.map +0 -1
  328. package/dist/evals/scorers/extract-tools.js.map +0 -1
  329. package/dist/evals/scorers/index.d.ts.map +0 -1
  330. package/dist/evals/scorers/outcome.d.ts.map +0 -1
  331. package/dist/evals/scorers/outcome.js.map +0 -1
  332. package/dist/experimental-agent.d.ts.map +0 -1
  333. package/dist/experimental-agent.js.map +0 -1
  334. package/dist/factory/client.d.ts.map +0 -1
  335. package/dist/factory/client.js.map +0 -1
  336. package/dist/factory/remote-controller.d.ts.map +0 -1
  337. package/dist/factory/remote-controller.js.map +0 -1
  338. package/dist/factory/remote-session.d.ts.map +0 -1
  339. package/dist/factory/remote-session.js.map +0 -1
  340. package/dist/goal-manager.d.ts.map +0 -1
  341. package/dist/goal-manager.js.map +0 -1
  342. package/dist/goal-signal.d.ts.map +0 -1
  343. package/dist/goal-signal.js.map +0 -1
  344. package/dist/headless/cli.d.ts.map +0 -1
  345. package/dist/headless/cli.js.map +0 -1
  346. package/dist/headless/flags.d.ts.map +0 -1
  347. package/dist/headless/flags.js.map +0 -1
  348. package/dist/headless/format.d.ts.map +0 -1
  349. package/dist/headless/format.js.map +0 -1
  350. package/dist/headless/index.d.ts.map +0 -1
  351. package/dist/headless/policy.d.ts.map +0 -1
  352. package/dist/headless/policy.js.map +0 -1
  353. package/dist/headless/run-mc.d.ts.map +0 -1
  354. package/dist/headless/run-mc.js.map +0 -1
  355. package/dist/headless/types.d.ts.map +0 -1
  356. package/dist/headless/types.js.map +0 -1
  357. package/dist/hooks/config.d.ts.map +0 -1
  358. package/dist/hooks/config.js.map +0 -1
  359. package/dist/hooks/executor.d.ts.map +0 -1
  360. package/dist/hooks/executor.js.map +0 -1
  361. package/dist/hooks/index.d.ts.map +0 -1
  362. package/dist/hooks/manager.d.ts.map +0 -1
  363. package/dist/hooks/manager.js.map +0 -1
  364. package/dist/hooks/types.d.ts.map +0 -1
  365. package/dist/hooks/types.js.map +0 -1
  366. package/dist/index.d.ts.map +0 -1
  367. package/dist/index.js.map +0 -1
  368. package/dist/ipc/ipc-reporter.d.ts.map +0 -1
  369. package/dist/ipc/ipc-reporter.js.map +0 -1
  370. package/dist/knowledge-inspector.d.ts.map +0 -1
  371. package/dist/knowledge-inspector.js.map +0 -1
  372. package/dist/knowledge-scope-id.d.ts.map +0 -1
  373. package/dist/knowledge-scope-id.js.map +0 -1
  374. package/dist/knowledge-scope.d.ts.map +0 -1
  375. package/dist/knowledge-scope.js.map +0 -1
  376. package/dist/lsp/client.d.ts.map +0 -1
  377. package/dist/lsp/client.js.map +0 -1
  378. package/dist/lsp/index.d.ts.map +0 -1
  379. package/dist/lsp/language.d.ts.map +0 -1
  380. package/dist/lsp/language.js.map +0 -1
  381. package/dist/lsp/manager.d.ts.map +0 -1
  382. package/dist/lsp/manager.js.map +0 -1
  383. package/dist/lsp/server.d.ts.map +0 -1
  384. package/dist/lsp/server.js.map +0 -1
  385. package/dist/lsp/workspace.d.ts.map +0 -1
  386. package/dist/lsp/workspace.js.map +0 -1
  387. package/dist/mcp/config.d.ts.map +0 -1
  388. package/dist/mcp/config.js.map +0 -1
  389. package/dist/mcp/index.d.ts.map +0 -1
  390. package/dist/mcp/manager.d.ts.map +0 -1
  391. package/dist/mcp/manager.js.map +0 -1
  392. package/dist/mcp/state.d.ts.map +0 -1
  393. package/dist/mcp/state.js.map +0 -1
  394. package/dist/mcp/types.d.ts.map +0 -1
  395. package/dist/onboarding/custom-packs.d.ts.map +0 -1
  396. package/dist/onboarding/custom-packs.js.map +0 -1
  397. package/dist/onboarding/custom-providers.d.ts.map +0 -1
  398. package/dist/onboarding/custom-providers.js.map +0 -1
  399. package/dist/onboarding/index.d.ts.map +0 -1
  400. package/dist/onboarding/om-settings.d.ts.map +0 -1
  401. package/dist/onboarding/om-settings.js.map +0 -1
  402. package/dist/onboarding/pack-activation.d.ts.map +0 -1
  403. package/dist/onboarding/pack-activation.js.map +0 -1
  404. package/dist/onboarding/packs.d.ts.map +0 -1
  405. package/dist/onboarding/packs.js.map +0 -1
  406. package/dist/onboarding/settings.d.ts.map +0 -1
  407. package/dist/onboarding/settings.js.map +0 -1
  408. package/dist/permissions.d.ts.map +0 -1
  409. package/dist/permissions.js.map +0 -1
  410. package/dist/platform/index.d.ts.map +0 -1
  411. package/dist/platform/index.js.map +0 -1
  412. package/dist/plugin.d.ts.map +0 -1
  413. package/dist/plugin.js.map +0 -1
  414. package/dist/plugins/dependencies.d.ts.map +0 -1
  415. package/dist/plugins/dependencies.js.map +0 -1
  416. package/dist/plugins/install.d.ts.map +0 -1
  417. package/dist/plugins/install.js.map +0 -1
  418. package/dist/plugins/loader.d.ts.map +0 -1
  419. package/dist/plugins/loader.js.map +0 -1
  420. package/dist/plugins/manager.d.ts.map +0 -1
  421. package/dist/plugins/manager.js.map +0 -1
  422. package/dist/plugins/manifest.d.ts.map +0 -1
  423. package/dist/plugins/manifest.js.map +0 -1
  424. package/dist/plugins/package-link.d.ts.map +0 -1
  425. package/dist/plugins/package-link.js.map +0 -1
  426. package/dist/plugins/paths.d.ts.map +0 -1
  427. package/dist/plugins/paths.js.map +0 -1
  428. package/dist/plugins/registry.d.ts.map +0 -1
  429. package/dist/plugins/registry.js.map +0 -1
  430. package/dist/plugins/scaffold.d.ts.map +0 -1
  431. package/dist/plugins/scaffold.js.map +0 -1
  432. package/dist/plugins/signal-lane.d.ts.map +0 -1
  433. package/dist/plugins/signal-lane.js.map +0 -1
  434. package/dist/plugins/types.d.ts.map +0 -1
  435. package/dist/process-memory-diagnostics.d.ts.map +0 -1
  436. package/dist/process-memory-diagnostics.js.map +0 -1
  437. package/dist/processors/plan-rejection-abort.d.ts.map +0 -1
  438. package/dist/processors/plan-rejection-abort.js.map +0 -1
  439. package/dist/providers/amazon-bedrock-gateway.d.ts.map +0 -1
  440. package/dist/providers/amazon-bedrock-gateway.js.map +0 -1
  441. package/dist/providers/amazon-bedrock.d.ts.map +0 -1
  442. package/dist/providers/amazon-bedrock.js.map +0 -1
  443. package/dist/providers/anthropic-prompt-cache.d.ts.map +0 -1
  444. package/dist/providers/anthropic-prompt-cache.js.map +0 -1
  445. package/dist/providers/anthropic-thinking.d.ts.map +0 -1
  446. package/dist/providers/anthropic-thinking.js.map +0 -1
  447. package/dist/providers/claude-max.d.ts.map +0 -1
  448. package/dist/providers/claude-max.js.map +0 -1
  449. package/dist/providers/github-copilot-gateway.d.ts.map +0 -1
  450. package/dist/providers/github-copilot-gateway.js.map +0 -1
  451. package/dist/providers/github-copilot.d.ts.map +0 -1
  452. package/dist/providers/github-copilot.js.map +0 -1
  453. package/dist/providers/google-thinking.d.ts.map +0 -1
  454. package/dist/providers/google-thinking.js.map +0 -1
  455. package/dist/providers/google-vertex-gateway.d.ts.map +0 -1
  456. package/dist/providers/google-vertex-gateway.js.map +0 -1
  457. package/dist/providers/google-vertex.d.ts.map +0 -1
  458. package/dist/providers/google-vertex.js.map +0 -1
  459. package/dist/providers/kimi-coding.d.ts.map +0 -1
  460. package/dist/providers/kimi-coding.js.map +0 -1
  461. package/dist/providers/model-ids.d.ts.map +0 -1
  462. package/dist/providers/model-ids.js.map +0 -1
  463. package/dist/providers/openai-codex.d.ts.map +0 -1
  464. package/dist/providers/openai-codex.js.map +0 -1
  465. package/dist/providers/provider-thinking.d.ts.map +0 -1
  466. package/dist/providers/provider-thinking.js.map +0 -1
  467. package/dist/providers/thinking-request.d.ts.map +0 -1
  468. package/dist/providers/thinking-request.js.map +0 -1
  469. package/dist/providers/xai.d.ts.map +0 -1
  470. package/dist/providers/xai.js.map +0 -1
  471. package/dist/schedules/index.d.ts.map +0 -1
  472. package/dist/schedules/interval.d.ts.map +0 -1
  473. package/dist/schedules/interval.js.map +0 -1
  474. package/dist/schedules/prompt.d.ts.map +0 -1
  475. package/dist/schedules/prompt.js.map +0 -1
  476. package/dist/schedules/run-script.d.ts.map +0 -1
  477. package/dist/schedules/run-script.js.map +0 -1
  478. package/dist/schedules/scheduler.d.ts.map +0 -1
  479. package/dist/schedules/scheduler.js.map +0 -1
  480. package/dist/schedules/tools.d.ts.map +0 -1
  481. package/dist/schedules/tools.js.map +0 -1
  482. package/dist/schema.d.ts.map +0 -1
  483. package/dist/schema.js.map +0 -1
  484. package/dist/theme-palette.d.ts.map +0 -1
  485. package/dist/theme-palette.js.map +0 -1
  486. package/dist/thinking-catalog.d.ts.map +0 -1
  487. package/dist/thinking-catalog.js.map +0 -1
  488. package/dist/thinking.d.ts.map +0 -1
  489. package/dist/thinking.js.map +0 -1
  490. package/dist/tool-names.d.ts.map +0 -1
  491. package/dist/tool-names.js.map +0 -1
  492. package/dist/tools/index.d.ts.map +0 -1
  493. package/dist/tools/request-sandbox-access.d.ts.map +0 -1
  494. package/dist/tools/request-sandbox-access.js.map +0 -1
  495. package/dist/tools/utils.d.ts.map +0 -1
  496. package/dist/tools/utils.js.map +0 -1
  497. package/dist/tools/web-search.d.ts.map +0 -1
  498. package/dist/tools/web-search.js.map +0 -1
  499. package/dist/tools/workflows/create-workflow.d.ts.map +0 -1
  500. package/dist/tools/workflows/create-workflow.js.map +0 -1
  501. package/dist/tools/workflows/delete-workflow.d.ts.map +0 -1
  502. package/dist/tools/workflows/delete-workflow.js.map +0 -1
  503. package/dist/tools/workflows/ephemeral-memory.d.ts.map +0 -1
  504. package/dist/tools/workflows/ephemeral-memory.js.map +0 -1
  505. package/dist/tools/workflows/extract-json-schema.d.ts.map +0 -1
  506. package/dist/tools/workflows/extract-json-schema.js.map +0 -1
  507. package/dist/tools/workflows/get-workflow.d.ts.map +0 -1
  508. package/dist/tools/workflows/get-workflow.js.map +0 -1
  509. package/dist/tools/workflows/list-available-agents.d.ts.map +0 -1
  510. package/dist/tools/workflows/list-available-agents.js.map +0 -1
  511. package/dist/tools/workflows/list-available-classifiers.d.ts.map +0 -1
  512. package/dist/tools/workflows/list-available-classifiers.js.map +0 -1
  513. package/dist/tools/workflows/list-available-tools.d.ts.map +0 -1
  514. package/dist/tools/workflows/list-available-tools.js.map +0 -1
  515. package/dist/tools/workflows/list-available-workflows.d.ts.map +0 -1
  516. package/dist/tools/workflows/list-available-workflows.js.map +0 -1
  517. package/dist/tools/workflows/list-workflows.d.ts.map +0 -1
  518. package/dist/tools/workflows/list-workflows.js.map +0 -1
  519. package/dist/tools/workflows/run-workflow.d.ts.map +0 -1
  520. package/dist/tools/workflows/run-workflow.js.map +0 -1
  521. package/dist/tools/workflows/save-workflow.d.ts.map +0 -1
  522. package/dist/tools/workflows/save-workflow.js.map +0 -1
  523. package/dist/tools/workflows/tool-ids.d.ts.map +0 -1
  524. package/dist/tools/workflows/tool-ids.js.map +0 -1
  525. package/dist/utils/binaries.d.ts.map +0 -1
  526. package/dist/utils/binaries.js.map +0 -1
  527. package/dist/utils/debug-log.d.ts.map +0 -1
  528. package/dist/utils/debug-log.js.map +0 -1
  529. package/dist/utils/discarding-scores-storage.d.ts.map +0 -1
  530. package/dist/utils/discarding-scores-storage.js.map +0 -1
  531. package/dist/utils/errors.d.ts.map +0 -1
  532. package/dist/utils/errors.js.map +0 -1
  533. package/dist/utils/gateway-sync.d.ts.map +0 -1
  534. package/dist/utils/gateway-sync.js.map +0 -1
  535. package/dist/utils/local-observability.d.ts.map +0 -1
  536. package/dist/utils/local-observability.js.map +0 -1
  537. package/dist/utils/maintenance-lock.d.ts.map +0 -1
  538. package/dist/utils/maintenance-lock.js.map +0 -1
  539. package/dist/utils/notification-dispatch.d.ts.map +0 -1
  540. package/dist/utils/notification-dispatch.js.map +0 -1
  541. package/dist/utils/open-url.d.ts.map +0 -1
  542. package/dist/utils/open-url.js.map +0 -1
  543. package/dist/utils/path-security.d.ts.map +0 -1
  544. package/dist/utils/path-security.js.map +0 -1
  545. package/dist/utils/plan-diff.d.ts.map +0 -1
  546. package/dist/utils/plan-diff.js.map +0 -1
  547. package/dist/utils/plans.d.ts.map +0 -1
  548. package/dist/utils/plans.js.map +0 -1
  549. package/dist/utils/project.d.ts.map +0 -1
  550. package/dist/utils/project.js.map +0 -1
  551. package/dist/utils/prune-cli.d.ts.map +0 -1
  552. package/dist/utils/prune-cli.js.map +0 -1
  553. package/dist/utils/signals-pubsub.d.ts.map +0 -1
  554. package/dist/utils/signals-pubsub.js.map +0 -1
  555. package/dist/utils/slash-command-loader.d.ts.map +0 -1
  556. package/dist/utils/slash-command-loader.js.map +0 -1
  557. package/dist/utils/slash-command-processor.d.ts.map +0 -1
  558. package/dist/utils/slash-command-processor.js.map +0 -1
  559. package/dist/utils/stdin-pipe.d.ts.map +0 -1
  560. package/dist/utils/stdin-pipe.js.map +0 -1
  561. package/dist/utils/storage-factory.d.ts.map +0 -1
  562. package/dist/utils/storage-factory.js.map +0 -1
  563. package/dist/utils/storage-maintenance.d.ts.map +0 -1
  564. package/dist/utils/storage-maintenance.js.map +0 -1
  565. package/dist/utils/thread-lock.d.ts.map +0 -1
  566. package/dist/utils/thread-lock.js.map +0 -1
  567. package/dist/utils/token-estimator.d.ts.map +0 -1
  568. package/dist/utils/token-estimator.js.map +0 -1
  569. package/dist/utils/update-check.d.ts.map +0 -1
  570. package/dist/utils/update-check.js.map +0 -1
  571. package/dist/utils/wake-session.d.ts.map +0 -1
  572. package/dist/utils/wake-session.js.map +0 -1
  573. package/dist/voice/stt-registry.d.ts.map +0 -1
  574. package/dist/voice/stt-registry.js.map +0 -1
  575. package/dist/voice/transcribe.d.ts.map +0 -1
  576. package/dist/voice/transcribe.js.map +0 -1
  577. package/dist/workflows/register-primitives.d.ts.map +0 -1
  578. package/dist/workflows/register-primitives.js.map +0 -1
  579. package/dist/workflows/service.d.ts.map +0 -1
  580. package/dist/workflows/service.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"google-thinking.d.ts","sourceRoot":"","sources":["../../src/providers/google-thinking.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,IAAI,CAAC;AAClD,OAAO,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAEhF,KAAK,WAAW,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE7C,KAAK,oBAAoB,GAAG;IAAE,aAAa,EAAE,SAAS,GAAG,WAAW,CAAA;CAAE,GAAG;IAAE,cAAc,EAAE,MAAM,CAAA;CAAE,CAAC;AAuBpG,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,mBAAmB,GAAG,oBAAoB,CAGxG;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,oBAAoB,GAAG,SAAS,GACtC,oBAAoB,GAAG,SAAS,CASlC;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAC5C,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,oBAAoB,GAAG,SAAS,GACtC,uBAAuB,GAAG,SAAS,CAkBrC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"google-thinking.js","names":[],"sources":["../../src/providers/google-thinking.ts"],"sourcesContent":["/**\n * Google (Gemini) thinking-level middleware.\n *\n * Maps the Mastra Code session thinking level (`off|low|medium|high|xhigh|max`)\n * onto the thinking control each Gemini family accepts:\n * - Gemini 3+: `thinkingConfig.thinkingLevel` (Gemini 3 Pro only accepts `low|high`).\n * - Gemini 2.5: `thinkingConfig.thinkingBudget` (token budget).\n * Unknown model families get no thinking config, so requests are unchanged.\n */\n\nimport type { LanguageModelMiddleware } from 'ai';\nimport type { ActiveThinkingLevel, ThinkingLevelSetting } from '../thinking.js';\n\ntype GeminiLevel = 'low' | 'medium' | 'high';\ntype GeminiThinkingFamily = 'budget' | 'low-high' | 'minimal-high' | 'levels';\ntype GoogleThinkingConfig = { thinkingLevel: 'minimal' | GeminiLevel } | { thinkingBudget: number };\n\n// Budgets stay within the smallest Gemini 2.5 maximum (24576 for Flash / Flash-Lite).\nconst GEMINI_25_BUDGETS: Record<GeminiLevel, number> = { low: 1024, medium: 8192, high: 24576 };\n\nfunction getGeminiThinkingFamily(modelId: string): GeminiThinkingFamily | undefined {\n const id = modelId.toLowerCase();\n if (id.startsWith('gemini-2.5')) return 'budget';\n // Only Gemini 3 Pro lacks `medium`; Gemini 3.1 Pro accepts it.\n if (id.startsWith('gemini-3-pro')) return 'low-high';\n // Gemini 3.1 Flash Image models only accept `minimal|high`.\n if (id.startsWith('gemini-3.1-flash-image') || id.startsWith('gemini-3.1-flash-lite-image')) return 'minimal-high';\n if (/^gemini-\\d/.test(id) && !id.startsWith('gemini-1') && !id.startsWith('gemini-2')) return 'levels';\n return undefined;\n}\n\nfunction geminiLevelForFamily(family: GeminiThinkingFamily, level: ActiveThinkingLevel): GeminiLevel {\n const cappedAtHigh = level === 'xhigh' || level === 'max' ? 'high' : level;\n const hasNoMedium = family === 'low-high' || family === 'minimal-high';\n if (hasNoMedium && cappedAtHigh === 'medium') return 'high';\n return cappedAtHigh;\n}\n\nexport function runGeminiThinkingLevel(modelId: string, level: ActiveThinkingLevel): ThinkingLevelSetting {\n const family = getGeminiThinkingFamily(modelId);\n return family ? geminiLevelForFamily(family, level) : 'off';\n}\n\n/**\n * Resolve the Google thinking config for a model and session level.\n * Returns `undefined` for `off`, unset levels, and unrecognized model families.\n */\nexport function resolveGoogleThinkingConfig(\n modelId: string,\n level: ThinkingLevelSetting | undefined,\n): GoogleThinkingConfig | undefined {\n if (!level || level === 'off') return undefined;\n const family = getGeminiThinkingFamily(modelId);\n if (!family) return undefined;\n\n const geminiLevel = geminiLevelForFamily(family, level);\n if (family === 'budget') return { thinkingBudget: GEMINI_25_BUDGETS[geminiLevel] };\n if (family === 'minimal-high') return { thinkingLevel: geminiLevel === 'low' ? 'minimal' : 'high' };\n return { thinkingLevel: geminiLevel };\n}\n\n/**\n * Create middleware that injects the resolved config into\n * `providerOptions.google.thinkingConfig`. Returns `undefined` when there is\n * nothing to inject, so callers wrap nothing.\n */\nexport function createGoogleThinkingMiddleware(\n modelId: string,\n level: ThinkingLevelSetting | undefined,\n): LanguageModelMiddleware | undefined {\n const config = resolveGoogleThinkingConfig(modelId, level);\n if (!config) return undefined;\n\n return {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n const google = (params.providerOptions?.google ?? {}) as Record<string, unknown>;\n const thinkingConfig = (google.thinkingConfig ?? {}) as Record<string, unknown>;\n // Explicit caller settings win; Google rejects budget and level together.\n if (thinkingConfig.thinkingBudget !== undefined || thinkingConfig.thinkingLevel !== undefined) return params;\n params.providerOptions = {\n ...params.providerOptions,\n google: { ...google, thinkingConfig: { ...thinkingConfig, ...config } },\n } as typeof params.providerOptions;\n return params;\n },\n };\n}\n"],"mappings":";AAkBA,MAAM,oBAAiD;CAAE,KAAK;CAAM,QAAQ;CAAM,MAAM;AAAM;AAE9F,SAAS,wBAAwB,SAAmD;CAClF,MAAM,KAAK,QAAQ,YAAY;CAC/B,IAAI,GAAG,WAAW,YAAY,GAAG,OAAO;CAExC,IAAI,GAAG,WAAW,cAAc,GAAG,OAAO;CAE1C,IAAI,GAAG,WAAW,wBAAwB,KAAK,GAAG,WAAW,6BAA6B,GAAG,OAAO;CACpG,IAAI,aAAa,KAAK,EAAE,KAAK,CAAC,GAAG,WAAW,UAAU,KAAK,CAAC,GAAG,WAAW,UAAU,GAAG,OAAO;AAEhG;AAEA,SAAS,qBAAqB,QAA8B,OAAyC;CACnG,MAAM,eAAe,UAAU,WAAW,UAAU,QAAQ,SAAS;CAErE,KADoB,WAAW,cAAc,WAAW,mBACrC,iBAAiB,UAAU,OAAO;CACrD,OAAO;AACT;AAEA,SAAgB,uBAAuB,SAAiB,OAAkD;CACxG,MAAM,SAAS,wBAAwB,OAAO;CAC9C,OAAO,SAAS,qBAAqB,QAAQ,KAAK,IAAI;AACxD;;;;;AAMA,SAAgB,4BACd,SACA,OACkC;CAClC,IAAI,CAAC,SAAS,UAAU,OAAO,OAAO,KAAA;CACtC,MAAM,SAAS,wBAAwB,OAAO;CAC9C,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,MAAM,cAAc,qBAAqB,QAAQ,KAAK;CACtD,IAAI,WAAW,UAAU,OAAO,EAAE,gBAAgB,kBAAkB,aAAa;CACjF,IAAI,WAAW,gBAAgB,OAAO,EAAE,eAAe,gBAAgB,QAAQ,YAAY,OAAO;CAClG,OAAO,EAAE,eAAe,YAAY;AACtC;;;;;;AAOA,SAAgB,+BACd,SACA,OACqC;CACrC,MAAM,SAAS,4BAA4B,SAAS,KAAK;CACzD,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,OAAO;EACL,sBAAsB;EACtB,iBAAiB,OAAO,EAAE,aAAa;GACrC,MAAM,SAAU,OAAO,iBAAiB,UAAU,CAAC;GACnD,MAAM,iBAAkB,OAAO,kBAAkB,CAAC;GAElD,IAAI,eAAe,mBAAmB,KAAA,KAAa,eAAe,kBAAkB,KAAA,GAAW,OAAO;GACtG,OAAO,kBAAkB;IACvB,GAAG,OAAO;IACV,QAAQ;KAAE,GAAG;KAAQ,gBAAgB;MAAE,GAAG;MAAgB,GAAG;KAAO;IAAE;GACxE;GACA,OAAO;EACT;CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"google-vertex-gateway.d.ts","sourceRoot":"","sources":["../../src/providers/google-vertex-gateway.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGpH,eAAO,MAAM,wBAAwB,kBAAkB,CAAC;AAExD,wBAAgB,4BAA4B,IAAI,OAAO,CAEtD;AAWD,qBAAa,mBAAoB,SAAQ,kBAAkB;IACzD,QAAQ,CAAC,EAAE,mBAA4B;IACvC,QAAQ,CAAC,IAAI,sBAAsB;IAEnC,YAAY,IAAI,OAAO,CAEtB;IAEK,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAW9D;IAED,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAE7C;IAEK,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEjD;IAED,WAAW,CAAC,QAAQ,EAAE,kBAAkB,GAAG,iBAAiB,GAAG,SAAS,CAIvE;IAED,oBAAoB,CAAC,IAAI,EAAE;QACzB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,SAAS,CAAC,EAAE,GAAG,CAAC;QAChB,kBAAkB,CAAC,EAAE,GAAG,CAAC;KAC1B,GAAG,oBAAoB,CAEvB;CACF;AAED,wBAAgB,yBAAyB,IAAI,mBAAmB,CAE/D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"google-vertex-gateway.js","names":[],"sources":["../../src/providers/google-vertex-gateway.ts"],"sourcesContent":["import { createVertex } from '@ai-sdk/google-vertex';\nimport { MastraModelGateway } from '@mastra/core/llm';\nimport type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, ProviderConfig } from '@mastra/core/llm';\nimport { getGoogleVertexModelCatalog } from './google-vertex.js';\n\nexport const GOOGLE_VERTEX_GATEWAY_ID = 'google-vertex';\n\nexport function hasGoogleVertexConfiguration(): boolean {\n return Boolean(process.env.GOOGLE_VERTEX_PROJECT?.trim() && process.env.GOOGLE_VERTEX_LOCATION?.trim());\n}\n\nfunction googleVertexProvider(modelId: string, headers?: Record<string, string>) {\n const vertex = createVertex({\n project: process.env.GOOGLE_VERTEX_PROJECT?.trim(),\n location: process.env.GOOGLE_VERTEX_LOCATION?.trim(),\n headers,\n });\n return vertex(modelId);\n}\n\nexport class GoogleVertexGateway extends MastraModelGateway {\n readonly id = GOOGLE_VERTEX_GATEWAY_ID;\n readonly name = 'Google Vertex AI';\n\n shouldEnable(): boolean {\n return hasGoogleVertexConfiguration();\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const models = await getGoogleVertexModelCatalog();\n return {\n [GOOGLE_VERTEX_GATEWAY_ID]: {\n name: 'Google Vertex AI',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: models.map(model => model.id),\n },\n };\n }\n\n buildUrl(_modelId: string): string | undefined {\n return undefined;\n }\n\n async getApiKey(_modelId: string): Promise<string> {\n return hasGoogleVertexConfiguration() ? 'google-application-default-credentials' : '';\n }\n\n resolveAuth(_request: GatewayAuthRequest): GatewayAuthResult | undefined {\n return hasGoogleVertexConfiguration()\n ? { apiKey: 'google-application-default-credentials', source: 'gateway' }\n : undefined;\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n return googleVertexProvider(args.modelId, args.headers) as unknown as GatewayLanguageModel;\n }\n}\n\nexport function createGoogleVertexGateway(): GoogleVertexGateway {\n return new GoogleVertexGateway();\n}\n"],"mappings":";;;;AAKA,MAAa,2BAA2B;AAExC,SAAgB,+BAAwC;CACtD,OAAO,QAAQ,QAAQ,IAAI,uBAAuB,KAAK,KAAK,QAAQ,IAAI,wBAAwB,KAAK,CAAC;AACxG;AAEA,SAAS,qBAAqB,SAAiB,SAAkC;CAM/E,OALe,aAAa;EAC1B,SAAS,QAAQ,IAAI,uBAAuB,KAAK;EACjD,UAAU,QAAQ,IAAI,wBAAwB,KAAK;EACnD;CACF,CACY,CAAC,CAAC,OAAO;AACvB;AAEA,IAAa,sBAAb,cAAyC,mBAAmB;CAC1D,KAAc;CACd,OAAgB;CAEhB,eAAwB;EACtB,OAAO,6BAA6B;CACtC;CAEA,MAAM,iBAA0D;EAC9D,MAAM,SAAS,MAAM,4BAA4B;EACjD,OAAO,GACJ,2BAA2B;GAC1B,MAAM;GACN,cAAc;GACd,cAAc;GACd,SAAS,KAAK;GACd,QAAQ,OAAO,KAAI,UAAS,MAAM,EAAE;EACtC,EACF;CACF;CAEA,SAAS,UAAsC,CAE/C;CAEA,MAAM,UAAU,UAAmC;EACjD,OAAO,6BAA6B,IAAI,2CAA2C;CACrF;CAEA,YAAY,UAA6D;EACvE,OAAO,6BAA6B,IAChC;GAAE,QAAQ;GAA0C,QAAQ;EAAU,IACtE,KAAA;CACN;CAEA,qBAAqB,MAOI;EACvB,OAAO,qBAAqB,KAAK,SAAS,KAAK,OAAO;CACxD;AACF;AAEA,SAAgB,4BAAiD;CAC/D,OAAO,IAAI,oBAAoB;AACjC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"google-vertex.d.ts","sourceRoot":"","sources":["../../src/providers/google-vertex.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;CACZ;AAaD,wBAAgB,6BAA6B,IAAI,IAAI,CAGpD;AAiBD,wBAAsB,2BAA2B,IAAI,OAAO,CAAC,sBAAsB,EAAE,CAAC,CAgCrF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"google-vertex.js","names":[],"sources":["../../src/providers/google-vertex.ts"],"sourcesContent":["const MODELS_DEV_API_URL = 'https://models.dev/api.json';\nconst GOOGLE_VERTEX_PROVIDER_ID = 'google-vertex';\nconst CATALOG_TTL_MS = 60 * 60 * 1000;\nconst CATALOG_FAILURE_TTL_MS = 60 * 1000;\nconst CATALOG_FETCH_TIMEOUT_MS = 5_000;\n\nexport interface GoogleVertexModelEntry {\n id: string;\n}\n\nconst GOOGLE_VERTEX_FALLBACK_MODELS: GoogleVertexModelEntry[] = [{ id: 'gemini-3.8-flash' }];\n\ninterface CatalogCacheEntry {\n fetchedAt: number;\n ttl: number;\n models: GoogleVertexModelEntry[];\n}\n\nlet catalogCache: CatalogCacheEntry | null = null;\nlet inflightFetch: Promise<GoogleVertexModelEntry[]> | null = null;\n\nexport function clearGoogleVertexCatalogCache(): void {\n catalogCache = null;\n inflightFetch = null;\n}\n\nasync function fetchGoogleVertexModels(signal: AbortSignal): Promise<GoogleVertexModelEntry[]> {\n const response = await fetch(MODELS_DEV_API_URL, { signal });\n if (!response.ok) {\n throw new Error(`models.dev returned ${response.status}`);\n }\n const data = (await response.json()) as Record<string, { models?: Record<string, unknown> }>;\n const models = Object.keys(data[GOOGLE_VERTEX_PROVIDER_ID]?.models ?? {})\n .sort()\n .map(id => ({ id }));\n if (models.length === 0) {\n throw new Error('models.dev returned no Google Vertex models');\n }\n return models;\n}\n\nexport async function getGoogleVertexModelCatalog(): Promise<GoogleVertexModelEntry[]> {\n const now = Date.now();\n if (catalogCache && now - catalogCache.fetchedAt < catalogCache.ttl) {\n return catalogCache.models;\n }\n if (inflightFetch) return inflightFetch;\n\n inflightFetch = (async () => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);\n try {\n const models = await fetchGoogleVertexModels(controller.signal);\n catalogCache = { fetchedAt: Date.now(), ttl: CATALOG_TTL_MS, models };\n return models;\n } catch (error) {\n catalogCache = {\n fetchedAt: Date.now(),\n ttl: CATALOG_FAILURE_TTL_MS,\n models: GOOGLE_VERTEX_FALLBACK_MODELS,\n };\n console.warn(\n 'Failed to fetch live Google Vertex models, using fallback list:',\n error instanceof Error ? error.message : error,\n );\n return GOOGLE_VERTEX_FALLBACK_MODELS;\n } finally {\n clearTimeout(timer);\n inflightFetch = null;\n }\n })();\n\n return inflightFetch;\n}\n"],"mappings":";AAAA,MAAM,qBAAqB;AAC3B,MAAM,4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{"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AAWzE,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAOD,wBAAgB,yBAAyB,CAAC,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAuC3G;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,KAAK,CASvE;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,eAAe,CAAC,EAAE,eAAe,CAAA;CAAE,GAC/F,iBAAiB,CAYnB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"kimi-coding.js","names":[],"sources":["../../src/providers/kimi-coding.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from '../auth/providers/kimi-coding.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore, OAuthCredential } from '../auth/types.js';\n\nconst PROVIDER_ID = 'kimi-for-coding';\nconst PROVIDER_NAME = 'Kimi For Coding';\nconst INVALID_CREDENTIALS_MESSAGE = `${PROVIDER_NAME} credentials are invalid. Please reconnect the account.`;\n// Pi's provider root is https://api.kimi.com/coding. The AI SDK expects the\n// versioned Anthropic base URL and appends /messages itself.\nconst BASE_URL = 'https://api.kimi.com/coding/v1';\n\nlet authStorageInstance: AuthStorage | null = null;\n\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\nfunction getAuthStorage(): AuthStorage {\n if (!authStorageInstance) authStorageInstance = new AuthStorage();\n return authStorageInstance;\n}\n\nexport function buildKimiCodingOAuthFetch(options: { credentialStore?: CredentialStore } = {}): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const store = options.credentialStore ?? getAuthStorage();\n store.reload();\n const credential = store.get(PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);\n }\n if (!isKimiCodingDeviceId(credential.deviceId)) {\n throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);\n }\n let token: string | undefined;\n let activeCredential: OAuthCredential | undefined = credential;\n if (store.getOAuthCredential) {\n activeCredential = await store.getOAuthCredential(PROVIDER_ID);\n token = activeCredential?.access;\n } else {\n token = await store.getApiKey(PROVIDER_ID);\n store.reload();\n const reloaded = store.get(PROVIDER_ID);\n activeCredential = reloaded?.type === 'oauth' ? { ...reloaded, access: token ?? reloaded.access } : undefined;\n }\n if (!token) throw ProviderAuthRequiredError.signInExpired(PROVIDER_NAME);\n if (!activeCredential || !isKimiCodingDeviceId(activeCredential.deviceId)) {\n throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);\n }\n const deviceHeaders = getKimiCodingDeviceHeaders(activeCredential.deviceId);\n\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${token}`);\n return rejectUnauthorizedResponse(await fetch(input, { ...init, headers }), {\n providerName: PROVIDER_NAME,\n requestUrl: input instanceof URL ? input.toString() : typeof input === 'string' ? input : input.url,\n });\n }) as typeof fetch;\n}\n\nexport function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${apiKey}`);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport function kimiCodingProvider(\n modelId: string,\n options: { apiKey: string; headers?: Record<string, string>; credentialStore?: CredentialStore },\n): MastraModelConfig {\n const usesOAuth = options.credentialStore?.get(PROVIDER_ID)?.type === 'oauth';\n const provider = createAnthropic({\n name: PROVIDER_ID,\n apiKey: 'auth-placeholder',\n baseURL: BASE_URL,\n headers: options.headers,\n fetch: usesOAuth\n ? (buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) as any)\n : (buildKimiCodingApiKeyFetch(options.apiKey) as any),\n });\n return provider(modelId) as unknown as MastraModelConfig;\n}\n"],"mappings":";;;;;AAOA,MAAM,cAAc;AACpB,MAAM,gBAAgB;AACtB,MAAM,8BAA8B,GAAG,cAAc;AAGrD,MAAM,WAAW;AAEjB,IAAI,sBAA0C;AAE9C,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAEA,SAAS,iBAA8B;CACrC,IAAI,CAAC,qBAAqB,sBAAsB,IAAI,YAAY;CAChE,OAAO;AACT;AAEA,SAAgB,0BAA0B,UAAiD,CAAC,GAAiB;CAC3G,QAAQ,OAAO,OAA+B,SAAuC;EACnF,MAAM,QAAQ,QAAQ,mBAAmB,eAAe;EACxD,MAAM,OAAO;EACb,MAAM,aAAa,MAAM,IAAI,WAAW;EACxC,IAAI,CAAC,cAAc,WAAW,SAAS,SACrC,MAAM,0BAA0B,YAAY,aAAa;EAE3D,IAAI,CAAC,qBAAq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BAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAIlE;AAED,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAoBrE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"model-ids.js","names":[],"sources":["../../src/providers/model-ids.ts"],"sourcesContent":["/**\n * Model-id helpers shared by the model gateway and the browser settings\n * module. Kept dependency-free so neither side has to import the other.\n */\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const ANTHROPIC_PREFIX = 'anthropic/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\n\n/** Anthropic's API only accepts dashed ids (`claude-opus-4-6`), but catalogs may list dotted ones. */\nexport function normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\n}\n\n/**\n * The Codex ChatGPT-account endpoint serves some OpenAI models only under a\n * `-codex` id. Applied wherever a model id is sent over Codex OAuth (chat\n * agents and Stagehand alike) so both paths hit the same upstream model.\n */\nconst CODEX_OPENAI_MODEL_REMAPS: Record<string, string> = {\n 'gpt-5.3': 'gpt-5.3-codex',\n 'gpt-5.2': 'gpt-5.2-codex',\n 'gpt-5.1': 'gpt-5.1-codex',\n 'gpt-5.1-mini': 'gpt-5.1-codex-mini',\n 'gpt-5': 'gpt-5-codex',\n};\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\n/**\n * Kimi For Coding subscriptions are served from `api.kimi.com`, which models.dev\n * lists as `kimi-code-plan-cn`. Mastra Code augments that provider with the\n * Kimi OAuth/API-key credential instead of defining its own.\n */\nexport const KIMI_CODING_PROVIDER_ID = 'kimi-code-plan-cn';\n/** Credential id the Kimi login stores accounts under. */\nexport const KIMI_CODING_CREDENTIAL_ID = 'kimi-for-coding';\n\n/** Providers Mastra Code used to catalog as `mastracode/<provider>/<model>`. */\nconst LEGACY_MASTRACODE_NAMESPACED_PROVIDERS = new Set(['amazon-bedrock', 'github-copilot', KIMI_CODING_CREDENTIAL_ID]);\n/** Provider ids Mastra Code defined itself before augmenting the models.dev provider. */\nconst LEGACY_PROVIDER_IDS: Record<string, string> = {\n [KIMI_CODING_CREDENTIAL_ID]: KIMI_CODING_PROVIDER_ID,\n};\n\nexport function normalizeLegacyProviderId(providerId: string): string {\n return LEGACY_PROVIDER_IDS[providerId] ?? providerId;\n}\n\n/**\n * Map model ids saved by older Mastra Code versions (packs, OM settings,\n * thread metadata) to the current catalog id:\n * `mastracode/kimi-for-coding/k3` and `kimi-for-coding/k3` → `kimi-code-plan-cn/k3`,\n * `mastracode/github-copilot/<m>` → `github-copilot/<m>`,\n * `mastracode/amazon-bedrock/<m>` → `amazon-bedrock/<m>`.\n */\nexport function normalizeLegacyModelId(modelId: string): string {\n let normalized = modelId;\n const namespacedProvider = normalized.startsWith('mastracode/') ? normalized.split('/', 3)[1] : undefined;\n if (namespacedProvider && LEGACY_MASTRACODE_NAMESPACED_PROVIDERS.has(namespacedProvider)) {\n normalized = normalized.slice('mastracode/'.length);\n }\n const slash = normalized.indexOf('/');\n if (slash <= 0) return normalized;\n return `${normalizeLegacyProviderId(normalized.slice(0, slash))}${normalized.slice(slash)}`;\n}\n\n/** Credential-store id that authenticates a catalog provider id. */\nexport function getCredentialProviderId(providerId: string): string {\n if (providerId === 'openai') return 'openai-codex';\n if (providerId === KIMI_CODING_PROVIDER_ID) return KIMI_CODING_CREDENTIAL_ID;\n return providerId;\n}\n\nexport function remapOpenAIModelForCodexOAuth(modelId: string): string {\n const normalizedModelId = stripMastraGatewayPrefix(modelId);\n\n if (!normalizedModelId.startsWith(OPENAI_PREFIX)) {\n return modelId;\n }\n\n const openaiModelId = normalizedModelId.substring(OPENAI_PREFIX.length);\n\n if (openaiModelId.includes('-codex')) {\n return modelId;\n }\n\n const codexModelId = CODEX_OPENAI_MODEL_REMAPS[openaiModelId];\n if (!codexModelId) {\n return modelId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F;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAMvF;AAED;;;;;;;;GAQG;AACH,wBAAgB,8BAA8B,CAAC,cAAc,CAAC,EAAE,MAAM,GAAG,uBAAuB,GAAG,SAAS,CAgB3G;AAED;;;;;;;;;GASG;AACH,wBAAgB,+BAA+B,CAC7C,WAAW,EAAE,MAAM,EACnB,eAAe,CAAC,EAAE,MAAM,GACvB,uBAAuB,GAAG,SAAS,CAgBrC;AAyCD;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAkB3D;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CAqEd;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,KAAK,CAuC/E;AAwID;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAA4B,EACrC,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,aAAa,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC3G,iBAAiB,CAuCnB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"openai-codex.js","names":[],"sources":["../../src/providers/openai-codex.ts"],"sourcesContent":["/**\n * OpenAI Codex OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.\n * This allows access to OpenAI models through the ChatGPT OAuth flow.\n *\n * Inspired by opencode's Codex plugin implementation:\n * https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts\n */\n\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { runCatalogThinkingLevel } from '../thinking-catalog.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nexport { supportsMaxReasoningEffort } from '../thinking.js';\n\n// Codex API endpoint (not standard OpenAI API)\nconst CODEX_API_ENDPOINT = 'https://chatgpt.com/backend-api/codex/responses';\nconst CODEX_ORIGINATOR = 'mastracode';\nconst CODEX_USER_AGENT = 'mastracode';\nconst CODEX_PROVIDER_NAME = 'OpenAI Codex';\n\n// Singleton auth storage instance (shared with claude-max.ts)\nlet authStorageInstance: AuthStorage | null = null;\n\n/**\n * Get or create the shared AuthStorage instance\n */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/**\n * Set a custom AuthStorage instance (useful for TUI integration)\n */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n// Default instructions for Codex API (required)\nconst 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.\n\nIMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;\n\nexport type ThinkingLevel = ThinkingLevelSetting;\n\nconst GPT5_MODEL_RE = /^gpt-5(?:\\.|-|$)/;\n\nexport function getEffectiveThinkingLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n // GPT-5.* models on Codex require at least low reasoning.\n const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === 'off' ? 'low' : level;\n return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);\n}\n\n// Map thinkingLevel state values to OpenAI reasoningEffort values.\n// undefined means omit the parameter (no reasoning). Model-dependent fitting\n// happens in getEffectiveThinkingLevel before this lookup.\nexport const THINKING_LEVEL_TO_REASONING_EFFORT: Record<ThinkingLevel, string | undefined> = {\n off: undefined,\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n};\n\n/**\n * Create Codex middleware with the given reasoning effort level.\n */\nexport function createCodexMiddleware(reasoningEffort?: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n // Remove topP if temperature is set (OpenAI doesn't like both)\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n // Codex API requires specific settings via providerOptions\n // Use type assertion to satisfy JSONValue constraints\n params.providerOptions = {\n ...params.providerOptions,\n openai: {\n ...(params.providerOptions?.openai ?? {}),\n instructions: CODEX_INSTRUCTIONS,\n // Codex API requires store to be false\n store: false,\n // Enable reasoning for Codex models — without this, the model\n // skips the reasoning/action phase and goes straight to final_answer,\n // resulting in narration instead of tool calls.\n ...(reasoningEffort ? { reasoningEffort } : {}),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * The thread a model request belongs to, from the `x-thread-id` header that\n * model resolution adds for requests made inside a thread.\n */\nexport function getRequestThreadId(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const name in headers) {\n if (name.toLowerCase() === 'x-thread-id') return headers[name] || undefined;\n }\n return undefined;\n}\n\n/**\n * Create middleware that sends `prompt_cache_key` on OpenAI Responses requests.\n *\n * OpenAI routes a cached prompt by a hash of its start plus this key. Every\n * Mastra Code prompt starts with the same system prompt, so without a key all\n * threads compete for the same cache slot and consecutive steps of one run often\n * land on a machine that doesn't hold their prefix. Keying by thread keeps each\n * thread's requests together. A key the caller already set wins.\n */\nexport function createPromptCacheKeyMiddleware(promptCacheKey?: string): LanguageModelMiddleware | undefined {\n if (!promptCacheKey) return undefined;\n return {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n openai: {\n promptCacheKey,\n ...(params.providerOptions?.openai ?? {}),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Create middleware that forwards a resolved reasoning effort to an\n * OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.\n *\n * Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing\n * (e.g. thinking level `off`), leaving the wire request without a\n * `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not\n * inject Codex-only options (instructions/store); it only sets reasoning\n * effort, keyed by the caller-supplied provider id.\n */\nexport function createReasoningEffortMiddleware(\n providerKey: string,\n reasoningEffort?: string,\n): LanguageModelMiddleware | undefined {\n if (!reasoningEffort) return undefined;\n return {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n [providerKey]: {\n ...(params.providerOptions?.[providerKey] ?? {}),\n reasoningEffort,\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Get a live OAuth bearer token for the Codex OAuth credential.\n *\n * Refreshes the token if it's expired, and returns the credential's\n * accountId alongside the access token. Throws if the user isn't logged in\n * or if the refresh fails.\n *\n * This is the only piece of Codex auth that is genuinely shared between\n * the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand\n * fetch (`buildCodexStagehandFetch`).\n */\nasync function getCodexBearer(\n authStorage?: CredentialStore,\n): Promise<{ accessToken: string; accountId: string | undefined }> {\n const storage = authStorage ?? getAuthStorage();\n storage.reload();\n\n let cred = storage.get('openai-codex');\n if (!cred || cred.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);\n }\n\n if (storage.getOAuthCredential) {\n cred = await storage.getOAuthCredential('openai-codex');\n if (!cred) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);\n } else if (Date.now() >= cred.expires) {\n const refreshedToken = await storage.getApiKey('openai-codex');\n if (!refreshedToken) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);\n storage.reload();\n const reloaded = storage.get('openai-codex');\n if (!reloaded || reloaded.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);\n }\n cred = { ...reloaded, access: refreshedToken };\n }\n\n return { accessToken: cred.access, accountId: (cred as any).accountId as string | undefined };\n}\n\n/**\n * Make a Responses request body safe for Codex's stateless (`store: false`) mode.\n *\n * AI SDK replays earlier output items with their server ids (`rs_…`, `msg_…`,\n * `fc_…`) even when `store` is false. Codex looks those ids up and answers\n * 404 `Item with id 'rs_…' not found` once its short-lived item cache has\n * expired, so every later request in the thread fails the same way. Like the\n * Codex CLI, send items without ids (the encrypted reasoning content carries the\n * reasoning chain) and drop `item_reference`s, which can never resolve.\n */\nexport function stripCodexInputItemIds(body: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return body;\n }\n if (!parsed || typeof parsed !== 'object' || !Array.isArray((parsed as { input?: unknown }).input)) return body;\n const request = parsed as { store?: unknown; input: unknown[] };\n if (request.store !== false) return body;\n\n request.input = request.input.flatMap(item => {\n if (!item || typeof item !== 'object') return [item];\n const { id: _id, ...rest } = item as Record<string, unknown>;\n if (rest.type === 'item_reference') return [];\n return [rest];\n });\n return JSON.stringify(request);\n}\n\n/**\n * Build a fetch function that handles OpenAI Codex OAuth.\n * Preserves non-authorization headers from init.\n * When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions\n * to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the\n * SDK already targets the correct URL.\n */\nexport function buildOpenAICodexOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { accessToken, accountId } = await getCodexBearer(opts.authStorage);\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n\n // Preserve Request headers and let explicit init headers override them.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n if (!headers.has('originator')) {\n headers.set('originator', CODEX_ORIGINATOR);\n }\n if (!headers.has('User-Agent')) {\n headers.set('User-Agent', CODEX_USER_AGENT);\n }\n if (accountId) {\n headers.set('ChatGPT-Account-ID', accountId);\n }\n // Codex CLI sends its session on every request; send the thread the same way.\n const threadId = headers.get('x-thread-id');\n if (threadId) {\n if (!headers.has('session-id')) headers.set('session-id', threadId);\n if (!headers.has('thread-id')) headers.set('thread-id', threadId);\n }\n\n // URL rewriting — only when rewriteUrl !== false\n const parsed = new URL(request.url);\n const shouldRewrite =\n opts.rewriteUrl !== false &&\n (parsed.pathname.includes('/v1/responses') || parsed.pathname.includes('/chat/completions'));\n const finalUrl = shouldRewrite ? new URL(CODEX_API_ENDPOINT) : parsed;\n\n const hasBody = request.method !== 'GET' && request.method !== 'HEAD' && request.body !== null;\n // Only JSON bodies are rewritten; anything else (e.g. multipart uploads) streams through untouched.\n const mediaType = headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();\n const isJson = mediaType === 'application/json';\n let body: RequestInit['body'];\n if (hasBody && isJson) {\n body = stripCodexInputItemIds(await request.text());\n headers.delete('content-length');\n } else if (hasBody) {\n body = request.body!;\n }\n const finalRequest = new Request(finalUrl, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: request.redirect,\n integrity: request.integrity,\n ...(body instanceof ReadableStream ? ({ duplex: 'half' } as RequestInit) : {}),\n });\n try {\n return await rejectUnauthorizedResponse(await fetch(finalRequest), {\n providerName: CODEX_PROVIDER_NAME,\n requestUrl: finalUrl.toString(),\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: finalUrl.toString(),\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Build a fetch function for Stagehand-on-Codex.\n *\n * The Codex backend has two requirements that AI SDK's non-streaming\n * `generateText` path doesn't naturally satisfy:\n *\n * 1. `stream: true` must be set on every request body.\n * 2. The response is delivered as Server-Sent Events; AI SDK's\n * non-streaming code path expects a single JSON body.\n *\n * This fetch forces streaming on the outgoing request, collects the SSE\n * events, and synthesizes the non-streaming JSON shape that\n * `@ai-sdk/openai`'s Responses API parser expects.\n *\n * Headers, OAuth refresh, and URL targeting are handled by the caller via\n * `baseURL` / `headers` on the AI SDK provider; this fetch only injects the\n * live OAuth bearer per call.\n */\nexport function buildCodexStagehandFetch(authStorage: AuthStorage): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n // Refresh + inject the OAuth bearer per call.\n const { accessToken } = await getCodexBearer(authStorage);\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('Accept', 'text/event-stream');\n\n // Stagehand sends JSON; force stream: true while preserving Request bodies.\n let body = await request.clone().text();\n try {\n const parsed = JSON.parse(body) as Record<string, unknown>;\n parsed.stream = true;\n body = JSON.stringify(parsed);\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n } catch {\n // Not JSON; leave as-is.\n }\n\n const upstream = await fetch(\n new Request(request, {\n headers,\n ...(request.method === 'GET' || request.method === 'HEAD' ? {} : { body }),\n }),\n );\n if (!upstream.ok) return upstream;\n\n // Aggregate SSE -> synthesized non-streaming Response\n const aggregated = await aggregateCodexStream(upstream);\n return new Response(aggregated, {\n status: 200,\n headers: { 'content-type': 'application/json' },\n });\n }) as typeof fetch;\n}\n\n/**\n * Read an SSE Response and reduce it to a single JSON string matching the\n * non-streaming OpenAI Responses-API shape.\n *\n * Event vocabulary we care about (per OpenAI Responses API streaming):\n * - response.created → carries `response` object (id, model, usage stub)\n * - response.output_item.added/done → output items (message, reasoning, etc.)\n * - response.output_text.delta → text chunks\n * - response.completed → final `response` snapshot incl. usage\n * - response.error / error → bubble up as a thrown body\n *\n * Reasoning events (`response.reasoning_summary.*`) are intentionally ignored\n * for the non-streaming text response.\n */\nasync function aggregateCodexStream(response: Response): Promise<string> {\n if (!response.body) {\n throw new Error('Codex streaming response had no body');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n\n let finalResponse: any = null;\n let createdResponse: any = null;\n // Track output_items by index so we can rebuild the final array\n const items = new Map<number, any>();\n // Accumulate output_text deltas keyed by item_index + content_index\n const textBuffers = new Map<string, string>();\n\n const handleEvent = (event: { event?: string; data?: string }) => {\n if (!event.data || event.data === '[DONE]') return;\n let payload: any;\n try {\n payload = JSON.parse(event.data);\n } catch {\n return;\n }\n const type: string = payload.type ?? event.event ?? '';\n\n switch (type) {\n case 'response.created': {\n createdResponse = payload.response ?? createdResponse;\n break;\n }\n case 'response.output_item.added': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_item.done': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_text.delta': {\n const key = `${payload.output_index}:${payload.content_index ?? 0}`;\n textBuffers.set(key, (textBuffers.get(key) ?? '') + (payload.delta ?? ''));\n break;\n }\n case 'response.completed': {\n finalResponse = payload.response ?? finalResponse;\n break;\n }\n case 'response.error':\n case 'error': {\n throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);\n }\n default:\n // Ignore reasoning / unknown events\n break;\n }\n };\n\n // SSE parser: events separated by blank line; lines like \"event: x\" / \"data: y\"\n // Normalize CRLF→LF so \\r\\n\\r\\n event boundaries parse correctly (SSE spec allows CRLF).\n const processChunk = (chunk: string) => {\n buffer += chunk.replace(/\\r\\n/g, '\\n');\n let sepIdx: number;\n while ((sepIdx = buffer.indexOf('\\n\\n')) !== -1) {\n const raw = buffer.slice(0, sepIdx);\n buffer = buffer.slice(sepIdx + 2);\n const event: { event?: string; data?: string } = {};\n const dataLines: string[] = [];\n for (const line of raw.split('\\n')) {\n if (line.startsWith('event:')) {\n event.event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length > 0) {\n event.data = dataLines.join('\\n');\n }\n handleEvent(event);\n }\n };\n\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n processChunk(decoder.decode(value, { stream: true }));\n }\n processChunk(decoder.decode());\n } finally {\n reader.releaseLock();\n }\n\n // Stitch accumulated text deltas back into their items\n const base = finalResponse ?? createdResponse ?? { output: [] };\n const finalItems = Array.from(items.entries())\n .sort(([a], [b]) => a - b)\n .map(([index, item]) => {\n // Patch message-type items' content text using buffered deltas\n if (item?.type === 'message' && Array.isArray(item.content)) {\n item.content = item.content.map((c: any, ci: number) => {\n const key = `${index}:${ci}`;\n if (textBuffers.has(key)) {\n return { ...c, text: textBuffers.get(key) };\n }\n return c;\n });\n }\n return item;\n });\n\n base.output = finalItems.length > 0 ? finalItems : (base.output ?? []);\n\n return JSON.stringify(base);\n}\n\n/**\n * Creates an OpenAI model using ChatGPT OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n *\n * IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.\n * URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.\n */\nexport function openaiCodexProvider(\n modelId: string = 'codex-mini-latest',\n options?: { thinkingLevel?: ThinkingLevel; headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const requestedLevel: ThinkingLevel = options?.thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(modelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const headers = options?.headers;\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));\n const middleware = [\n createCodexMiddleware(reasoningEffort),\n ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : []),\n ];\n\n const baseURL = process.env.OPENAI_BASE_URL;\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const openai = createOpenAI({\n apiKey: 'test-api-key',\n baseURL,\n headers,\n });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware,\n });\n }\n\n const openai = createOpenAI({\n apiKey: 'oauth-dummy-key',\n baseURL,\n headers,\n fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Use the responses API for Codex models\n // Wrap with middleware\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAG5B,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAGA,MAAM,qBAAqB;;;AAM3B,MAAM,gBAAgB;AAEtB,SAAgB,0BAA0B,SAAiB,OAAqC;CAE9F,MAAM,iBAAiB,cAAc,KAAK,OAAO,KAAK,UAAU,QAAQ,QAAQ;CAChF,OAAO,wBAAwB,UAAU,WAAW,cAAc;AACpE;AAKA,MAAa,qCAAgF;CAC3F,KAAK,KAAA;CACL,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;AAKA,SAAgB,sBAAsB,iBAAmD;CACvF,OAAO;EACL,sBAAsB;EACtB,iBAAiB,OAAO,EAAE,aAAa;GAErC,IAAI,OAAO,gBAAgB,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AAC;AAK3D,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACnC,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CAClC;AAED,wBAAgB,uBAAuB,CACrC,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE,oBAAoB,GAAG,SAAS,GACtC,uBAAuB,GAAG,SAAS,CAarC;AAmBD,KAAK,kBAAkB,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;AAE3E,wBAAgB,wBAAwB,CAAC,KAAK,SAAS,kBAAkB,EACvE,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAC5C,KAAK,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAS9C;AAED,KAAK,YAAY,GAAG,qBAAqB,CAAC,OAAO,wBAAwB,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9E,KAAK,iBAAiB,GAAG,UAAU,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC7E,KAAK,gBAAgB,GAAG,UAAU,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAC,CAAC;AAEzE,qBAAa,oCAAqC,SAAQ,wBAAwB;;IAGhF,YAAY,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,uBAAuB,GAAG,SAAS,EAG9E;IAEQ,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAEhE;IAEQ,QAAQ,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAE9D;CACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider-thinking.js","names":[],"sources":["../../src/providers/provider-thinking.ts"],"sourcesContent":["import { getModelReasoningOptions, ModelRouterLanguageModel } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { JSONValue } from 'ai';\nimport { requestableReasoningOptions, runThinkingLevel } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { thinkingRequestFormatFor } from './thinking-request.js';\n\ntype ProviderOptions = Record<string, Record<string, JSONValue | undefined>>;\n\nexport interface ProviderThinkingOptions {\n optionsKey: string;\n options: Record<string, JSONValue>;\n controlKeys: ReadonlySet<string>;\n}\n\nexport function providerThinkingOptions(\n routedModelId: string,\n level: ThinkingLevelSetting | undefined,\n): ProviderThinkingOptions | undefined {\n const format = thinkingRequestFormatFor(routedModelId);\n if (!format || !level) return undefined;\n const catalogOptions = getModelReasoningOptions(routedModelId);\n const requestable = requestableReasoningOptions(routedModelId, catalogOptions);\n const runLevel = runThinkingLevel(routedModelId, level, catalogOptions);\n if (!requestable?.length || runLevel === 'off') return undefined;\n const effortOptions = format.sendEffort?.(runLevel);\n const sendsEffort = requestable.some(option => option.type === 'effort');\n const options = sendsEffort ? effortOptions : format.enableThinking;\n if (!options) return undefined;\n const controlKeys = new Set([...Object.keys(effortOptions ?? {}), ...Object.keys(format.enableThinking ?? {})]);\n return { optionsKey: format.optionsKey, options, controlKeys };\n}\n\nfunction withThinkingOptions<CallOptions extends { providerOptions?: ProviderOptions }>(\n callOptions: CallOptions,\n thinking: ProviderThinkingOptions | undefined,\n): CallOptions {\n if (!thinking) return callOptions;\n const callerOptions = callOptions.providerOptions?.[thinking.optionsKey] ?? {};\n const callerSetThinking = Object.keys(callerOptions).some(key => thinking.controlKeys.has(key));\n if (callerSetThinking) return callOptions;\n return {\n ...callOptions,\n providerOptions: {\n ...callOptions.providerOptions,\n [thinking.optionsKey]: { ...callerOptions, ...thinking.options },\n },\n };\n}\n\ntype AiSdkLanguageModel = Parameters<typeof wrapLanguageModel>[0]['model'];\n\nexport function withThinkingOptionsModel<Model extends AiSdkLanguageModel>(\n model: Model,\n thinking: ProviderThinkingOptions | undefined,\n): Model | ReturnType<typeof wrapLanguageModel> {\n if (!thinking) return model;\n return wrapLanguageModel({\n model,\n middleware: {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => withThinkingOptions(params, thinking),\n },\n });\n}\n\ntype RouterConfig = ConstructorParameters<typeof ModelRouterLanguageModel>[0];\ntype RouterCallOptions = Parameters<ModelRouterLanguageModel['doStream']>[0];\ntype RouterCallResult = ReturnType<ModelRouterLanguageModel['doStream']>;\n\nexport class ModelRouterLanguageModelWithThinking extends ModelRouterLanguageModel {\n readonly #thinking: ProviderThinkingOptions | undefined;\n\n constructor(config: RouterConfig, thinking: ProviderThinkingOptions | undefined) {\n super(config);\n this.#thinking = thinking;\n }\n\n override doGenerate(options: RouterCallOptions): RouterCallResult {\n return super.doGenerate(withThinkingOptions(options, this.#thinking));\n }\n\n override doStream(options: RouterCallOptions): RouterCallResult {\n return super.doStream(withThinkingOptions(options, this.#thinking));\n }\n}\n"],"mappings":";;;;;AAeA,SAAgB,wBACd,eACA,OACqC;CACrC,MAAM,SAAS,yBAAyB,aAAa;CACrD,IAAI,CAAC,UAAU,CAAC,OAAO,OAAO,KAAA;CAC9B,MAAM,iBAAiB,yBAAyB,aAAa;CAC7D,MAAM,cAAc,4BAA4B,eAAe,cAAc;CAC7E,MAAM,WAAW,iBAAiB,eAAe,OAAO,cAAc;CACtE,IAAI,CAAC,aAAa,UAAU,aAAa,OAAO,OAAO,KAAA;CACvD,MAAM,gBAAgB,OAAO,aAAa,QAAQ;CAElD,MAAM,UADc,YAAY,MAAK,WAAU,OAAO,SAAS,QACrC,IAAI,gBAAgB,OAAO;CACrD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,8BAAc,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,iBAAiB,CAAC,CAAC,GAAG,GAAG,OAAO,KAAK,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC;CAC9G,OAAO;EAAE,YAAY,OAAO;EAAY;EAAS;CAAY;AAC/D;AAEA,SAAS,oBACP,aACA,UACa;CACb,IAAI,CAAC,UAAU,OAA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AE,uBAAuB,CAAC;CAC1C;AAyCD,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEnE;AASD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAGhE;AAED,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,qBAAqB,GAAG,SAAS,CAM3F"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"thinking-request.js","names":[],"sources":["../../src/providers/thinking-request.ts"],"sourcesContent":["import type { JSONValue } from 'ai';\nimport type { ActiveThinkingLevel } from '../thinking.js';\nimport { MASTRA_GATEWAY_PREFIX, stripMastraGatewayPrefix } from './model-ids.js';\n\ntype ThinkingProviderOptions = Record<string, JSONValue>;\n\nexport interface ThinkingRequestFormat {\n optionsKey: string;\n sendEffort?: (effort: ActiveThinkingLevel) => ThinkingProviderOptions;\n acceptedEfforts?: readonly ActiveThinkingLevel[];\n enableThinking?: ThinkingProviderOptions;\n}\n\nconst LOW_TO_HIGH: readonly ActiveThinkingLevel[] = ['low', 'medium', 'high'];\nconst sendReasoningEffort = (reasoningEffort: ActiveThinkingLevel): ThinkingProviderOptions => ({ reasoningEffort });\nconst ENABLE_REASONING: ThinkingProviderOptions = { reasoning: { enabled: true } };\n\nconst OPENROUTER_FORMAT: ThinkingRequestFormat = {\n optionsKey: 'openrouter',\n sendEffort: effort => ({ reasoning: { effort } }),\n enableThinking: ENABLE_REASONING,\n};\n\nconst REQUEST_FORMATS_BY_PROVIDER: Partial<Record<string, ThinkingRequestFormat>> = {\n deepseek: {\n optionsKey: 'deepseek',\n sendEffort: sendReasoningEffort,\n enableThinking: { thinking: { type: 'enabled' } },\n },\n openrouter: OPENROUTER_FORMAT,\n alibaba: { optionsKey: 'alibaba', enableThinking: { enableThinking: true } },\n groq: { optionsKey: 'groq', sendEffort: sendReasoningEffort, acceptedEfforts: LOW_TO_HIGH },\n mistral: { optionsKey: 'mistral', sendEffort: sendReasoningEffort, acceptedEfforts: ['high'] },\n xai: { optionsKey: 'xai', sendEffort: sendReasoningEffort, acceptedEfforts: [...LOW_TO_HIGH, 'xhigh'] },\n togetherai: {\n optionsKey: 'togetherai',\n sendEffort: sendReasoningEffort,\n acceptedEfforts: LOW_TO_HIGH,\n enableThinking: ENABLE_REASONING,\n },\n deepinfra: {\n optionsKey: 'deepinfra',\n sendEffort: sendReasoningEffort,\n acceptedEfforts: LOW_TO_HIGH,\n enableThinking: ENABLE_REASONING,\n },\n cerebras: { optionsKey: 'cerebras', sendEffort: sendReasoningEffort },\n perplexity: { optionsKey: 'perplexity', sendEffort: effort => ({ reasoning_effort: effort }) },\n};\n\nconst THINKING_ADAPTER_PROVIDERS: ReadonlySet<string> = new Set(['anthropic', 'openai', 'google']);\n\nexport function isThinkingAdapterProvider(provider: string): boolean {\n return THINKING_ADAPTER_PROVIDERS.has(provider);\n}\n\nconst PROVIDERS_ROUTED_WITHOUT_THINKING: ReadonlySet<string> = new Set([\n 'github-copilot',\n 'kimi-for-coding',\n 'moonshotai',\n 'amazon-bedrock',\n]);\n\nexport function isRoutedWithoutThinking(modelId: string): boolean {\n const [provider = ''] = stripMastraGatewayPrefix(modelId).split('/');\n return PROVIDERS_ROUTED_WITHOUT_THINKING.has(provider);\n}\n\nexport function thinkingRequestFormatFor(modelId: string): ThinkingRequestFormat | undefined {\n const routedThroughMastraGateway = modelId.startsWith(MASTRA_GATEWAY_PREFIX);\n const [provider = ''] = stripMastraGatewayPrefix(modelId).split('/');\n if (isThinkingAdapterProvider(provider)) return undefined;\n if (routedThroughMastraGateway) return OPENROUTER_FORMAT;\n return REQUEST_FORMATS_BY_PROVIDER[provider.includes('alibaba') ? 'alibaba' : provider];\n}\n"],"mappings":";;AAaA,MAAM,cAA8C;CAAC;CAAO;CAAU;AAAM;AAC5E,MAAM,uBAAuB,qBAAmE,EAAE,gBAAgB;AAClH,MAAM,mBAA4C,EAAE,WAAW,EAAE,SAAS,KAAK,EAAE;AAEjF,MAAM,oBAA2C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AA0B,QAAQ,GAAG,OAAO,KAAA;CAChD,IAAI,4BAA4B,OAAO;CACvC,OAAO,4BAA4B,SAAS,SAAS,SAAS,IAAI,YAAY;AAChF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../src/providers/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AASxD,qDAAqD;AACrD,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAuC7F;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC5E,UAAU,CAAC,wBAAwB,CAAC,WAAW,CAAC,CAAC,CASnD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"xai.js","names":[],"sources":["../../src/providers/xai.ts"],"sourcesContent":["/**\n * xAI (Grok) OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with the xAI API.\n * The xAI API speaks an OpenAI-compatible chat format, and the OAuth access\n * token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`\n * into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)\n * access token.\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\n\nconst XAI_PROVIDER_ID = 'xai';\nconst XAI_PROVIDER_NAME = 'xAI';\nconst XAI_BASE_URL = 'https://api.x.ai/v1';\n\n// Singleton auth storage instance (shared with claude-max.ts / github-copilot.ts when not overridden).\nlet authStorageInstance: AuthStorage | null = null;\n\n/** Get or create the shared AuthStorage instance. */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Build a fetch wrapper that authenticates with xAI OAuth.\n * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,\n * preserving non-auth headers from the caller.\n */\nexport function buildXAIOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get(XAI_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(XAI_PROVIDER_NAME);\n }\n\n // getApiKey() refreshes the access token if it has expired.\n const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);\n if (!accessToken) throw ProviderAuthRequiredError.signInExpired(XAI_PROVIDER_NAME);\n\n // Preserve existing headers, strip auth-related ones. Explicit init\n // headers override headers carried by an incoming Request.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) {\n new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n }\n headers.delete('authorization');\n headers.delete('x-api-key');\n\n headers.set('Authorization', `Bearer ${accessToken}`);\n\n try {\n return await rejectUnauthorizedResponse(await fetch(url, { ...init, headers }), {\n providerName: XAI_PROVIDER_NAME,\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an xAI model using OAuth authentication.\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed).\n */\nexport function xaiProvider(\n modelId: string,\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): ReturnType<OpenAICompatibleProvider['chatModel']> {\n const provider = createOpenAICompatible({\n name: XAI_PROVIDER_ID,\n baseURL: XAI_BASE_URL,\n apiKey: 'oauth-placeholder', // real auth injected by the custom fetch\n headers: options?.headers,\n fetch: buildXAIOAuthFetch({ authStorage: options?.authStorage }),\n });\n return provider.chatModel(modelId);\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AAGrB,IAAI,sBAA0C;;AAG9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;AAGA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;;AAOA,SAAgB,mBAAmB,OAA0C,CAAC,GAAiB;CAC7F,QAAQ,OAAO,KAA6B,SAAuC;EACjF,MAAM,UAAU,KAAK,eAAe,eAAe;EACnD,QAAQ,OAAO;EAEf,MAAM,OAAO,QAAQ,IAAI,eAAe;EACxC,IAAI,CAAC,QAAQ,KAAK,SAAS,SACzB,MAAM,0BAA0B,YAAY,iBAAiB;EAI/D,MAAM,cAAc,MAAM,QAAQ,UAAU,eAAe;EAC3D,IAAI,CAAC,aAAa,MAAM,0BAA0B,cAAc,iBAAiB;EAIjF,MAAM,UAAU,IAAI,QAA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+0,0 @@
1
- {"version":3,"file":"interval.js","names":[],"sources":["../../src/schedules/interval.ts"],"sourcesContent":["/**\n * Interval parsing and fire-time math for `/schedules`.\n *\n * Users type `5m`, `2h`, `1 day`. Schedules fire on local wall-clock\n * boundaries (5m fires at :00, :05, ...), so only intervals that divide the\n * hour (minutes) or the day (hours) give a stable cadence; anything else is\n * rejected with the nearest valid suggestion instead of silently drifting.\n */\n\nconst SECOND_MS = 1_000;\nconst MINUTE_MS = 60 * SECOND_MS;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\nexport type ParsedInterval = { ms: number; label: string };\nexport type IntervalError = { error: string };\n\nconst UNIT_MS: Record<string, { ms: number; short: string }> = {\n s: { ms: SECOND_MS, short: 's' },\n sec: { ms: SECOND_MS, short: 's' },\n secs: { ms: SECOND_MS, short: 's' },\n second: { ms: SECOND_MS, short: 's' },\n seconds: { ms: SECOND_MS, short: 's' },\n m: { ms: MINUTE_MS, short: 'm' },\n min: { ms: MINUTE_MS, short: 'm' },\n mins: { ms: MINUTE_MS, short: 'm' },\n minute: { ms: MINUTE_MS, short: 'm' },\n minutes: { ms: MINUTE_MS, short: 'm' },\n h: { ms: HOUR_MS, short: 'h' },\n hr: { ms: HOUR_MS, short: 'h' },\n hrs: { ms: HOUR_MS, short: 'h' },\n hour: { ms: HOUR_MS, short: 'h' },\n hours: { ms: HOUR_MS, short: 'h' },\n d: { ms: DAY_MS, short: 'd' },\n day: { ms: DAY_MS, short: 'd' },\n days: { ms: DAY_MS, short: 'd' },\n};\n\nconst INTERVAL_RE = /^(\\d+)\\s*([a-z]+)$/i;\n\n/** Parse `5m`, `2h`, `1 day`, `90 minutes` into milliseconds plus a normalized label. */\nexport function parseInterval(text: string): ParsedInterval | IntervalError {\n const match = INTERVAL_RE.exec(text.trim());\n if (!match) {\n return { error: `Invalid interval \"${text}\". Use a number followed by a unit, e.g. 5m, 2h, 1d.` };\n }\n const value = Number(match[1]);\n const unit = UNIT_MS[match[2]!.toLowerCase()];\n if (!unit) {\n return { error: `Unknown interval unit \"${match[2]}\". Use s, m, h, or d.` };\n }\n if (value <= 0) {\n return { error: 'Interval must be greater than zero.' };\n }\n return { ms: value * unit.ms, label: `${value}${unit.short}` };\n}\n\nexport type IntervalCheck = { ok: true } | { error: string; suggestion?: string };\n\nconst MINUTE_DIVISORS = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60];\nconst HOUR_DIVISORS = [1, 2, 3, 4, 6, 8, 12, 24];\n\nfunction nearest(candidates: number[], target: number): number {\n return candidates.reduce((best, candidate) =>\n Math.abs(candidate - target) < Math.abs(best - target) ? candidate : best,\n );\n}\n\n/**\n * Check that an interval fires on stable clock boundaries: whole minutes that\n * divide the hour, whole hours that divide the day, or exactly one day.\n */\nexport function validateInterval({ ms }: { ms: number }): IntervalCheck {\n if (ms < MINUTE_MS) {\n return { error: 'Schedules fire at most once per minute.', suggestion: '1m' };\n }\n if (ms % MINUTE_MS !== 0) {\n const minutes = Math.round(ms / MINUTE_MS);\n return {\n error: 'Interval must be a whole number of minutes.',\n suggestion: `${Math.max(1, nearest(MINUTE_DIVISORS, minutes))}m`,\n };\n }\n const minutes = ms / MINUTE_MS;\n if (minutes < 60) {\n if (60 % minutes === 0) {\n return { ok: true };\n }\n return {\n error: `${minutes}m does not divide an hour evenly.`,\n suggestion: `${nearest(MINUTE_DIVISORS, minutes)}m`,\n };\n }\n if (minutes % 60 !== 0) {\n const hours = Math.round(minutes / 60);\n return {\n error: `${minutes}m is not a whole number of hours.`,\n suggestion: hours < 24 ? `${nearest(HOUR_DIVISORS, hours)}h` : '1d',\n };\n }\n const hours = minutes / 60;\n if (hours < 24) {\n if (24 % hours === 0) {\n return { ok: true };\n }\n return {\n error: `${hours}h does not divide a day evenly.`,\n suggestion: `${nearest(HOUR_DIVISORS, hours)}h`,\n };\n }\n if (hours === 24) {\n return { ok: true };\n }\n return {\n error: 'Intervals longer than one day are not supported.',\n suggestion: '1d',\n };\n}\n\n/** Hour-and-longer cadences: which local wall-clock slot a minute belongs to. */\nfunction hourSlotKey(date: Date, stepHours: number): number {\n return (\n ((date.getFullYear() * 12 + date.getMonth()) * 31 + date.getDate()) * 24 +\n Math.floor(date.getHours() / stepHours) * stepHours\n );\n}\n\n/**\n * The first boundary strictly after `after`, on the local wall clock\n * (5m → :00, :05, ...; 2h → 00:00, 02:00, ...; 1d → midnight). `intervalMs`\n * must pass {@link validateInterval}.\n *\n * Around daylight-saving changes this behaves like cron:\n * - Sub-hour cadences follow the minute hand, so they keep firing every N real\n * minutes through both the skipped and the repeated hour. Across a\n * half-hour change, the gap between fires never exceeds the interval.\n * - Hourly and daily cadences fire once per wall-clock slot. A boundary that\n * falls in a skipped hour fires at the first minute after the jump (02:00 →\n * 03:00), and a repeated hour does not fire a second time.\n *\n * Computing from `after` rather than from the previous fire means a late\n * timer (sleep, busy event loop) skips missed boundaries instead of bursting\n * to catch up.\n */\nexport function nextFireTime(intervalMs: number, after: number): number {\n // Truncate in UTC: local setters resolve a repeated hour to its first occurrence.\n const cursor = new Date(Math.floor(after / MINUTE_MS) * MINUTE_MS);\n const stepMinutes = intervalMs / MINUTE_MS;\n // Walk minute by minute: at most an hour for sub-hour cadences, ~a day otherwise.\n if (stepMinutes < 60) {\n // Never wait longer than one interval: a half-hour clock change (Lord Howe\n // Island) can otherwise shift the minute hand past the next boundary.\n const latest = cursor.getTime() + intervalMs;\n do cursor.setTime(cursor.getTime() + MINUTE_MS);\n while (cursor.getMinutes() % stepMinutes !== 0 && cursor.getTime() < latest);\n return cursor.getTime();\n }\n const stepHours = stepMinutes / 60;\n const startSlot = hourSlotKey(new Date(after), stepHours);\n do cursor.setTime(cursor.getTime() + MINUTE_MS);\n while (hourSlotKey(cursor, stepHours) <= startSlot);\n return cursor.getTime();\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,YAAY;AAClB,MAAM,YAAY,KAAK;AACvB,MAAM,UAAU,KAAK;AACrB,MAAM,SAAS,KAAK;AA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E,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;AAEhH;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnE,MAAM,MAAM,qBAAqB,GAAG;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,SAAS,CAAC;IACrB,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAChD,CAAC;AAMF,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,GAAG,MAAM,CAMpF;AAMD,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,MAAM,GAAG,aAAa,CAAC,EAC7D,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,eAAe,CAAC,CAmB1B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"prompt.js","names":[],"sources":["../../src/schedules/prompt.ts"],"sourcesContent":["/**\n * Fire-time prompt assembly for Mastra Code schedules.\n *\n * File-backed schedules only hold a descriptor; each fire runs the script or\n * re-reads the file so the model always sees current output. Failures become\n * the prompt text rather than a skipped fire — a schedule that silently stops\n * delivering is worse than one that reports \"the script broke\".\n */\nimport type { ThreadSchedule } from './scheduler.js';\n\nexport const SCRIPT_TIMEOUT_MS = 60_000;\n\nexport type ScriptResult = { stdout: string; stderr: string; exitCode: number | null };\n\nexport type RunScript = (absPath: string, options: { cwd: string; timeoutMs: number }) => Promise<ScriptResult>;\n\n/**\n * One fire's prompt. `outcome` summarizes a file-backed fire for the\n * transcript header: `exit 0`, `exit 3`, `killed` (timeout/signal), or\n * `failed` (the file could not be run or read).\n */\nexport type AssembledPrompt = { prompt: string; outcome?: string };\n\nexport type AssemblePromptOptions = {\n cwd: string;\n runScript: RunScript;\n readFile: (absPath: string) => Promise<string>;\n};\n\nfunction appendExtra(text: string, extra: string | undefined): string {\n return extra ? `${text}\\n\\n${extra}` : text;\n}\n\nexport function formatScriptOutput(displayPath: string, result: ScriptResult): string {\n const body = [result.stdout, result.stderr]\n .map(part => part.trimEnd())\n .filter(Boolean)\n .join('\\n');\n return `Output of ${displayPath} (exit ${result.exitCode ?? 'null'}):\\n${body || '(no output)'}`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport async function assembleSchedulePrompt(\n spec: Pick<ThreadSchedule, 'prompt' | 'file' | 'extraPrompt'>,\n options: AssemblePromptOptions,\n): Promise<AssembledPrompt> {\n const { file } = spec;\n if (!file) return { prompt: spec.prompt ?? '' };\n\n let text: string;\n let outcome: string | undefined;\n try {\n if (file.mode === 'script') {\n const result = await options.runScript(file.path, { cwd: options.cwd, timeoutMs: SCRIPT_TIMEOUT_MS });\n text = formatScriptOutput(file.displayPath, result);\n outcome = result.exitCode === null ? 'killed' : `exit ${result.exitCode}`;\n } else {\n text = (await options.readFile(file.path)).trim();\n }\n } catch (error) {\n text = `Schedule ${file.displayPath} failed: ${errorMessage(error)}`;\n outcome = 'failed';\n }\n return { prompt: appendExtra(text, spec.extraPrompt), ...(outcome ? { outcome } : {}) };\n}\n"],"mappings":";AAUA,MAAa,oBAAoB;AAmBjC,SAAS,YAAY,MAAc,OAAmC;CACpE,OAAO,QAAQ,GAAG,KAAK,MAAM,UAAU;AACzC;AAEA,SAAgB,mBAAmB,aAAqB,QAA8B;CACpF,MAAM,OAAO,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC,CACxC,KAAI,SAAQ,KAAK,QAAQ,CAAC,CAAC,CAC3B,OAAO,OAAO,CAAC,CACf,KAAK,IAAI;CACZ,OAAO,aAAa,YAAY,SAAS,OAAO,YAAY,OAAO,MAAM,QAAQ;AACnF;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,eAAsB,uBACpB,MACA,SAC0B;CAC1B,MAAM,EAAE,SAAS;CACjB,IAAI,CAAC,MAAM,OAAO,EAAE,QAAQ,KAAK,UAAU,GAAG;CAE9C,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,IAAI,KAAK,SAAS,UAAU;GAC1B,MAAM,SAAS,MAAM,QAAQ,UAAU,KAAK,MAAM;IAAE,KAAK,QAAQ;IAAK,WAAW;GAAkB,CAAC;GACpG,OAAO,mBAAmB,KAAK,aAAa,MAAM;GAClD,UAAU,OAAO,aAAa,OAAO,WAAW,QAAQ,OAAO;EACjE,OACE,QAAQ,MAAM,QAAQ,SAAS,KAAK,IAAI,EAAA,CAAG,KAAK;CAEpD,SAAS,OAAO;EACd,OAAO,YAAY,KAAK,YAAY,WAAW,aAAa,KAAK;EACjE,UAAU;CACZ;CACA,OAAO;EAAE,QAAQ,YAAY,MAAM,KAAK,WAAW;EAAG,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;CAAG;AACxF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-script.d.ts","sourceRoot":"","sources":["../../src/schedules/run-script.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,SAAS,EAAgB,MAAM,aAAa,CAAC;AAc3D,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAOzD;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAOzF;AAED,eAAO,MAAM,SAAS,EAAE,SAyBvB,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-script.js","names":["fs","path"],"sources":["../../src/schedules/run-script.ts"],"sourcesContent":["/**\n * Runs a schedule's script file at fire time.\n *\n * The file path is always passed as the literal command (or as the single\n * argument to a fixed interpreter) — never through a shell string — so the\n * user's extra prompt can never be interpolated into a command line.\n */\nimport { execFile } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { RunScript, ScriptResult } from './prompt.js';\n\n/** Interpreter for scripts that lack an executable bit, keyed by extension. */\nconst INTERPRETERS: Record<string, () => string> = {\n '.sh': () => '/bin/sh',\n '.js': () => process.execPath,\n '.mjs': () => process.execPath,\n '.cjs': () => process.execPath,\n '.ts': () => process.execPath,\n '.py': () => 'python3',\n};\n\nconst MAX_OUTPUT_BYTES = 1024 * 1024;\n\nexport function isExecutableFile(absPath: string): boolean {\n try {\n fs.accessSync(absPath, fs.constants.X_OK);\n return fs.statSync(absPath).isFile();\n } catch {\n return false;\n }\n}\n\nexport function resolveScriptCommand(absPath: string): { command: string; args: string[] } {\n if (isExecutableFile(absPath)) return { command: absPath, args: [] };\n const interpreter = INTERPRETERS[path.extname(absPath).toLowerCase()];\n if (!interpreter) {\n throw new Error(`${absPath} is not executable and has no known interpreter`);\n }\n return { command: interpreter(), args: [absPath] };\n}\n\nexport const runScript: RunScript = async (absPath, { cwd, timeoutMs }) => {\n const { command, args } = resolveScriptCommand(absPath);\n return new Promise<ScriptResult>((resolve, reject) => {\n execFile(\n command,\n args,\n { cwd, timeout: timeoutMs, maxBuffer: MAX_OUTPUT_BYTES, windowsHide: true },\n (error, stdout, stderr) => {\n if (!error) {\n resolve({ stdout, stderr, exitCode: 0 });\n return;\n }\n const spawnError = error as NodeJS.ErrnoException & { code?: number | string; killed?: boolean };\n if (typeof spawnError.code === 'number') {\n resolve({ stdout, stderr, exitCode: spawnError.code });\n return;\n }\n if (spawnError.killed) {\n resolve({ stdout, stderr: `${stderr}\\n[timed out after ${timeoutMs}ms]`.trim(), exitCode: null });\n return;\n }\n reject(error);\n },\n );\n });\n};\n"],"mappings":";;;;;;;;;;;;AAaA,MAAM,eAA6C;CACjD,aAAa;CACb,aAAa,QAAQ;CACrB,cAAc,QAAQ;CACtB,cAAc,QAAQ;CACtB,aAAa,QAAQ;CACrB,aAAa;AACf;AAEA,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M,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAOhD;IAED,wDAAwD;IACxD,IAAI,IAAI,IAAI,CAGX;CA0CF;AAED,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,gHAAgH;AAChH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,MAAM,GAAG,aAAa,CAAC,GAAG,MAAM,CAMhH;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,cAAc,EACxB,SAAS,GAAE,IAAI,CAAC,eAAe,EAAE,SAAS,CAAM,GAC/C,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CASxB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scheduler.js","names":[],"sources":["../../src/schedules/scheduler.ts"],"sourcesContent":["/**\n * Process-local scheduler behind `/schedules`.\n *\n * Schedules live only in this process: timers fire them and they die with it.\n * Nothing is written to shared storage, so other Mastra Code processes on the\n * same database never see — or fire — this session's schedules.\n */\nimport { randomUUID } from 'node:crypto';\nimport { nextFireTime, validateInterval } from './interval.js';\nimport type { ParsedInterval } from './interval.js';\nimport type { AssembledPrompt } from './prompt.js';\n\n/** `source` attribute on fired signals; the TUI labels these turns `schedule`. */\nexport const SCHEDULE_SIGNAL_SOURCE = 'schedule';\n\n/** When a schedule fires. Only recurring `every` triggers exist today. */\nexport type ScheduleTrigger = { kind: 'every'; interval: ParsedInterval };\n\n/** A file a schedule runs as a script, or re-reads and sends as the prompt, on every fire. */\nexport type ScheduleFile = { path: string; displayPath: string; mode: 'script' | 'prompt' };\n\n/** What to send on each fire: `prompt` text, or a `file` (plus `extraPrompt` appended after it). */\nexport type ThreadScheduleSource = { prompt: string } | { file: ScheduleFile; extraPrompt?: string };\n\nexport type ThreadScheduleSpec = ThreadScheduleSource & {\n trigger: ScheduleTrigger;\n /** Who is creating it: the user via `/schedules`, or the agent via its schedule tools. Defaults to `user`. */\n createdBy?: 'user' | 'agent';\n};\n\nexport type ThreadSchedule = {\n id: string;\n threadId: string;\n resourceId: string;\n trigger: ScheduleTrigger;\n prompt?: string;\n file?: ScheduleFile;\n extraPrompt?: string;\n createdBy: 'user' | 'agent';\n status: 'active' | 'paused';\n /** Next boundary this schedule fires at; only meaningful while active. */\n nextFireAt: number;\n createdAt: number;\n};\n\nexport type ThreadSchedulerOptions = {\n /** Build the prompt for one fire (runs scripts / reads files). */\n assemblePrompt: (schedule: ThreadSchedule) => Promise<AssembledPrompt>;\n /** Hand the prompt to the agent for the schedule's thread. */\n deliver: (schedule: ThreadSchedule, assembled: AssembledPrompt) => Promise<void>;\n /** A fire failed before reaching the agent. */\n onError?: (error: unknown, schedule: ThreadSchedule) => void;\n now?: () => number;\n};\n\n/** How late a timer may run before its fire counts as missed (sleep, stalled event loop). */\nexport const LATE_FIRE_GRACE_MS = 60_000;\n\n/**\n * Outcome of a manual `run()`. `failed` means nothing reached the agent: the\n * prompt could not be built or the agent refused it.\n */\nexport type ScheduleRunResult =\n | { status: 'fired' }\n | { status: 'failed'; error: unknown }\n | { status: 'busy' }\n | { status: 'not-found' };\n\ntype FireOutcome = { kind: 'delivered' } | { kind: 'deleted' } | { kind: 'failed'; error: unknown };\n\ntype Entry = { schedule: ThreadSchedule; timer?: ReturnType<typeof setTimeout>; inFlight: number };\n\nexport class ThreadScheduler {\n #entries = new Map<string, Entry>();\n #options: ThreadSchedulerOptions;\n\n constructor(options: ThreadSchedulerOptions) {\n this.#options = options;\n }\n\n #now(): number {\n return this.#options.now?.() ?? Date.now();\n }\n\n /** Throws when the interval is not a supported wall-clock cadence (see `validateInterval`) or the prompt is empty. */\n create(spec: ThreadScheduleSpec, target: { threadId: string; resourceId: string }): ThreadSchedule {\n const { interval } = spec.trigger;\n const check = validateInterval(interval);\n if ('error' in check) {\n throw new Error(\n `Invalid schedule interval: ${check.error}${check.suggestion ? ` Try ${check.suggestion}.` : ''}`,\n );\n }\n if ('prompt' in spec && !spec.prompt.trim()) throw new Error('Schedule prompt is empty.');\n const now = this.#now();\n const schedule: ThreadSchedule = {\n id: randomUUID(),\n threadId: target.threadId,\n resourceId: target.resourceId,\n trigger: { kind: 'every', interval: { ...interval } },\n ...('file' in spec\n ? { file: { ...spec.file }, ...(spec.extraPrompt ? { extraPrompt: spec.extraPrompt } : {}) }\n : { prompt: spec.prompt }),\n createdBy: spec.createdBy ?? 'user',\n status: 'active',\n nextFireAt: nextFireTime(interval.ms, now),\n createdAt: now,\n };\n const entry: Entry = { schedule, inFlight: 0 };\n this.#entries.set(schedule.id, entry);\n this.#arm(entry);\n return { ...schedule };\n }\n\n list(filter: { threadId?: string } = {}): ThreadSchedule[] {\n return [...this.#entries.values()]\n .map(entry => ({ ...entry.schedule }))\n .filter(schedule => !filter.threadId || schedule.threadId === filter.threadId)\n .sort((a, b) => a.createdAt - b.createdAt);\n }\n\n delete(id: string): boolean {\n const entry = this.#entries.get(id);\n if (!entry) return false;\n clearTimeout(entry.timer);\n this.#entries.delete(id);\n return true;\n }\n\n pause(id: string): boolean {\n const entry = this.#entries.get(id);\n if (!entry) return false;\n clearTimeout(entry.timer);\n entry.timer = undefined;\n entry.schedule.status = 'paused';\n return true;\n }\n\n resume(id: string): boolean {\n const entry = this.#entries.get(id);\n if (!entry) return false;\n if (entry.schedule.status === 'active') return true;\n entry.schedule.status = 'active';\n entry.schedule.nextFireAt = nextFireTime(entry.schedule.trigger.interval.ms, this.#now());\n this.#arm(entry);\n return true;\n }\n\n /** Whether a fire of this schedule (timer or manual) is still assembling or delivering. */\n isFiring(id: string): boolean {\n return (this.#entries.get(id)?.inFlight ?? 0) > 0;\n }\n\n /**\n * Fire once now, outside the cadence. Returns `busy` without firing when a\n * fire of this schedule is still running (a slow script, say), so the same\n * script never runs twice at once. Resolves once the fire finished; a fire\n * that never reached the agent resolves `failed` instead of calling `onError`.\n */\n async run(id: string): Promise<ScheduleRunResult> {\n const entry = this.#entries.get(id);\n if (!entry) return { status: 'not-found' };\n if (entry.inFlight > 0) return { status: 'busy' };\n const result = await this.#fire(entry);\n if (result.kind === 'failed') return { status: 'failed', error: result.error };\n return result.kind === 'delivered' ? { status: 'fired' } : { status: 'not-found' };\n }\n\n /** Drop every schedule and timer (process shutdown). */\n stop(): void {\n for (const entry of this.#entries.values()) clearTimeout(entry.timer);\n this.#entries.clear();\n }\n\n #arm(entry: Entry): void {\n clearTimeout(entry.timer);\n const scheduledAt = entry.schedule.nextFireAt;\n entry.timer = setTimeout(\n () => {\n if (this.#entries.get(entry.schedule.id) !== entry || entry.schedule.status !== 'active') return;\n // Timers can fire a hair early; step from the later of now and the\n // intended boundary so the same boundary is never fired twice.\n const now = this.#now();\n entry.schedule.nextFireAt = nextFireTime(entry.schedule.trigger.interval.ms, Math.max(now, scheduledAt));\n this.#arm(entry);\n // A timer that ran long after its boundary (machine asleep) is a missed fire, not a late one.\n if (now - scheduledAt > LATE_FIRE_GRACE_MS) return;\n // A slow script can outlast a short interval; don't stack fires.\n if (entry.inFlight === 0) {\n void this.#fire(entry).then(result => {\n if (result.kind === 'failed') this.#options.onError?.(result.error, { ...entry.schedule });\n });\n }\n },\n Math.max(0, scheduledAt - this.#now()),\n );\n entry.timer.unref?.();\n }\n\n async #fire(entry: Entry): Promise<FireOutcome> {\n const schedule = { ...entry.schedule };\n entry.inFlight++;\n try {\n const assembled = await this.#options.assemblePrompt(schedule);\n // Deleted while its prompt was being built: drop the fire quietly.\n if (this.#entries.get(schedule.id) !== entry) return { kind: 'deleted' };\n await this.#options.deliver(schedule, assembled);\n return { kind: 'delivered' };\n } catch (error) {\n return { kind: 'failed', error };\n } finally {\n entry.inFlight--;\n }\n }\n}\n\nexport function shortScheduleId(id: string): string {\n return id.slice(0, 8);\n}\n\n/** One-line human summary of what a schedule sends: `run ./check.sh + \"extra\"`, `read notes.md`, `\"prompt\"`. */\nexport function describeScheduleSource(schedule: Pick<ThreadSchedule, 'prompt' | 'file' | 'extraPrompt'>): string {\n const oneLine = (text: string) => text.replace(/\\s+/g, ' ').trim();\n if (!schedule.file) return `\"${oneLine(schedule.prompt ?? '')}\"`;\n const verb = schedule.file.mode === 'script' ? 'run' : 'read';\n const extra = schedule.extraPrompt ? ` + \"${oneLine(schedule.extraPrompt)}\"` : '';\n return `${verb} ${schedule.file.displayPath}${extra}`;\n}\n\n/**\n * Attributes on a fired schedule signal. They carry everything the transcript\n * header needs, so reloaded history renders without the process-local entry.\n */\nexport function scheduleSignalAttributes(\n schedule: ThreadSchedule,\n assembled: Pick<AssembledPrompt, 'outcome'> = {},\n): Record<string, string> {\n return {\n source: SCHEDULE_SIGNAL_SOURCE,\n scheduleId: schedule.id,\n scheduleCadence: schedule.trigger.interval.label,\n scheduleSource: describeScheduleSource(schedule),\n scheduleCreatedBy: schedule.createdBy,\n ...(assembled.outcome ? { scheduleOutcome: assembled.outcome } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,yBAAyB;;AA2CtC,MAAa,qBAAqB;AAgBlC,IAAa,kBAAb,MAA6B;CAC3B,2BAAW,IAAI,IAAmB;CAClC;CAEA,YAAY,SAAiC;EAC3C,KAAK,WAAW;CAClB;CAEA,OAAe;EACb,OAAO,KAAK,SAAS,MAAM,KAAK,KAAK,IAAI;CAC3C;;CAGA,OAAO,MAA0B,QAAkE;EACjG,MAAM,EAAE,aAAa,KAAK;EAC1B,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,IAAI,WAAW,OACb,MAAM,IAAI,MACR,8BAA8B,MAAM,QAAQ,MAAM,aAAa,QAAQ,MAAM,WAAW,KAAK,IAC/F;EAEF,IAAI,YAAY,QAAQ,CAAC,KAAK,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM,2BAA2B;EACxF,MAAM,MAAM,KAAK,KAAK;EACtB,MAAM,WAA2B;GAC/B,IAAI,WAAW;GACf,UAAU,OAAO;GACjB,YAAY,OAAO;GACnB,SAAS;IAAE,MAAM;IAAS,UAAU,EAAE,GAAG,SAAS;GAAE;GACpD,GAAI,U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,iBAAiB;aAC5B,MAAM,EAAE,iBAAiB;aACzB,IAAI,EAAE,eAAe;aACrB,MAAM,EAAE,iBAAiB;aACzB,MAAM,EAAE,iBAAiB;aACzB,GAAG,EAAE,cAAc;CACX,CAAC;AAEX,MAAM,MAAM,mBAAmB,GAAG;IAChC,mEAAmE;IACnE,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,SAAS,EAAE,eAAe,CAAC;IAC3B,WAAW,EAAE,MAAM,mBAAmB,CAAC;CACxC,CAAC;AAiFF,wBAAgB,mBAAmB,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,EAAE,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4InF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools.js","names":["path"],"sources":["../../src/schedules/tools.ts"],"sourcesContent":["/**\n * Agent-facing tools for the process-local `/schedules` scheduler.\n *\n * Opt-in (experimental setting). Every tool is bound to the thread of the run\n * that calls it — the model never picks a thread or resource — and can only\n * see or manage schedules on that thread.\n */\nimport * as path from 'node:path';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { parseInterval, validateInterval } from './interval.js';\nimport { resolveScriptCommand } from './run-script.js';\nimport { describeScheduleSource, shortScheduleId } from './scheduler.js';\nimport type { ScheduleFile, ThreadSchedule, ThreadScheduler } from './scheduler.js';\n\nexport const SCHEDULE_TOOL_IDS = {\n create: 'schedule_create',\n list: 'schedule_list',\n update: 'schedule_update',\n resume: 'schedule_resume',\n run: 'schedule_run',\n} as const;\n\nexport type ScheduleFileOptions = {\n /** Directory relative paths resolve against (the project root). */\n cwd: string;\n homeDir?: string;\n fileExists: (absPath: string) => boolean;\n};\n\nexport type ScheduleToolsOptions = {\n scheduler: ThreadScheduler;\n fileOptions: () => ScheduleFileOptions;\n};\n\ntype ToolRunContext = { agent?: { threadId?: string; resourceId?: string } };\n\nconst resultSchema = z.object({\n content: z.string(),\n isError: z.boolean().optional(),\n});\ntype ScheduleToolResult = z.infer<typeof resultSchema>;\n\nconst intervalSchema = z\n .string()\n .min(1)\n .transform((value, ctx) => {\n const interval = parseInterval(value);\n if ('error' in interval) {\n ctx.addIssue({ code: 'custom', message: interval.error });\n return z.NEVER;\n }\n const check = validateInterval(interval);\n if ('error' in check) {\n const suggestion = check.suggestion ? ` Try ${check.suggestion}.` : '';\n ctx.addIssue({ code: 'custom', message: `${check.error}${suggestion}` });\n return z.NEVER;\n }\n return interval;\n })\n .describe('Cadence such as \"5m\", \"2h\", or \"1d\". Minute steps must divide 60, hour steps must divide 24.');\n\nconst triggerSchema = z\n .discriminatedUnion('kind', [\n z.object({\n kind: z.literal('every'),\n interval: intervalSchema,\n }),\n ])\n .describe('When the schedule fires. \"every\" repeats on wall-clock boundaries (5m fires at :00, :05, …).');\n\nconst idSchema = z.string().min(1).describe('Schedule id, or a unique prefix of it (the 8-character short id works).');\n\nfunction threadOf(context: unknown): { threadId: string; resourceId: string } | undefined {\n const agent = (context as ToolRunContext | undefined)?.agent;\n return agent?.threadId && agent.resourceId ? { threadId: agent.threadId, resourceId: agent.resourceId } : undefined;\n}\n\nconst NO_THREAD: ScheduleToolResult = { content: 'Schedules require a memory-backed thread.', isError: true };\n\nfunction resolveFile(\n token: string,\n mode: ScheduleFile['mode'],\n options: ScheduleFileOptions,\n): ScheduleFile | undefined {\n const expanded = token.startsWith('~/') && options.homeDir ? path.join(options.homeDir, token.slice(2)) : token;\n const absPath = path.resolve(options.cwd, expanded);\n return options.fileExists(absPath) ? { path: absPath, displayPath: token, mode } : undefined;\n}\n\nfunction formatSchedule(schedule: ThreadSchedule): string {\n const timing =\n schedule.status === 'paused' ? 'paused' : `next at ${new Date(schedule.nextFireAt).toLocaleTimeString()}`;\n return `${shortScheduleId(schedule.id)} every ${schedule.trigger.interval.label} ${timing} ${describeScheduleSource(schedule)} (created by ${schedule.createdBy})`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction findOne(\n scheduler: ThreadScheduler,\n threadId: string,\n id: string,\n): { schedule: ThreadSchedule } | ScheduleToolResult {\n const needle = id.toLowerCase();\n const matches = scheduler.list({ threadId }).filter(schedule => schedule.id.toLowerCase().startsWith(needle));\n if (matches.length === 1) return { schedule: matches[0]! };\n return {\n content: matches.length === 0 ? `No schedule \"${id}\" on this thread.` : `\"${id}\" matches several schedules.`,\n isError: true,\n };\n}\n\nexport function createScheduleTools({ scheduler, fileOptions }: ScheduleToolsOptions) {\n const scheduleCreateTool = createTool({\n id: SCHEDULE_TOOL_IDS.create,\n description: `Schedule a recurring prompt on this thread. Each fire arrives as a new user turn labelled \"schedule\".\n\nPass exactly one source: \"prompt\" (text sent each fire), \"promptFile\" (a file re-read and sent as the prompt each fire), or \"script\" (run each fire; its output is sent, followed by \"extraPrompt\" if given). Schedules live only until Mastra Code exits.`,\n inputSchema: z\n .object({\n trigger: triggerSchema,\n prompt: z.string().trim().min(1).optional().describe('Prompt text to send on every fire.'),\n promptFile: z.string().trim().min(1).optional().describe('Path to a file to re-read and send on every fire.'),\n script: z.string().trim().min(1).optional().describe('Path to a script to run on every fire.'),\n extraPrompt: z.string().trim().min(1).optional().describe('Text sent after the script output.'),\n })\n .refine(input => [input.prompt, input.promptFile, input.script].filter(Boolean).length === 1, {\n message: 'Provide exactly one of \"prompt\", \"promptFile\", or \"script\".',\n })\n .refine(input => !input.extraPrompt || input.script, {\n message: '\"extraPrompt\" only applies with \"script\".',\n }),\n outputSchema: resultSchema,\n execute: async (input, context): Promise<ScheduleToolResult> => {\n const target = threadOf(context);\n if (!target) return NO_THREAD;\n let schedule: ThreadSchedule;\n if (input.prompt) {\n schedule = scheduler.create({ trigger: input.trigger, prompt: input.prompt, createdBy: 'agent' }, target);\n } else {\n const token = (input.script ?? input.promptFile)!;\n const file = resolveFile(token, input.script ? 'script' : 'prompt', fileOptions());\n if (!file) return { content: `File not found: ${token}`, isError: true };\n if (file.mode === 'script') {\n try {\n resolveScriptCommand(file.path);\n } catch (error) {\n return {\n content: `Can't run ${token}: ${error instanceof Error ? error.message : String(error)}`,\n isError: true,\n };\n }\n }\n schedule = scheduler.create(\n {\n trigger: input.trigger,\n file,\n ...(input.extraPrompt ? { extraPrompt: input.extraPrompt } : {}),\n createdBy: 'agent',\n },\n target,\n );\n }\n return { content: `Created schedule ${formatSchedule(schedule)}` };\n },\n });\n\n const scheduleListTool = createTool({\n id: SCHEDULE_TOOL_IDS.list,\n description: 'List the recurring prompt schedules on this thread, including ones the user created with /schedules.',\n inputSchema: z.object({}),\n outputSchema: resultSchema,\n execute: async (_input, context): Promise<ScheduleToolResult> => {\n const target = threadOf(context);\n if (!target) return NO_THREAD;\n const schedules = scheduler.list({ threadId: target.threadId });\n if (schedules.length === 0) return { content: 'No schedules on this thread.' };\n return {\n content: [`Schedules on this thread (${schedules.length}):`, ...schedules.map(formatSchedule)].join('\\n'),\n };\n },\n });\n\n const scheduleUpdateTool = createTool({\n id: SCHEDULE_TOOL_IDS.update,\n description: 'Pause or delete a schedule on this thread. Use schedule_resume to resume a paused one.',\n inputSchema: z.object({\n id: idSchema,\n action: z.enum(['pause', 'delete']),\n }),\n outputSchema: resultSchema,\n execute: async ({ id, action }, context): Promise<ScheduleToolResult> => {\n const target = threadOf(context);\n if (!target) return NO_THREAD;\n const found = findOne(scheduler, target.threadId, id);\n if (!('schedule' in found)) return found;\n scheduler[action](found.schedule.id);\n const verb = action === 'pause' ? 'Paused' : 'Deleted';\n return { content: `${verb} schedule ${shortScheduleId(found.schedule.id)}.` };\n },\n });\n\n // Separate from schedule_update: resuming lets the timer run the schedule's\n // script again, so it needs the same approval as creating or running one.\n const scheduleResumeTool = createTool({\n id: SCHEDULE_TOOL_IDS.resume,\n description: 'Resume a paused schedule on this thread. It fires again from the next clock boundary.',\n inputSchema: z.object({ id: idSchema }),\n outputSchema: resultSchema,\n execute: async ({ id }, context): Promise<ScheduleToolResult> => {\n const target = threadOf(context);\n if (!target) return NO_THREAD;\n const found = findOne(scheduler, target.threadId, id);\n if (!('schedule' in found)) return found;\n scheduler.resume(found.schedule.id);\n return { content: `Resumed schedule ${shortScheduleId(found.schedule.id)}.` };\n },\n });\n\n const scheduleRunTool = createTool({\n id: SCHEDULE_TOOL_IDS.run,\n description:\n 'Fire a schedule on this thread once now, even if it is paused, without changing its cadence. Its prompt arrives as the next user turn.',\n inputSchema: z.object({ id: idSchema }),\n outputSchema: resultSchema,\n execute: async ({ id }, context): Promise<ScheduleToolResult> => {\n const target = threadOf(context);\n if (!target) return NO_THREAD;\n const found = findOne(scheduler, target.threadId, id);\n if (!('schedule' in found)) return found;\n const short = shortScheduleId(found.schedule.id);\n const result = await scheduler.run(found.schedule.id);\n switch (result.status) {\n case 'fired':\n return { content: `Triggered schedule ${short}; its prompt arrives as the next turn.` };\n case 'busy':\n return { content: `Schedule ${short} is already firing; skipped so its prompt isn't sent twice.` };\n case 'not-found':\n return { content: `Schedule ${short} was deleted before it fired.`, isError: true };\n case 'failed':\n return { content: `Schedule ${short} failed to fire: ${errorMessage(result.error)}`, isError: true };\n }\n },\n });\n\n return {\n [SCHEDULE_TOOL_IDS.create]: scheduleCreateTool,\n [SCHEDULE_TOOL_IDS.list]: scheduleListTool,\n [SCHEDULE_TOOL_IDS.update]: scheduleUpdateTool,\n [SCHEDULE_TOOL_IDS.resume]: scheduleResumeTool,\n [SCHEDULE_TOOL_IDS.run]: scheduleRunTool,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,MAAa,oBAAoB;CAC/B,QAAQ;CACR,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,KAAK;AACP;AAgBA,MAAM,eAAe,EAAE,OAAO;CAC5B,SAAS,EAAE,OAAO;CAClB,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS;AAChC,CAAC;AA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,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+KnB,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema.js","names":[],"sources":["../src/schema.ts"],"sourcesContent":["import type { OMModel } from '@mastra/core/agent-controller';\nimport { z } from 'zod';\nimport { DEFAULT_CONFIG_DIR, MODEL_ROUTE_MAX_ENTRIES, MODEL_ROUTE_MAX_FIELD_LENGTH } from './constants.js';\nimport { THINKING_LEVEL_VALUES } from './thinking.js';\nimport type { ThinkingLevelSetting } from './thinking.js';\n\nexport type PermissionPolicy = 'allow' | 'ask' | 'deny';\n\nexport type MastraCodeSessionState = {\n currentModelId: string;\n modeId: string;\n};\n\nexport type MastraCodeComposedState = MastraCodeState & MastraCodeSessionState;\n\nexport interface ModelRouteEntry {\n id: string;\n label: string;\n modelId: string;\n accountId?: string;\n memoryModelId?: string;\n}\n\nexport interface ModelRoute {\n entries: ModelRouteEntry[];\n}\n\nexport interface PendingModelFallback {\n fromEntryId: string;\n toEntryId: string;\n toModelId: string;\n threadId?: string;\n reason: 'pool-exhausted' | 'persistent-outage';\n at: string;\n}\n\nexport interface MastraCodeState {\n [key: string]: unknown;\n [key: `subagentModelId_${string}`]: string | undefined;\n subagentModelId?: string;\n projectPath?: string;\n projectName?: string;\n /** Factory project that owns this session. */\n factoryProjectId?: string;\n /** Whether this session uses organization or owner-scoped models and credentials. */\n factoryModelScope?: 'factory' | 'user';\n /** Stable user id of the Factory session owner. */\n factoryOwnerUserId?: string;\n /** Authoritative organization id seeded by factory at session construction. */\n factoryOrgId?: string;\n /**\n * Factory owns this session but could not resolve its organization. Knowledge\n * capture refuses rather than filing under a substituted identity; without the\n * marker a projectless factory session is indistinguishable from a local one.\n */\n factoryOrgUnresolved?: boolean;\n /** Linked repository used by this session when source-control execution is required. */\n projectRepositoryId?: string;\n /** Active feature branch checked out in the session workdir. */\n branch?: string;\n /**\n * The session's checkout contains third-party content (e.g. a PR branch\n * under review). Project-level instruction files (AGENTS.md, CLAUDE.md)\n * are attacker-writable there and must not be ingested into the system\n * prompt or injected as reminders.\n */\n untrustedCheckout?: boolean;\n /**\n * Trusted git ref (typically the PR's base branch) to serve project\n * instruction files from when the checkout is untrusted. Without it,\n * project-scope instruction files are skipped entirely.\n */\n baseRef?: string;\n /**\n * Skip the home-directory instruction files (~/.claude/AGENTS.md and\n * friends). Hosts running sessions for someone else set this so a run never\n * inherits the machine owner's personal configuration.\n */\n skipGlobalInstructions?: boolean;\n /**\n * Directories under the working directory whose project instruction files\n * (AGENTS.md, CLAUDE.md) load, the session's own checkout first. Hosts that\n * boot several checkouts under one working directory set it; unset, the\n * working directory itself is the only root.\n */\n instructionRoots?: string[];\n configDir: string;\n homeDir?: string;\n gitBranch?: string;\n lastCommand?: string;\n observerModelId?: string;\n reflectorModelId?: string;\n observerModelSelection: OMModel;\n reflectorModelSelection: OMModel;\n observationThreshold: number;\n reflectionThreshold: number;\n cavemanObservations: boolean;\n observeAttachments: 'auto' | boolean;\n omScope?: 'thread' | 'resource';\n /** Ordered host-supplied model and account fallback route for this thread. */\n modelRoute?: ModelRoute;\n /** One-hop fallback intent written by account rotation and consumed by the host. */\n mastracodePendingModelFallback?: PendingModelFallback | null;\n /**\n * Session-level reasoning-effort override. When unset, the effective level is\n * resolved at request time from settings (`models.modeThinkingDefaults[mode]`\n * falling back to `preferences.thinkingLevel`).\n */\n thinkingLevel?: ThinkingLevelSetting;\n yolo: boolean;\n permissionRules: {\n categories: Record<string, PermissionPolicy>;\n tools: Record<string, PermissionPolicy>;\n };\n smartEditing: boolean;\n notifications: 'bell' | 'system' | 'both' | 'off';\n tasks: Array<{\n id?: string;\n content: string;\n status: 'pending' | 'in_progress' | 'completed';\n activeForm: string;\n }>;\n sandboxAllowedPaths: string[];\n pluginSkillPaths: string[];\n pluginCommandPaths: string[];\n pluginInstructions: string[];\n activePlan: {\n title: string;\n plan: string;\n approvedAt: string;\n } | null;\n activeBrowserSettings?: {\n enabled: boolean;\n provider: 'stagehand' | 'agent-browser';\n headless?: boolean;\n viewport?: { width: number; height: number } | 'window';\n cdpUrl?: string;\n profile?: string;\n executablePath?: string;\n scope?: 'shared' | 'thread';\n stagehand?: {\n env: 'LOCAL' | 'BROWSERBASE';\n projectId?: string;\n model?: string;\n preserveUserDataDir?: boolean;\n };\n agentBrowser?: {\n storageState?: string;\n };\n };\n activeBrowserModel?: {\n modelName?: string;\n source: 'settings' | 'chat-model' | 'codex-oauth' | 'stagehand-default';\n viaCodexOAuth: boolean;\n };\n}\n\nexport const stateSchema = z\n .object({\n // Session-scoped selection. The controller validates state against this\n // schema, so these keys must be declared here — Zod strips unknown keys.\n currentModelId: z.string().optional(),\n modeId: z.string().optional(),\n modelRoute: z\n .object({\n entries: z\n .array(\n z.object({\n id: z.string().max(MODEL_ROUTE_MAX_FIELD_LENGTH),\n label: z.string().max(MODEL_ROUTE_MAX_FIELD_LENGTH),\n modelId: z.string().max(MODEL_ROUTE_MAX_FIELD_LENGTH),\n accountId: z.string().max(MODEL_ROUTE_MAX_FIELD_LENGTH).optional(),\n memoryModelId: z.string().max(MODEL_ROUTE_MAX_FIELD_LENGTH).optional(),\n }),\n )\n .max(MODEL_ROUTE_MAX_ENTRIES),\n })\n .optional(),\n subagentModelId: z.string().optional(),\n // Per-agentType subagent selections, written by session.subagents.model.set\n // (key shape: subagentModelId_<agentType>). Declared so state validation\n // keeps them — Zod strips unknown keys.\n subagentModelId_explore: z.string().optional(),\n subagentModelId_plan: z.string().optional(),\n subagentModelId_execute: z.string().optional(),\n projectPath: z.string().optional(),\n projectName: z.string().optional(),\n factoryProjectId: z.string().optional(),\n factoryModelScope: z.enum(['factory', 'user']).optional(),\n factoryOwnerUserId: z.string().optional(),\n factoryOrgId: z.string().optional(),\n factoryOrgUnresolved: z.boolean().optional(),\n projectRepositoryId: z.string().optional(),\n branch: z.string().optional(),\n // Session operates on an untrusted checkout — suppress AGENTS.md ingestion.\n untrustedCheckout: z.boolean().optional(),\n // Trusted ref to serve instruction files from on untrusted checkouts.\n baseRef: z.string().optional(),\n // Skip the operator machine's home-directory instruction files.\n skipGlobalInstructions: z.boolean().optional(),\n // Checkouts whose instruction files load, the session's own first.\n instructionRoots: z.array(z.string()).optional(),\n configDir: z.string().default(DEFAULT_CONFIG_DIR),\n homeDir: z.string().optional(),\n gitBranch: z.string().optional(),\n lastCommand: z.string().optional(),\n // Observational Memory model settings. Concrete IDs are legacy/explicit\n // compatibility fields; fresh sessions preserve auto selection intent.\n observerModelId: z.string().optional(),\n reflectorModelId: z.string().optional(),\n observerModelSelection: z.string().optional(),\n reflectorModelSelection: z.string().optional(),\n // Observational Memory threshold settings\n observationThreshold: z.number().default(30_000),\n reflectionThreshold: z.number().default(40_000),\n // Whether observations and reflections use the terse caveman-style instruction.\n // Off by default — caveman style is opt-in via `/om` settings; observers and\n // reflectors fall back to their built-in (prose) behavior unless enabled.\n cavemanObservations: z.boolean().default(false),\n // Whether OM forwards image/file attachment parts to the Observer LLM.\n // 'auto' (default) checks the provider capabilities registry to decide.\n // true/false forces the setting regardless of model capabilities.\n observeAttachments: z.union([z.literal('auto'), z.boolean()]).default('auto'),\n // Observational Memory scope — 'thread' (per-conversation) or 'resource' (shared across threads)\n omScope: z.enum(['thread', 'resource']).optional(),\n // Thinking level for model reasoning effort. Optional: absent means \"no\n // session override\" — the effective level is resolved from settings\n // (per-mode defaults, then the global preference) at request time.\n thinkingLevel: z.preprocess(\n value => (value === null ? undefined : value),\n z.enum(THINKING_LEVEL_VALUES).optional(),\n ),\n // YOLO mode — auto-approve all tool calls\n yolo: z.boolean().default(false),\n // Permission rules — per-category and per-tool approval policies\n permissionRules: z\n .object({\n categories: z.record(z.string(), z.enum(['allow', 'ask', 'deny'])).default({}),\n tools: z.record(z.string(), z.enum(['allow', 'ask', 'deny'])).default({}),\n })\n .default({ categories: {}, tools: {} }),\n // Smart editing mode — use AST-based analysis for code edits\n smartEditing: z.boolean().default(true),\n // Notification mode — alert when TUI needs user attention\n notifications: z.enum(['bell', 'system', 'both', 'off']).default('off'),\n // Task list (ephemeral per-thread, cleared on thread switch/creation)\n tasks: z\n .array(\n z.object({\n id: z.string().optional(),\n content: z.string(),\n status: z.enum(['pending', 'in_progress', 'completed']),\n activeForm: z.string(),\n }),\n )\n .default([]),\n // Sandbox allowed paths (per-thread, absolute paths allowed in addition to project root)\n sandboxAllowedPaths: z.array(z.string()).default([]),\n // Pending route hop written by account rotation. The host consumes it on\n // `state_changed` to apply thread stickiness, then clears it back to null.\n mastracodePendingModelFallback: z\n .object({\n fromEntryId: z.string(),\n toEntryId: z.string(),\n toModelId: z.string(),\n threadId: z.string().optional(),\n reason: z.enum(['pool-exhausted', 'persistent-outage']),\n at: z.string(),\n })\n .nullish(),\n // Asset directories contributed by active plugins.\n pluginSkillPaths: z.array(z.string()).default([]),\n pluginCommandPaths: z.array(z.string()).default([]),\n pluginInstructions: z.array(z.string()).default([]),\n // Active plan (set when a plan is approved in Plan mode)\n activePlan: z\n .object({\n title: z.string(),\n plan: z.string(),\n approvedAt: z.string(),\n })\n .nullable()\n .default(null),\n // Active browser settings (tracks what's actually running vs. what's in the settings file)\n activeBrowserSettings: z\n .object({\n enabled: z.boolean(),\n provider: z.enum(['stagehand', 'agent-browser']),\n headless: z.boolean().optional(),\n viewport: z\n .union([\n z.object({\n width: z.number(),\n height: z.number(),\n }),\n z.literal('window'),\n ])\n .optional(),\n cdpUrl: z.string().optional(),\n profile: z.string().optional(),\n executablePath: z.string().optional(),\n scope: z.enum(['shared', 'thread']).optional(),\n stagehand: z\n .object({\n env: z.enum(['LOCAL', 'BROWSERBASE']),\n projectId: z.string().optional(),\n model: z.string().optional(),\n preserveUserDataDir: z.boolean().optional(),\n })\n .optional(),\n agentBrowser: z\n .object({\n storageState: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n // Model the active Stagehand browser was created with. Resolved once at\n // launch so /browser status reports what is really running even if the\n // user signs in/out of Codex afterwards.\n activeBrowserModel: z\n .object({\n modelName: z.string().optional(),\n source: z.enum(['settings', 'chat-model', 'codex-oauth', 'stagehand-default']),\n viaCodexOAuth: z.boolean(),\n })\n .optional(),\n })\n .transform(state => ({\n ...state,\n observerModelSelection: state.observerModelSelection ?? state.observerModelId ?? 'auto',\n reflectorModelSelection: state.reflectorModelSelection ?? state.reflectorModelId ?? 'auto',\n }));\n"],"mappings":";;;;AA6JA,MAAa,cAAc,EACxB,OAAO;CAGN,gBAAgB,EAAE,OAAO,CAAC,CAAC,SAAS;CACpC,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS;CAC5B,YAAY,EACT,OAAO,EACN,SAAS,EACN,MACC,EAAE,OAAO;EACP,IAAI,EAAE,OAAO,CAAC,CAAC,IAAA,GAAgC;EAC/C,OAAO,EAAE,OAAO,CAAC,CAAC,IAAA,GAAgC;EAClD,SAAS,EAAE,OAAO,CAAC,CAAC,IAAA,GAAgC;EACpD,WAAW,EAAE,OAAO,CAAC,CAAC,IAAA,GAAgC,CAAC,CAAC,SAAS;EACjE,eAAe,EAAE,OAAO,CAAC,CAAC,IAAA,GAAgC,CAAC,CAAC,SAAS;CACvE,CAAC,CACH,CAAC,CACA,IAAA,EAA2B,EAChC,CAAC,CAAC,CACD,SAAS;CACZ,iBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS;CAIrC,yBAAyB,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7C,sBAAsB,EAAE,OAA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c,EACX,OAAO,EACN,cAAc,EAAE,OAAO,CAAC,CAAC,SAAS,EACpC,CAAC,CAAC,CACD,SAAS;CACd,CAAC,CAAC,CACD,SAAS;CAIZ,oBAAoB,EACjB,OAAO;EACN,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;EAC/B,QAAQ,EAAE,KAAK;GAAC;GAAY;GAAc;GAAe;EAAmB,CAAC;EAC7E,eAAe,EAAE,QAAQ;CAC3B,CAAC,CAAC,CACD,SAAS;AACd,CAAC,CAAC,CACD,WAAU,WAAU;CACnB,GAAG;CACH,wBAAwB,MAAM,0BAA0B,MAAM,mBAAmB;CACjF,yBAAyB,MAAM,2BAA2B,MAAM,oBAAoB;AACtF,EAAE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"theme-palette.d.ts","sourceRoot":"","sources":["../src/theme-palette.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,WAAW;aACtB,MAAM,EAAE,SAAS;aACjB,KAAK,EAAE,SAAS;aAChB,MAAM,EAAE,SAAS;aACjB,IAAI,EAAE,SAAS;aACf,IAAI,EAAE,SAAS;aACf,GAAG,EAAE,SAAS;aACd,MAAM,EAAE,SAAS;CACT,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"theme-palette.js","names":[],"sources":["../src/theme-palette.ts"],"sourcesContent":["/**\n * Mastra brand palette (immutable — stays constant regardless of theme).\n *\n * Lives outside the TUI so non-TUI code (e.g. mode metadata colors in\n * `createMastraCode`) can use brand colors without importing TUI modules.\n * The TUI's `theme.ts` re-exports this and layers contrast adaptation on top.\n */\nexport const mastraBrand = {\n purple: '#7f45e0', // #b588fe brand is too washed out for terminal\n green: '#16c858', // brand green (dark mode primary)\n orange: '#fdac53',\n pink: '#ff69cc',\n blue: '#2563eb', // #6ccdfb brand is to washed out\n red: '#DC5663', // #ff4758 too intense\n yellow: '#e7e67b',\n} as const;\n"],"mappings":";;;;;;;;AAOA,MAAa,cAAc;CACzB,QAAQ;CACR,OAAO;CACP,QAAQ;CACR,MAAM;CACN,MAAM;CACN,KAAK;CACL,QAAQ;AACV"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"thinking-catalog.d.ts","sourceRoot":"","sources":["../src/thinking-catalog.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAE1D,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,oBAAoB,GAAG,oBAAoB,CAE1G;AAED,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,EAAE,CAEhF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"thinking-catalog.js","names":[],"sources":["../src/thinking-catalog.ts"],"sourcesContent":["import { getModelReasoningOptions } from '@mastra/core/llm';\nimport { getAvailableThinkingLevelsForModel, runThinkingLevel } from './thinking.js';\nimport type { ThinkingLevelSetting } from './thinking.js';\n\nexport function runCatalogThinkingLevel(modelId: string, level: ThinkingLevelSetting): ThinkingLevelSetting {\n return runThinkingLevel(modelId, level, getModelReasoningOptions(modelId));\n}\n\nexport function getCatalogThinkingLevels(modelId: string): ThinkingLevelSetting[] {\n return getAvailableThinkingLevelsForModel(modelId, getModelReasoningOptions(modelId));\n}\n"],"mappings":";;;AAIA,SAAgB,wBAAwB,SAAiB,OAAmD;CAC1G,OAAO,iBAAiB,SAAS,OAAO,yBAAyB,OAAO,CAAC;AAC3E;AAEA,SAAgB,yBAAyB,SAAyC;CAChF,OAAO,mCAAmC,SAAS,yBAAyB,OAAO,CAAC;AACtF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"thinking.d.ts","sourceRoot":"","sources":["../src/thinking.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAc7D,MAAM,MAAM,oBAAoB,GAAG,KAAK,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK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AAgB,CAAC,EAAE,SAAS,oBAAoB,EAAE,GACjD,oBAAoB,EAAE,CAExB;AAED,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,SAAS,oBAAoB,EAA0B,GAC9D,kBAAkB,CAMpB;AAED,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,gBAAgB,EAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,GACnB;IAAE,KAAK,EAAE,oBAAoB,CAAC;IAAC,MAAM,EAAE,mBAAmB,CAAA;CAAE,CAG9D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"thinking.js","names":[],"sources":["../src/thinking.ts"],"sourcesContent":["import type { ModelReasoningOption } from '@mastra/core/llm';\nimport {\n ANTHROPIC_THINKING_BUDGET_TOKENS,\n getAnthropicThinkingCapability,\n supportsAnthropicXhighEffort,\n} from './providers/anthropic-thinking.js';\nimport { runGeminiThinkingLevel } from './providers/google-thinking.js';\nimport { normalizeAnthropicModelId, stripMastraGatewayPrefix } from './providers/model-ids.js';\nimport {\n isRoutedWithoutThinking,\n isThinkingAdapterProvider,\n thinkingRequestFormatFor,\n} from './providers/thinking-request.js';\n\nexport type ThinkingLevelSetting = 'off' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n\nexport type ActiveThinkingLevel = Exclude<ThinkingLevelSetting, 'off'>;\n\nexport type ThinkingLevelSource = 'mode-default' | 'global';\n\nexport interface ThinkingDefaults {\n globalDefault: ThinkingLevelSetting;\n modeDefaults: Readonly<Record<string, ThinkingLevelSetting>>;\n}\n\nexport const THINKING_LEVEL_VALUES: ThinkingLevelSetting[] = ['off', 'low', 'medium', 'high', 'xhigh', 'max'];\n\nconst ACTIVE_THINKING_LEVELS: ActiveThinkingLevel[] = ['low', 'medium', 'high', 'xhigh', 'max'];\n\nexport const THINK_COMMAND_DESCRIPTOR = {\n name: 'think',\n args: '[status|default|off|low|medium|high|xhigh|max]',\n description: 'Show or set session thinking level',\n};\n\nexport type ThinkCommandAction =\n | { kind: 'status' }\n | { kind: 'clear' }\n | { kind: 'set'; level: ThinkingLevelSetting }\n | { kind: 'invalid'; value: string; levels: readonly ThinkingLevelSetting[] };\n\nconst GPT_VERSION_RE = /^gpt-(\\d+)(?:\\.(\\d+))?/;\n\nexport function isThinkingLevelSetting(value: unknown): value is ThinkingLevelSetting {\n return typeof value === 'string' && THINKING_LEVEL_VALUES.some(level => level === value);\n}\n\nexport function supportsMaxReasoningEffort(modelId: string): boolean {\n const bareModelId = modelId.startsWith('openai/') ? modelId.slice('openai/'.length) : modelId;\n const match = GPT_VERSION_RE.exec(bareModelId);\n if (!match) return false;\n const major = Number(match[1]);\n const minor = Number(match[2] ?? 0);\n return major > 5 || (major === 5 && minor >= 6);\n}\n\nfunction splitProvider(modelId: string): { provider: string; bareModelId: string } {\n const routedModelId = stripMastraGatewayPrefix(modelId);\n const slash = routedModelId.indexOf('/');\n if (slash === -1) return { provider: '', bareModelId: routedModelId };\n return { provider: routedModelId.slice(0, slash), bareModelId: routedModelId.slice(slash + 1) };\n}\n\nfunction offeredEffortLevels(reasoningOptions: readonly ModelReasoningOption[] | undefined): ActiveThinkingLevel[] {\n const effortValues = reasoningOptions?.flatMap(option => (option.type === 'effort' ? option.values : [])) ?? [];\n return ACTIVE_THINKING_LEVELS.filter(level => effortValues.includes(level));\n}\n\nconst TOGGLE_ON_LEVEL: ActiveThinkingLevel = 'high';\n\nfunction onlyTogglesThinking(reasoningOptions: readonly ModelReasoningOption[] | undefined): boolean {\n return !!reasoningOptions?.length && reasoningOptions.every(option => option.type === 'toggle');\n}\n\nexport function requestableReasoningOptions(\n modelId: string,\n reasoningOptions: readonly ModelReasoningOption[] | undefined,\n): readonly ModelReasoningOption[] | undefined {\n if (isRoutedWithoutThinking(modelId)) return [];\n if (!reasoningOptions) return reasoningOptions;\n const format = thinkingRequestFormatFor(modelId);\n if (!format) return isThinkingAdapterProvider(splitProvider(modelId).provider) ? reasoningOptions : [];\n const acceptedEfforts = format.sendEffort ? (format.acceptedEfforts ?? ACTIVE_THINKING_LEVELS) : [];\n return reasoningOptions.flatMap((option): ModelReasoningOption[] => {\n if (option.type === 'toggle') return format.enableThinking ? [option] : [];\n if (option.type !== 'effort') return [];\n const values = option.values.filter(value => acceptedEfforts.some(effort => effort === value));\n return values.length ? [{ type: 'effort', values }] : [];\n });\n}\n\nfunction closestOfferedEffort(\n level: ActiveThinkingLevel,\n reasoningOptions: readonly ModelReasoningOption[] | undefined,\n): ActiveThinkingLevel | undefined {\n const offered = offeredEffortLevels(reasoningOptions);\n const requestedRank = ACTIVE_THINKING_LEVELS.indexOf(level);\n const atOrBelow = offered.filter(candidate => ACTIVE_THINKING_LEVELS.indexOf(candidate) <= requestedRank);\n return atOrBelow.at(-1) ?? offered[0];\n}\n\nfunction lowestLevelWithSameBudget(level: ActiveThinkingLevel): ActiveThinkingLevel {\n const budget = ANTHROPIC_THINKING_BUDGET_TOKENS[level];\n return ACTIVE_THINKING_LEVELS.find(candidate => ANTHROPIC_THINKING_BUDGET_TOKENS[candidate] === budget) ?? level;\n}\n\nfunction runAnthropicThinkingLevel(\n modelId: string,\n level: ActiveThinkingLevel,\n reasoningOptions: readonly ModelReasoningOption[] | undefined,\n): ThinkingLevelSetting {\n const capability = getAnthropicThinkingCapability(modelId);\n if (capability === 'none') return 'off';\n if (capability === 'budget') return lowestLevelWithSameBudget(level);\n const offeredEffort = closestOfferedEffort(level, reasoningOptions);\n if (offeredEffort) return offeredEffort;\n return level === 'xhigh' && !supportsAnthropicXhighEffort(modelId) ? 'high' : level;\n}\n\nfunction runOpenAIThinkingLevel(\n modelId: string,\n level: ActiveThinkingLevel,\n reasoningOptions: readonly ModelReasoningOption[] | undefined,\n): ActiveThinkingLevel {\n const offeredEffort = closestOfferedEffort(level, reasoningOptions);\n if (offeredEffort) return offeredEffort;\n return level === 'max' && !supportsMaxReasoningEffort(modelId) ? 'xhigh' : level;\n}\n\nexport function runThinkingLevel(\n modelId: string,\n level: ThinkingLevelSetting,\n reasoningOptions: readonly ModelReasoningOption[] | undefined,\n): ThinkingLevelSetting {\n if (level === 'off') return 'off';\n const { provider, bareModelId } = splitProvider(modelId);\n if (provider === 'google') return runGeminiThinkingLevel(bareModelId, level);\n if (provider === 'anthropic') {\n return runAnthropicThinkingLevel(normalizeAnthropicModelId(bareModelId), level, reasoningOptions);\n }\n const requestable = requestableReasoningOptions(modelId, reasoningOptions);\n const listedWithoutReasoningControls = requestable?.length === 0;\n if (listedWithoutReasoningControls) return 'off';\n if (onlyTogglesThinking(requestable)) return TOGGLE_ON_LEVEL;\n if (provider === 'openai') return runOpenAIThinkingLevel(bareModelId, level, requestable);\n return closestOfferedEffort(level, requestable) ?? level;\n}\n\nexport function getAvailableThinkingLevelsForModel(\n modelId: string,\n reasoningOptions?: readonly ModelReasoningOption[],\n): ThinkingLevelSetting[] {\n return THINKING_LEVEL_VALUES.filter(level => runThinkingLevel(modelId, level, reasoningOptions) === level);\n}\n\nexport function parseThinkCommand(\n input: string,\n levels: readonly ThinkingLevelSetting[] = THINKING_LEVEL_VALUES,\n): ThinkCommandAction {\n const value = input.trim().toLowerCase();\n if (!value || value === 'status') return { kind: 'status' };\n if (value === 'default' || value === 'clear') return { kind: 'clear' };\n const level = levels.find(candidate => candidate === value);\n return level ? { kind: 'set', level } : { kind: 'invalid', value, levels };\n}\n\nexport function resolveDefaultThinkingLevel(\n defaults: ThinkingDefaults,\n mode?: string | null,\n): { level: ThinkingLevelSetting; source: ThinkingLevelSource } {\n const modeLevel = mode ? defaults.modeDefaults[mode] : undefined;\n return modeLevel ? { level: modeLevel, source: 'mode-default' } : { level: defaults.globalDefault, source: 'global' };\n}\n"],"mappings":";;;;;AAyBA,MAAa,wBAAgD;CAAC;CAAO;CAAO;CAAU;CAAQ;CAAS;AAAK;AAE5G,MAAM,yBAAgD;CAAC;CAAO;CAAU;CAAQ;CAAS;AAAK;AAE9F,MAAa,2BAA2B;CACtC,MAAM;CACN,MAAM;CACN,aAAa;AACf;AAQA,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BAAoB;aACxC,UAAU,EAAE,YAAY;aACxB,WAAW,EAAE,aAAa;aAC1B,SAAS,EAAE,WAAW;aACtB,KAAK,EAAE,OAAO;aAGd,cAAc,EAAE,gBAAgB;aAGhC,cAAc,EAAE,gBAAgB;aAGhC,eAAe,EAAE,iBAAiB;aAClC,kBAAkB,EAAE,oBAAoB;aACxC,YAAY,EAAE,cAAc;aAG5B,WAAW,EAAE,aAAa;aAG1B,kBAAkB,EAAE,oBAAoB;aAGxC,sBAAsB,EAAE,wBAAwB;aAChD,aAAa,EAAE,eAAe;aAC9B,gBAAgB,EAAE,kBAAkB;aACpC,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC;AAEX;;;;GAIG;AACH,eAAO,MAAM,mBAAmB;;iBACY,IAAI;;;iBACH,IAAI;;;iBACL,IAAI;;;iBACH,IAAI;;;iBACR,IAAI;;;iBACD,IAAI;;;iBACR,IAAI;;;iBACL,IAAI;;;iBACA,IAAI;;;iBACA,IAAI;;;iBACD,IAAI;;;iBACV,IAAI;;;iBACT,IAAI;;CACjC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tool-names.js","names":[],"sources":["../src/tool-names.ts"],"sourcesContent":["/**\n * Mastracode tool name constants.\n *\n * These are the names exposed to the LLM via workspace tool name remapping.\n * Used throughout mastracode for permissions, TUI rendering, tool guidance,\n * subagent allowedTools, etc.\n *\n * The workspace tools get remapped from their core names (e.g. `mastra_workspace_read_file`)\n * to these names (e.g. `view`) via the `name` property in workspace tool config.\n */\n\nimport { WORKSPACE_TOOLS } from '@mastra/core/workspace';\n\nexport const MC_TOOLS = {\n // Filesystem\n VIEW: 'view',\n WRITE_FILE: 'write_file',\n STRING_REPLACE_LSP: 'string_replace_lsp',\n FIND_FILES: 'find_files',\n DELETE_FILE: 'delete_file',\n FILE_STAT: 'file_stat',\n MKDIR: 'mkdir',\n\n // Search\n SEARCH_CONTENT: 'search_content',\n\n // Code intelligence\n AST_SMART_EDIT: 'ast_smart_edit',\n\n // Sandbox\n EXECUTE_COMMAND: 'execute_command',\n GET_PROCESS_OUTPUT: 'get_process_output',\n KILL_PROCESS: 'kill_process',\n\n // Code intelligence\n LSP_INSPECT: 'lsp_inspect',\n\n // Notifications\n NOTIFICATION_INBOX: 'notification_inbox',\n\n // Agent connections\n AGENT_CONNECTIONS_LIST: 'agent_connections_list',\n AGENT_CONNECT: 'agent_connect',\n AGENT_DISCONNECT: 'agent_disconnect',\n AGENT_SIGNAL_SEND: 'agent_signal_send',\n} as const;\n\n/**\n * Workspace tool name remapping config.\n * Maps core workspace tool constants to mastracode's tool names.\n * Pass this (or spread it) into `Workspace({ tools: ... })`.\n */\nexport const TOOL_NAME_OVERRIDES = {\n [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: { name: MC_TOOLS.VIEW },\n [WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE]: { name: MC_TOOLS.WRITE_FILE },\n [WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE]: { name: MC_TOOLS.STRING_REPLACE_LSP },\n [WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES]: { name: MC_TOOLS.FIND_FILES },\n [WORKSPACE_TOOLS.FILESYSTEM.DELETE]: { name: MC_TOOLS.DELETE_FILE },\n [WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT]: { name: MC_TOOLS.FILE_STAT },\n [WORKSPACE_TOOLS.FILESYSTEM.MKDIR]: { name: MC_TOOLS.MKDIR },\n [WORKSPACE_TOOLS.FILESYSTEM.GREP]: { name: MC_TOOLS.SEARCH_CONTENT },\n [WORKSPACE_TOOLS.FILESYSTEM.AST_EDIT]: { name: MC_TOOLS.AST_SMART_EDIT },\n [WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]: { name: MC_TOOLS.EXECUTE_COMMAND },\n [WORKSPACE_TOOLS.SANDBOX.GET_PROCESS_OUTPUT]: { name: MC_TOOLS.GET_PROCESS_OUTPUT },\n [WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS]: { name: MC_TOOLS.KILL_PROCESS },\n [WORKSPACE_TOOLS.LSP.LSP_INSPECT]: { name: MC_TOOLS.LSP_INSPECT },\n} as const;\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,WAAW;CAEtB,MAAM;CACN,YAAY;CACZ,oBAAoB;CACpB,YAAY;CACZ,aAAa;CACb,WAAW;CACX,OAAO;CAGP,gBAAgB;CAGhB,gBAAgB;CAGhB,iBAAiB;CACjB,oBAAoB;CACpB,cAAc;CAGd,aAAa;CAGb,oBAAoB;CAGpB,wBAAwB;CACxB,eAAe;CACf,kBAAkB;CAClB,mBAAmB;AACrB;;;;;;AAOA,MAAa,sBAAsB;EAChC,gBAAgB,WAAW,YAAY,EAAE,MAAM,SAAS,KAAK;EAC7D,gBAAgB,WAAW,aAAa,EAAE,MAAM,SAAS,WAAW;EACpE,gBAAgB,WAAW,YAAY,EAAE,MAAM,SAAS,mBAAmB;EAC3E,gBAAgB,WAAW,aAAa,EAAE,MAAM,SAAS,WAAW;EACpE,gBAAgB,WAAW,SAAS,EAAE,MAAM,SAAS,YAAY;EACjE,gBAAgB,WAAW,YAAY,EAAE,MAAM,SAAS,UAAU;EAClE,gBAAgB,WAAW,QAAQ,EAAE,MAAM,SAAS,MAAM;EAC1D,gBAAgB,WAAW,OAAO,EAAE,MAAM,SAAS,eAAe;EAClE,gBAAgB,WAAW,WAAW,EAAE,MAAM,SAAS,eAAe;EACtE,gBAAgB,QAAQ,kBAAkB,EAAE,MAAM,SAAS,gBAAgB;EAC3E,gBAAgB,QAAQ,qBAAqB,EAAE,MAAM,SAAS,mBAAmB;EACjF,gBAAgB,QAAQ,eAAe,EAAE,MAAM,SAAS,aAAa;EACrE,gBAAgB,IAAI,cAAc,EAAE,MAAM,SAAS,YAAY;AAClE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,2BAA2B,EAC3B,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,wBAAwB,GACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"request-sandbox-access.d.ts","sourceRoot":"","sources":["../../src/tools/request-sandbox-access.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2BH,eAAO,MAAM,wBAAwB,sKA4F5B,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"request-sandbox-access.js","names":["os","path"],"sources":["../../src/tools/request-sandbox-access.ts"],"sourcesContent":["/**\n * request_access tool — requests permission to access a directory outside the project root.\n * The user can approve or deny the request via TUI dialog.\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createTool } from '@mastra/core/tools';\nimport { LocalFilesystem } from '@mastra/core/workspace';\nimport { z } from 'zod';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathAllowed, getAllowedPathsFromContext } from './utils.js';\n\nfunction expandTilde(p: string): string {\n if (p === '~') return os.homedir();\n if (p.startsWith('~/') || p.startsWith('~\\\\')) return path.join(os.homedir(), p.slice(2));\n return p;\n}\n\ntype RequestSandboxAccessInput = {\n path: string;\n reason: string;\n};\n\nconst requestSandboxAccessInputSchema = z.object({\n path: z.string().min(1).describe('The absolute path to the directory you need access to.'),\n reason: z.string().min(1).describe('Brief explanation of why you need access to this directory.'),\n});\n\nexport const requestSandboxAccessTool = createTool({\n id: 'request_access',\n description: `Request permission to access a directory outside the current project. Use this when you need to read or write files in a directory that is not within the project root. The user will be prompted to approve or deny the request.`,\n inputSchema: requestSandboxAccessInputSchema,\n suspendSchema: z.object({\n kind: z.literal('sandbox_access_request'),\n path: z.string(),\n reason: z.string(),\n }),\n resumeSchema: z.union([z.string(), z.array(z.string())]),\n execute: async ({ path: requestedPath, reason }: RequestSandboxAccessInput, context: any) => {\n try {\n const agentControllerCtx = context?.requestContext?.get('controller') as\n | AgentControllerRequestContext<MastraCodeState>\n | undefined;\n\n // Resolve to absolute path (expand ~ first since Node path APIs don't handle it)\n const projectRoot = agentControllerCtx?.getState()?.projectPath ?? process.cwd();\n const expanded = expandTilde(requestedPath);\n const absolutePath = path.isAbsolute(expanded) ? expanded : path.resolve(projectRoot, expanded);\n\n // Check if already allowed\n const allowedPaths = getAllowedPathsFromContext(context);\n if (isPathAllowed(absolutePath, projectRoot, allowedPaths)) {\n return {\n content: `Access already granted: \"${absolutePath}\" is within the project root or allowed paths.`,\n isError: false,\n };\n }\n\n const suspend = context?.agent?.suspend ?? context?.suspend;\n const resumeData = context?.agent?.resumeData ?? context?.resumeData;\n\n // First pass: pause via the native tool-suspension primitive so the host can\n // prompt the user. The suspend payload carries the request details; the host\n // resumes with the user's answer as resume data.\n if (resumeData === undefined) {\n if (!suspend) {\n return {\n content: `Cannot request sandbox access: interactive context not available. The user should manually run /sandbox add ${absolutePath}`,\n isError: true,\n };\n }\n await suspend({ kind: 'sandbox_access_request', path: absolutePath, reason });\n return;\n }\n\n const answerText = Array.isArray(resumeData) ? resumeData.join(', ') : String(resumeData);\n const approved = answerText.toLowerCase().startsWith('y') || answerText.toLowerCase() === 'approve';\n if (approved) {\n // Persist to controller state first (and await it) so the value is\n // committed before the next tool call re-derives the workspace's\n // allowed paths from state. The workspace factory rebuilds the\n // filesystem allowlist from `sandboxAllowedPaths` on every call\n // (getDynamicWorkspace), so an unawaited setState would let that\n // rebuild clobber the in-turn widen below before the grant lands.\n const controllerState = agentControllerCtx?.getState();\n const currentAllowed = (controllerState?.sandboxAllowedPaths as string[] | undefined) ?? [];\n const nextAllowed = currentAllowed.includes(absolutePath) ? currentAllowed : [...currentAllowed, absolutePath];\n if (!currentAllowed.includes(absolutePath)) {\n await agentControllerCtx?.setState({\n sandboxAllowedPaths: nextAllowed,\n });\n }\n\n // Also update the live workspace filesystem immediately so tools in\n // the same turn (e.g. `view`) can access the path without waiting for\n // a fresh workspace build. The resolved workspace is carried on the\n // controller request context — the tool-execution context does not expose\n // it — so read the filesystem from there.\n const fs = agentControllerCtx?.workspace?.filesystem ?? context?.workspace?.filesystem;\n if (fs instanceof LocalFilesystem) {\n fs.setAllowedPaths((prev: readonly string[]) => [...prev, absolutePath]);\n }\n\n return {\n content: `Access granted: \"${absolutePath}\" has been added to allowed paths. You can now access files in this directory.`,\n isError: false,\n };\n }\n return {\n content: `Access denied: The user declined access to \"${absolutePath}\".`,\n isError: false,\n };\n } catch (error) {\n const msg = error instanceof Error ? error.message : 'Unknown error';\n return {\n content: `Failed to request sandbox access: ${msg}`,\n isError: true,\n };\n }\n },\n} as any);\n"],"mappings":";;;;;;;;;;;AAcA,SAAS,YAAY,GAAmB;CACtC,IAAI,MAAM,KAAK,OAAOA,KAAG,QAAQ;CACjC,IAAI,EAAE,WAAW,IAAI,KAAK,EAAE,WAAW,KAAK,GAAG,OAAOC,OAAK,KAAKD,KAAG,QAAQ,GAAG,EAAE,MAAM,CAAC,CAAC;CACxF,OAAO;AACT;AAOA,MAAM,kCAAkC,EAAE,OAAO;CAC/C,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,wDAAwD;CACzF,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,6DAA6D;AAClG,CAAC;AAED,MAAa,2BAA2B,WAAW;CACjD,IAAI;CACJ,aAAa;CACb,aAAa;CACb,eAAe,EAAE,OAAO;EACtB,MAAM,EAAE,QAAQ,wBAAwB;EACxC,MAAM,EAAE,OAAO;EACf,QAAQ,EAAE,OAAO;CACnB,CAAC;CACD,cAAc,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACvD,SAAS,OAAO,EAAE,MAAM,eAAe,UAAqC,YAAiB;EAC3F,IAAI;GACF,MAAM,qBA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AO;GAEd,OAAO;IACL,SAAS,qCAFC,iBAAiB,QAAQ,MAAM,UAAU;IAGnD,SAAS;GACX;EACF;CACF;AACF,CAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/tools/utils.ts"],"names":[],"mappings":"AAIA;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,YAAY,GAAE,MAAM,EAAO,GAAG,OAAO,CAK3G;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,WAAW,EAAE;IAAE,cAAc,CAAC,EAAE;QAAE,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAA;KAAE,CAAA;CAAE,GAAG,SAAS,GAC9E,MAAM,EAAE,CAgBV"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":["path"],"sources":["../../src/tools/utils.ts"],"sourcesContent":["import * as path from 'node:path';\nimport { buildSkillPaths } from '../agents/workspace.js';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\n\n/**\n * Check whether `targetPath` falls inside `projectRoot` or any of the\n * additional `allowedPaths`. All arguments are expected to be absolute.\n *\n * Returns `true` when access should be **allowed**.\n */\nexport function isPathAllowed(targetPath: string, projectRoot: string, allowedPaths: string[] = []): boolean {\n const resolved = path.resolve(targetPath);\n const roots = [projectRoot, ...allowedPaths].map(p => path.resolve(p));\n\n return roots.some(root => resolved === root || resolved.startsWith(root + path.sep));\n}\n\n/**\n * Read allowed paths from the Mastra controller runtime context.\n * Combines skill paths (computed dynamically from projectPath and configDir)\n * with user-approved sandbox paths from controller state so that both parent\n * and subagent tools have the same access.\n * Returns default skill paths when the context is unavailable (e.g. in tests).\n */\nexport function getAllowedPathsFromContext(\n toolContext: { requestContext?: { get: (key: string) => unknown } } | undefined,\n): string[] {\n const agentControllerCtx = toolContext?.requestContext?.get('controller') as\n | {\n getState?: () => { sandboxAllowedPaths?: string[]; projectPath?: string; configDir?: string };\n session?: {\n state?: { get?: () => { sandboxAllowedPaths?: string[]; projectPath?: string; configDir?: string } };\n };\n }\n | undefined;\n const state = agentControllerCtx?.getState?.() ?? agentControllerCtx?.session?.state?.get?.();\n const projectPath = state?.projectPath ? path.resolve(state.projectPath) : process.cwd();\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const skillPaths = buildSkillPaths(projectPath, configDir);\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n\n return [...skillPaths, ...sandboxPaths];\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,cAAc,YAAoB,aAAqB,eAAyB,CAAC,GAAY;CAC3G,MAAM,WAAWA,OAAK,QAAQ,UAAU;CAGxC,OAFc,CAAC,aAAa,GAAG,YAAY,CAAC,CAAC,KAAI,MAAKA,OAAK,QAAQ,CAAC,CAEzD,CAAC,CAAC,MAAK,SAAQ,aAAa,QAAQ,SAAS,WAAW,OAAOA,OAAK,GAAG,CAAC;AACrF;;;;;;;;AASA,SAAgB,2BACd,aACU;CACV,MAAM,qBAAqB,aAAa,gBAAgB,IAAI,YAAY;CAQxE,MAAM,QAAQ,oBAAoB,WAAW,KAAK,oBAAoB,SAAS,OAAO,MAAM;CAC5F,MAAM,cAAc,OAAO,cAAcA,OAAK,QAAQ,MAAM,WAAW,IAAI,QAAQ,IAAI;CACvF,MAAM,YAAY,OAAO,aAAA;CACzB,MAAM,aAAa,gBAAgB,aAAa,SAAS;CACzD,MAAM,eAAe,OAAO,uBAAuB,CAAC;CAEpD,OAAO,CAAC,GAAG,YAAY,GAAG,YAAY;AACxC"}