@mastra/code-sdk 1.2.0-alpha.1 → 1.2.0-alpha.13

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 (71) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/dist/agents/credential-resolver.d.ts +6 -0
  3. package/dist/agents/credential-resolver.d.ts.map +1 -1
  4. package/dist/agents/credential-resolver.js +14 -4
  5. package/dist/agents/credential-resolver.js.map +1 -1
  6. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  7. package/dist/agents/mastracode-gateway.js +27 -13
  8. package/dist/agents/mastracode-gateway.js.map +1 -1
  9. package/dist/agents/model.d.ts +16 -1
  10. package/dist/agents/model.d.ts.map +1 -1
  11. package/dist/agents/model.js +27 -6
  12. package/dist/agents/model.js.map +1 -1
  13. package/dist/agents/tools.js +1 -1
  14. package/dist/headless/cli.d.ts.map +1 -1
  15. package/dist/headless/cli.js +3 -0
  16. package/dist/headless/cli.js.map +1 -1
  17. package/dist/headless/flags.js +1 -1
  18. package/dist/headless/flags.js.map +1 -1
  19. package/dist/headless/types.d.ts +2 -2
  20. package/dist/headless/types.d.ts.map +1 -1
  21. package/dist/headless/types.js +2 -1
  22. package/dist/headless/types.js.map +1 -1
  23. package/dist/hooks/executor.d.ts.map +1 -1
  24. package/dist/hooks/executor.js +1 -0
  25. package/dist/hooks/executor.js.map +1 -1
  26. package/dist/hooks/manager.d.ts +9 -2
  27. package/dist/hooks/manager.d.ts.map +1 -1
  28. package/dist/hooks/manager.js +19 -3
  29. package/dist/hooks/manager.js.map +1 -1
  30. package/dist/hooks/types.d.ts +20 -0
  31. package/dist/hooks/types.d.ts.map +1 -1
  32. package/dist/hooks/types.js.map +1 -1
  33. package/dist/index.d.ts +68 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +179 -64
  36. package/dist/index.js.map +1 -1
  37. package/dist/onboarding/settings.d.ts +75 -6
  38. package/dist/onboarding/settings.d.ts.map +1 -1
  39. package/dist/onboarding/settings.js +128 -13
  40. package/dist/onboarding/settings.js.map +1 -1
  41. package/dist/plugin.d.ts +64 -1
  42. package/dist/plugin.d.ts.map +1 -1
  43. package/dist/plugin.js +3 -1
  44. package/dist/plugin.js.map +1 -1
  45. package/dist/plugins/loader.d.ts +7 -3
  46. package/dist/plugins/loader.d.ts.map +1 -1
  47. package/dist/plugins/loader.js +53 -1
  48. package/dist/plugins/loader.js.map +1 -1
  49. package/dist/plugins/manager.d.ts +36 -2
  50. package/dist/plugins/manager.d.ts.map +1 -1
  51. package/dist/plugins/manager.js +74 -2
  52. package/dist/plugins/manager.js.map +1 -1
  53. package/dist/plugins/signal-lane.d.ts +58 -0
  54. package/dist/plugins/signal-lane.d.ts.map +1 -0
  55. package/dist/plugins/signal-lane.js +166 -0
  56. package/dist/plugins/signal-lane.js.map +1 -0
  57. package/dist/plugins/types.d.ts +36 -0
  58. package/dist/plugins/types.d.ts.map +1 -1
  59. package/dist/providers/claude-max.d.ts +13 -0
  60. package/dist/providers/claude-max.d.ts.map +1 -1
  61. package/dist/providers/claude-max.js +83 -3
  62. package/dist/providers/claude-max.js.map +1 -1
  63. package/dist/providers/openai-codex.d.ts +3 -1
  64. package/dist/providers/openai-codex.d.ts.map +1 -1
  65. package/dist/providers/openai-codex.js +13 -2
  66. package/dist/providers/openai-codex.js.map +1 -1
  67. package/dist/schema.d.ts +11 -5
  68. package/dist/schema.d.ts.map +1 -1
  69. package/dist/schema.js +5 -4
  70. package/dist/schema.js.map +1 -1
  71. package/package.json +13 -13
package/CHANGELOG.md CHANGED
@@ -1,5 +1,180 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 1.2.0-alpha.13
4
+
5
+ ### Patch Changes
6
+
7
+ - Fixed woken notifications running against the controller-level workspace, which is `undefined` for dynamic workspace factories. They now use the workspace of the session that owns the target thread. ([#21144](https://github.com/mastra-ai/mastra/pull/21144))
8
+
9
+ - Updated dependencies [[`2e4624e`](https://github.com/mastra-ai/mastra/commit/2e4624edb6917e61249cb60ee377735e7af7e4a9), [`e6534fa`](https://github.com/mastra-ai/mastra/commit/e6534fab031216f6cb48c4c9907cbfdce9d60bc6), [`7fdcaa6`](https://github.com/mastra-ai/mastra/commit/7fdcaa66105d64290f9b14432a12ec99f39c4d3a), [`65b1183`](https://github.com/mastra-ai/mastra/commit/65b11832834f87a9bc8719391deb27559de5138a), [`5dba2a4`](https://github.com/mastra-ai/mastra/commit/5dba2a41600385751f5aace79878904e1972609d), [`cfd0d9e`](https://github.com/mastra-ai/mastra/commit/cfd0d9ec77ec3c69dd96f79cdb579e03d79f22ce), [`d9d93b2`](https://github.com/mastra-ai/mastra/commit/d9d93b25e4a65ad5fa153fa35be7ed149c8d587f)]:
10
+ - @mastra/core@1.58.0-alpha.12
11
+ - @mastra/observability@1.16.6-alpha.3
12
+ - @mastra/schema-compat@1.3.6-alpha.3
13
+ - @mastra/mcp@1.16.0-alpha.2
14
+ - @mastra/memory@1.26.1-alpha.6
15
+
16
+ ## 1.2.0-alpha.12
17
+
18
+ ### Minor Changes
19
+
20
+ - Added `processors` and `signalProviders` to the Mastra Code plugin contract, so a plugin can contribute more than tools. ([#20848](https://github.com/mastra-ai/mastra/pull/20848))
21
+
22
+ **Processors**
23
+
24
+ A plugin can now extend the agent pipeline directly, passing a bare array for input processors or an object for both lanes. Plugin processors run after the processors Mastra Code configures and before the channel and memory layers the Agent appends. The slot isn't configurable, and the processors are resolved before every LLM call. Enabling, disabling, or updating a plugin applies on the next request instead of requiring a restart.
25
+
26
+ **Signal providers**
27
+
28
+ A plugin can also ship a signal provider, which monitors an external source and pushes notifications into a thread. Providers are long-lived, so the SDK owns their lifecycle instead of handing them to the agent: it registers Mastra on them, connects them to the coding agent, starts them polling, and stops them when the plugin is updated, disabled, or uninstalled. That makes a provider installed from a GitHub repository survive a mid-session update of that repository. Only one provider with a given id runs at a time, and a provider that fails to start is isolated from the rest of its plugin.
29
+
30
+ Field resolvers also receive `getController()` and `getActiveSession()` on the plugin context, so a plugin can read the running session lazily at the moment it needs it.
31
+
32
+ For embedders that inject their own `pluginManager` into `createMastraCode`: the `PluginManager` contract now also requires `onReload`, `getPluginSignalProviders`, and `setRuntime`, so hand-built manager implementations must add these methods.
33
+
34
+ ### Patch Changes
35
+
36
+ - Fixed deferred notification deliveries failing with "No model selected" when the woken thread had no request context. The notification dispatch workflow re-sends deferred and summarized notifications long after the originating send, so any stream options attached to the original signal are gone; waking an idle thread then had no way to resolve a model. The notification delivery policy now drives the fix: `NotificationDeliveryDecision` accepts `streamOptions`, and the dispatcher re-runs the agent's delivery policy at delivery time (via the new `agent.resolveNotificationDeliveryDecision()`) to attach freshly resolved stream options to both individual and summary deliveries. Only `streamOptions` is honored at dispatch time; the record's persisted schedule still governs when and how it is delivered. Receipt-time sends also honor the policy's `streamOptions` now: an immediate deliver or summarize-now wake attaches them too, with caller-supplied stream options taking precedence. Mastra Code wires its session-based stream options resolver through the Code Agent's `deliveryPolicy.decide`, layered on the default decision logic. This fix applies to threads whose session is live in the current process; deliveries with no resolvable session fall back to a bare wake, and the "No model selected" error now distinguishes the case where a run started without any controller session context. This re-lands the capability removed by the #18637 revert in the policy-driven shape that revert called for, and the `@mastra/github-signals` bump only widens its `getNotificationStreamOptions` callback return type to allow `undefined`. ([#21113](https://github.com/mastra-ai/mastra/pull/21113))
37
+
38
+ - Updated dependencies [[`b8ce7ec`](https://github.com/mastra-ai/mastra/commit/b8ce7ec96e39343c6c2f36d12d68a9ad816c09f7), [`a3a3624`](https://github.com/mastra-ai/mastra/commit/a3a3624f646b98e409424d8defccbd334da9e8b8), [`6246914`](https://github.com/mastra-ai/mastra/commit/62469146636911f3cbbe0880bd011c6a897a59a7), [`1315d8f`](https://github.com/mastra-ai/mastra/commit/1315d8f17e8e7acb61cca46b72a1d42f6d00d289), [`3f73c07`](https://github.com/mastra-ai/mastra/commit/3f73c076727e8c36b4fff7a1b40290fb68957fa8), [`7c1ebb1`](https://github.com/mastra-ai/mastra/commit/7c1ebb15690c4b3f0eabb19077cf8af573311e57), [`32980a3`](https://github.com/mastra-ai/mastra/commit/32980a3e2413d0274ac244d32c37d910edc13f00), [`261edb9`](https://github.com/mastra-ai/mastra/commit/261edb9bc0cfbed2b77090b87562307a360f1a04), [`4bcdfaf`](https://github.com/mastra-ai/mastra/commit/4bcdfaf0eac3199d7cb171b0a19a92c9c341eea4), [`1b1dd7b`](https://github.com/mastra-ai/mastra/commit/1b1dd7bc0e59b7a8bfabd09a3eec1ccd95b4c2f3), [`af4636a`](https://github.com/mastra-ai/mastra/commit/af4636a74463275d71c1d13a38f7d2b738f128bf), [`a463cdf`](https://github.com/mastra-ai/mastra/commit/a463cdf1c95c3059e70f0bff27959e8558bb899d), [`0ea6b80`](https://github.com/mastra-ai/mastra/commit/0ea6b8001408ce02b56e8be0536b0fd8cbaf8ad2)]:
39
+ - @mastra/core@1.58.0-alpha.11
40
+ - @mastra/github-signals@0.2.5-alpha.1
41
+ - @mastra/memory@1.26.1-alpha.5
42
+ - @mastra/mcp@1.16.0-alpha.2
43
+
44
+ ## 1.2.0-alpha.11
45
+
46
+ ### Patch Changes
47
+
48
+ - Updated dependencies [[`66bbfb5`](https://github.com/mastra-ai/mastra/commit/66bbfb5f05b473d39f88c0e4a481ccac41634f3a)]:
49
+ - @mastra/core@1.58.0-alpha.10
50
+
51
+ ## 1.2.0-alpha.10
52
+
53
+ ### Patch Changes
54
+
55
+ - Include worktree identity (`worktree_path`, `branch`, `main_repo_path`) in `SessionStart` and `SessionEnd` hook payloads when a session runs in a git worktree, so hooks can provision and tear down per-worktree resources. ([#21034](https://github.com/mastra-ai/mastra/pull/21034))
56
+
57
+ - Updated dependencies [[`86b7b77`](https://github.com/mastra-ai/mastra/commit/86b7b777980d30f66e1fd134a37d2af4c22e54cc), [`80a3324`](https://github.com/mastra-ai/mastra/commit/80a33245d3110204de6f56d61211523ffe338692), [`d9d2881`](https://github.com/mastra-ai/mastra/commit/d9d2881ede6dd6c023d144215fc812062aed0890), [`82e3365`](https://github.com/mastra-ai/mastra/commit/82e3365ef7c9bf7bee2e7a7029035ea262d68895), [`1b482c2`](https://github.com/mastra-ai/mastra/commit/1b482c2d89244dd758c41e5f927a2b44041388d2), [`e6a2860`](https://github.com/mastra-ai/mastra/commit/e6a2860649cc51f87d32d78b766ae2126446ba07), [`7bd85ea`](https://github.com/mastra-ai/mastra/commit/7bd85ea7588b71c25ce9f4019c88f8539be5dcbc)]:
58
+ - @mastra/core@1.58.0-alpha.9
59
+
60
+ ## 1.2.0-alpha.9
61
+
62
+ ### Patch Changes
63
+
64
+ - Updated dependencies [[`1c75e32`](https://github.com/mastra-ai/mastra/commit/1c75e32f7fc0b9fb6f548b4407feaec8a1440212), [`c47165c`](https://github.com/mastra-ai/mastra/commit/c47165c983c87594c6952f1fd2fa51a90205034c), [`e08e789`](https://github.com/mastra-ai/mastra/commit/e08e789c1bf4cd2fe46363f7a4728536ceccc9bd), [`35cc901`](https://github.com/mastra-ai/mastra/commit/35cc90102cf834a84827acaf9eee0b6d6d1e2a3b), [`a8b4cf0`](https://github.com/mastra-ai/mastra/commit/a8b4cf02823cffebc4751a53337dfacf097c1ae1), [`a53f19b`](https://github.com/mastra-ai/mastra/commit/a53f19b9badb8bd349fe2f885814e9db6b7d3c4b), [`f33264f`](https://github.com/mastra-ai/mastra/commit/f33264f517ae603279afd5c4251e2b40f6dd3618), [`689f2c4`](https://github.com/mastra-ai/mastra/commit/689f2c4b6c0835fe455702b01d21daa8abcd9331), [`eeae63e`](https://github.com/mastra-ai/mastra/commit/eeae63e7fbe8e1f237adc69bca6e2ac13c5ca907), [`4c186a0`](https://github.com/mastra-ai/mastra/commit/4c186a017275f45e6ed4c09de0f89550e2d09e8c), [`b0fa077`](https://github.com/mastra-ai/mastra/commit/b0fa077bcbc9b08551846fe372a0d3d15b71ed72)]:
65
+ - @mastra/core@1.58.0-alpha.8
66
+ - @mastra/memory@1.26.1-alpha.4
67
+ - @mastra/libsql@1.20.0-alpha.2
68
+ - @mastra/pg@1.20.0-alpha.3
69
+
70
+ ## 1.2.0-alpha.8
71
+
72
+ ### Patch Changes
73
+
74
+ - Updated dependencies [[`7fb580a`](https://github.com/mastra-ai/mastra/commit/7fb580ac73fbcacf2ff00872a3395f73ae1b9fa5), [`333785c`](https://github.com/mastra-ai/mastra/commit/333785c93cbb01e42c60167e995457c28897ddbf), [`2eabc09`](https://github.com/mastra-ai/mastra/commit/2eabc097d86d52fbd0123da36a7c874154cc384f), [`83fa004`](https://github.com/mastra-ai/mastra/commit/83fa0044bfda8b703a83883dbd8bef204844d13f)]:
75
+ - @mastra/core@1.58.0-alpha.7
76
+
77
+ ## 1.2.0-alpha.7
78
+
79
+ ### Patch Changes
80
+
81
+ - Persist the browser viewport as a preset name, a `{ width, height }` size, or `'window'` in settings, and drop unusable stored values back to the default rather than passing them to the browser. ([#21010](https://github.com/mastra-ai/mastra/pull/21010))
82
+
83
+ - Fixed tenant credential resolution for session-based authentication providers. Background Factory runs now resolve the authenticated user and active organization from session-wrapped request context values instead of falling back to an empty credential store. ([#21008](https://github.com/mastra-ai/mastra/pull/21008))
84
+
85
+ - Updated dependencies [[`f59032a`](https://github.com/mastra-ai/mastra/commit/f59032a73699443555a08a479e7ac578975784f2), [`f59032a`](https://github.com/mastra-ai/mastra/commit/f59032a73699443555a08a479e7ac578975784f2), [`bf936e2`](https://github.com/mastra-ai/mastra/commit/bf936e2c89b2ff0dad5695b873ddc009ba96d41e)]:
86
+ - @mastra/core@1.58.0-alpha.6
87
+ - @mastra/agent-browser@0.5.1-alpha.0
88
+ - @mastra/stagehand@0.3.2-alpha.1
89
+
90
+ ## 1.2.0-alpha.6
91
+
92
+ ### Patch Changes
93
+
94
+ - Added a `model` option to Stagehand browser settings, so browser automation can run on a chosen provider instead of a fixed default: ([#20993](https://github.com/mastra-ai/mastra/pull/20993))
95
+
96
+ ```ts
97
+ import { createBrowserFromSettings } from '@mastra/code-sdk/onboarding/settings';
98
+
99
+ const browser = await createBrowserFromSettings({
100
+ enabled: true,
101
+ provider: 'stagehand',
102
+ headless: true,
103
+ stagehand: { env: 'LOCAL', model: 'anthropic/claude-sonnet-4-5' },
104
+ });
105
+ ```
106
+
107
+ The model must be provider-qualified as `<provider>/<model>`. Values Stagehand cannot resolve, such as a bare `gpt-4.1`, are ignored so the browser still starts.
108
+
109
+ - Updated dependencies [[`25956fc`](https://github.com/mastra-ai/mastra/commit/25956fc8841780d506acb22b618fdb4dcf6c4e21)]:
110
+ - @mastra/stagehand@0.3.2-alpha.0
111
+
112
+ ## 1.2.0-alpha.5
113
+
114
+ ### Patch Changes
115
+
116
+ - Updated dependencies [[`6445eba`](https://github.com/mastra-ai/mastra/commit/6445eba6020abac681aba1cc9289f446cb400cbe), [`deaf0c4`](https://github.com/mastra-ai/mastra/commit/deaf0c4c38fe2e988a094c63bbd8899436f4e579), [`df31eb0`](https://github.com/mastra-ai/mastra/commit/df31eb0c7087d782a0d9346e467f9a4af4b0eef6), [`59866f2`](https://github.com/mastra-ai/mastra/commit/59866f2e0a7986bea3b418aaa2c2f79a77d33719), [`fcd0667`](https://github.com/mastra-ai/mastra/commit/fcd0667a4e378be35c9a1b1eb19cce78fbfd7282), [`bab06b1`](https://github.com/mastra-ai/mastra/commit/bab06b18923873a584bdfc71a6b4ec7fb4727fb7)]:
117
+ - @mastra/core@1.58.0-alpha.5
118
+ - @mastra/memory@1.26.1-alpha.3
119
+ - @mastra/libsql@1.20.0-alpha.1
120
+ - @mastra/pg@1.20.0-alpha.2
121
+
122
+ ## 1.2.0-alpha.4
123
+
124
+ ### Patch Changes
125
+
126
+ - Updated dependencies [[`76e5132`](https://github.com/mastra-ai/mastra/commit/76e51328dbc0749c8304e6b3f21e4401f451b081), [`0282e16`](https://github.com/mastra-ai/mastra/commit/0282e16115538c8e9b248b90f0748eb01cb5dc98)]:
127
+ - @mastra/core@1.58.0-alpha.4
128
+
129
+ ## 1.2.0-alpha.3
130
+
131
+ ### Minor Changes
132
+
133
+ - Add a reasoning-effort configuration surface across mastracode and Factory (fixes #20766): ([#20884](https://github.com/mastra-ai/mastra/pull/20884))
134
+
135
+ - New `max` thinking level (mapped to `reasoning effort: max` for OpenAI Codex and Anthropic `effort`).
136
+ - Anthropic extended-thinking wiring: the session thinking level now applies to anthropic/claude-opus-4-7 and other Anthropic models via provider thinking/effort options (previously OpenAI-only).
137
+ - New `models.modeThinkingDefaults` setting: per-mode (build/plan/fast) default thinking levels, resolved at request time with precedence session override → mode default → global `preferences.thinkingLevel`. Configuration changes now apply to the next request of every session, including automated Factory runs.
138
+ - Factory: new Settings → Defaults controls for editing global and per-mode thinking defaults in local deployments.
139
+ - TUI: `/think` now sets a session-only override, supports `/think default` to clear it, and `/think status` reports the effective level with provenance (session override / mode default / global default).
140
+
141
+ Example `settings.json` configuration:
142
+
143
+ ```json
144
+ {
145
+ "preferences": { "thinkingLevel": "medium" },
146
+ "models": {
147
+ "modeThinkingDefaults": {
148
+ "build": "high",
149
+ "plan": "max",
150
+ "fast": "off"
151
+ }
152
+ }
153
+ }
154
+ ```
155
+
156
+ ### Patch Changes
157
+
158
+ - Updated dependencies [[`cdd5c33`](https://github.com/mastra-ai/mastra/commit/cdd5c33ac6c7118a9f139e6dc0e14e6a8ae31658), [`cdd5c33`](https://github.com/mastra-ai/mastra/commit/cdd5c33ac6c7118a9f139e6dc0e14e6a8ae31658), [`6bff877`](https://github.com/mastra-ai/mastra/commit/6bff877e214695ff8d9c84b06c13a6e6bcf9f1ed), [`d7cf7fa`](https://github.com/mastra-ai/mastra/commit/d7cf7fafc1ae1b50bd8462dd0e6c671a8606db93), [`0f9a448`](https://github.com/mastra-ai/mastra/commit/0f9a448502157e59f7b76f24360ad497168f5ef8), [`289f4ce`](https://github.com/mastra-ai/mastra/commit/289f4ce16e3293370440172132c52ee787cbc09f), [`4f16ff8`](https://github.com/mastra-ai/mastra/commit/4f16ff824bf2f9b0ddc93f210477c10c8a4fb1ab), [`1c67d85`](https://github.com/mastra-ai/mastra/commit/1c67d85e9da8285662f4dbbf47e0378c3fee0747), [`03ebe06`](https://github.com/mastra-ai/mastra/commit/03ebe06aeb671d7127b700e53853ed0759e4c19f), [`ba24be6`](https://github.com/mastra-ai/mastra/commit/ba24be662439c331ab23a600041f93803c89eca8), [`842b5fe`](https://github.com/mastra-ai/mastra/commit/842b5fe22b6a7fa811bd14e48eb9af523ac989f2), [`80bdf3a`](https://github.com/mastra-ai/mastra/commit/80bdf3ae16ade6ff63bde0cb16fa2df8ab7dd4dd), [`195e83c`](https://github.com/mastra-ai/mastra/commit/195e83c077687f6016fd8090324975c8d8cea50b), [`9ba1247`](https://github.com/mastra-ai/mastra/commit/9ba12470c77f1c03642d720ce67e517e878f666e), [`fd96298`](https://github.com/mastra-ai/mastra/commit/fd96298a8367622f4ebfcaa97b5b6c1fbbd14564), [`9168b80`](https://github.com/mastra-ai/mastra/commit/9168b80120a82816b1b9f2385e788bf86fa5d9cd), [`6a84954`](https://github.com/mastra-ai/mastra/commit/6a84954a2667f85b6d59da652dab1bbff007ccb0), [`52d8ef0`](https://github.com/mastra-ai/mastra/commit/52d8ef03801f1deb7ee48532fc4190dd4a33916c), [`cdd5c33`](https://github.com/mastra-ai/mastra/commit/cdd5c33ac6c7118a9f139e6dc0e14e6a8ae31658), [`289f4ce`](https://github.com/mastra-ai/mastra/commit/289f4ce16e3293370440172132c52ee787cbc09f), [`edfe906`](https://github.com/mastra-ai/mastra/commit/edfe906f7926faf8c63c21b3c87e797985557feb), [`efd5c81`](https://github.com/mastra-ai/mastra/commit/efd5c81cc25fde3c2ddd86fc1178deb4ec176e19), [`43ea2a1`](https://github.com/mastra-ai/mastra/commit/43ea2a1f5c5867d0f41254047a786e96cd00798b), [`0976933`](https://github.com/mastra-ai/mastra/commit/0976933142333ec78451feef265b68bcb45aa5e7), [`242b945`](https://github.com/mastra-ai/mastra/commit/242b94558777bfbdeb42cbfea84afff0b6ad0633), [`fea5cae`](https://github.com/mastra-ai/mastra/commit/fea5caedc7e2cfea51784a15e015952692027abf), [`4b59f78`](https://github.com/mastra-ai/mastra/commit/4b59f786cbc9a7d1ef07a07517dbd4b96865e99d), [`9ba1247`](https://github.com/mastra-ai/mastra/commit/9ba12470c77f1c03642d720ce67e517e878f666e), [`7010c5d`](https://github.com/mastra-ai/mastra/commit/7010c5d15728bf9c5dfe4fb6b1bf80ce23bf143a)]:
159
+ - @mastra/core@1.58.0-alpha.3
160
+ - @mastra/observability@1.16.6-alpha.2
161
+ - @mastra/schema-compat@1.3.6-alpha.2
162
+ - @mastra/pg@1.20.0-alpha.1
163
+ - @mastra/memory@1.26.1-alpha.2
164
+ - @mastra/github-signals@0.2.5-alpha.0
165
+ - @mastra/mcp@1.16.0-alpha.1
166
+
167
+ ## 1.2.0-alpha.2
168
+
169
+ ### Patch Changes
170
+
171
+ - Updated dependencies [[`1bdfde1`](https://github.com/mastra-ai/mastra/commit/1bdfde1f4061b7c0550253a1512a2118debe7996), [`b4c89b4`](https://github.com/mastra-ai/mastra/commit/b4c89b4371b0c86da57403ad1a3b3ef0681f3128), [`e44e8f3`](https://github.com/mastra-ai/mastra/commit/e44e8f370b66c339ddcaba946d33da6d3c3f06cd), [`c967a5e`](https://github.com/mastra-ai/mastra/commit/c967a5eec150c5dc5418c4a4388982d1fb7ad27c), [`f53d5bd`](https://github.com/mastra-ai/mastra/commit/f53d5bd4885b29e4ac29a428a6044088ea8d6aa3), [`bda2235`](https://github.com/mastra-ai/mastra/commit/bda22353ee28f2df0eaea555f7cae1549f979c0b), [`a7eb4a1`](https://github.com/mastra-ai/mastra/commit/a7eb4a11450f6170274ed5141bffe821d4fdd5a6), [`2f9ef3f`](https://github.com/mastra-ai/mastra/commit/2f9ef3f4ca06fc2dcdd5088c26b7f4da6a016791), [`e7eefcb`](https://github.com/mastra-ai/mastra/commit/e7eefcb162cda7c493e8c3bf43050ead0efbcb2c), [`4d7aca2`](https://github.com/mastra-ai/mastra/commit/4d7aca2fe75f225c83d1502d63079568e6ec163f), [`c4ec889`](https://github.com/mastra-ai/mastra/commit/c4ec889561c0264c43f66d04d587bee4ce35e792), [`9be8878`](https://github.com/mastra-ai/mastra/commit/9be8878dcf0388e84fc4873e0eec27bd49b881a4)]:
172
+ - @mastra/observability@1.16.6-alpha.1
173
+ - @mastra/core@1.58.0-alpha.2
174
+ - @mastra/schema-compat@1.3.6-alpha.1
175
+ - @mastra/mcp@1.16.0-alpha.0
176
+ - @mastra/memory@1.26.1-alpha.1
177
+
3
178
  ## 1.2.0-alpha.1
4
179
 
5
180
  ### Minor Changes
@@ -39,6 +39,12 @@ export declare function hasCredentialStoreProvider(): boolean;
39
39
  * Derive the calling tenant from a request context, if an authenticated web
40
40
  * user was stashed on it. Mirrors the web layer's stable-id resolution
41
41
  * (`workosId` falling back to the provider `id`).
42
+ *
43
+ * The value under `user` is whatever the active auth provider's
44
+ * `authenticateToken` returned, so its shape follows the provider: a flat user
45
+ * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the
46
+ * flat shape resolves no tenant at all for the wrapper, which in deployed mode
47
+ * fails closed to an empty credential store.
42
48
  */
43
49
  export declare function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined;
44
50
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"credential-resolver.d.ts","sourceRoot":"","sources":["../../src/agents/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,gBAAgB,KAAK,eAAe,GAAG,SAAS,CAAC;AAkBhG,mFAAmF;AACnF,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,IAAI,CAE9F;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AASD;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,gBAAgB,GAAG,SAAS,CAM7G;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,SAAS,CAKnG"}
1
+ {"version":3,"file":"credential-resolver.d.ts","sourceRoot":"","sources":["../../src/agents/credential-resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,qDAAqD;AACrD,MAAM,WAAW,gBAAgB;IAC/B,iFAAiF;IACjF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,MAAM,EAAE,gBAAgB,KAAK,eAAe,GAAG,SAAS,CAAC;AAkBhG,mFAAmF;AACnF,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,IAAI,CAE9F;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAkBD;;;;;;;;;;GAUG;AACH,wBAAgB,+BAA+B,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,gBAAgB,GAAG,SAAS,CAiB7G;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,SAAS,CAKnG"}
@@ -23,14 +23,24 @@ function hasCredentialStoreProvider() {
23
23
  * Derive the calling tenant from a request context, if an authenticated web
24
24
  * user was stashed on it. Mirrors the web layer's stable-id resolution
25
25
  * (`workosId` falling back to the provider `id`).
26
+ *
27
+ * The value under `user` is whatever the active auth provider's
28
+ * `authenticateToken` returned, so its shape follows the provider: a flat user
29
+ * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the
30
+ * flat shape resolves no tenant at all for the wrapper, which in deployed mode
31
+ * fails closed to an empty credential store.
26
32
  */
27
33
  function resolveTenantFromRequestContext(requestContext) {
28
- const user = requestContext?.get("user");
29
- if (!user || typeof user !== "object") return void 0;
34
+ const raw = requestContext?.get("user");
35
+ if (!raw || typeof raw !== "object") return void 0;
36
+ const wrapped = Boolean(raw.user && typeof raw.user === "object" && raw.session && typeof raw.session === "object");
37
+ const user = wrapped ? raw.user : raw;
38
+ const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;
30
39
  const userId = user.workosId ?? user.id;
31
- if (!userId) return void 0;
40
+ if (typeof userId !== "string" || !userId) return void 0;
41
+ if (orgId !== void 0 && typeof orgId !== "string") return void 0;
32
42
  return {
33
- orgId: user.organizationId,
43
+ orgId,
34
44
  userId
35
45
  };
36
46
  }
@@ -1 +1 @@
1
- {"version":3,"file":"credential-resolver.js","names":[],"sources":["../../src/agents/credential-resolver.ts"],"sourcesContent":["/**\n * Per-tenant credential resolution seam for deployed (multi-user) servers.\n *\n * Locally, model resolution reads the server-global file-backed `AuthStorage`.\n * A deployed web host registers a {@link CredentialStoreProvider} at boot; from\n * then on `resolveModel` derives the calling tenant from the request context\n * (the web auth gate stashes the authenticated user under the `user` key) and\n * resolves credentials through the tenant's own store — user credentials over\n * org credentials over server env vars, with OAuth refresh owned by the store.\n *\n * When no provider is registered (TUI, local web), everything falls through to\n * the existing global behavior unchanged.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { CredentialStore } from '../auth/types.js';\n\n/** The identity a credential lookup is scoped to. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id from the web auth adapter. */\n userId: string;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back\n * to the global store (e.g. tenant storage temporarily unavailable). Must be\n * synchronous — implementations serve from a primed snapshot and do\n * authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\n\nconst unavailableTenantCredentialStore: CredentialStore = {\n allowEnvironmentFallback: false,\n reload() {},\n get() {\n return undefined;\n },\n getStoredApiKey() {\n return undefined;\n },\n async getApiKey() {\n return undefined;\n },\n};\n\n/** Register (or clear) the tenant credential store provider. Deployed-web only. */\nexport function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void {\n credentialStoreProvider = provider;\n}\n\n/**\n * Whether a tenant provider is registered. Used to disable the\n * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant\n * credentials must never leak into process-global env vars.\n */\nexport function hasCredentialStoreProvider(): boolean {\n return credentialStoreProvider !== undefined;\n}\n\n/** Shape the web auth gate stashes on the request context under `user`. */\ninterface RequestContextUser {\n workosId?: string;\n id?: string;\n organizationId?: string;\n}\n\n/**\n * Derive the calling tenant from a request context, if an authenticated web\n * user was stashed on it. Mirrors the web layer's stable-id resolution\n * (`workosId` falling back to the provider `id`).\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n const user = requestContext?.get('user') as RequestContextUser | undefined;\n if (!user || typeof user !== 'object') return undefined;\n const userId = user.workosId ?? user.id;\n if (!userId) return undefined;\n return { orgId: user.organizationId, userId };\n}\n\n/**\n * Resolve the credential store for a request. Local mode returns `undefined`\n * and keeps the global `AuthStorage` behavior. Once deployed web registers a\n * provider, missing tenant identity or unavailable tenant storage fails closed\n * through an empty store that also disables process-environment fallback.\n */\nexport function resolveCredentialStore(requestContext?: RequestContext): CredentialStore | undefined {\n if (!credentialStoreProvider) return undefined;\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return unavailableTenantCredentialStore;\n return credentialStoreProvider(tenant) ?? unavailableTenantCredentialStore;\n}\n"],"mappings":";AAiCA,IAAI;AAEJ,MAAM,mCAAoD;CACxD,0BAA0B;CAC1B,SAAS,CAAC;CACV,MAAM,CAEN;CACA,kBAAkB,CAElB;CACA,MAAM,YAAY,CAElB;AACF;;AAGA,SAAgB,2BAA2B,UAAqD;CAC9F,0BAA0B;AAC5B;;;;;;AAOA,SAAgB,6BAAsC;CACpD,OAAO,4BAA4B,KAAA;AACrC;;;;;;AAcA,SAAgB,gCAAgC,gBAA+D;CAC7G,MAAM,OAAO,gBAAgB,IAAI,MAAM;CACvC,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAA;CAC9C,MAAM,SAAS,KAAK,YAAY,KAAK;CACrC,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EAAE,OAAO,KAAK;EAAgB;CAAO;AAC9C;;;;;;;AAQA,SAAgB,uBAAuB,gBAA8D;CACnG,IAAI,CAAC,yBAAyB,OAAO,KAAA;CACrC,MAAM,SAAS,gCAAgC,cAAc;CAC7D,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,wBAAwB,MAAM,KAAK;AAC5C"}
1
+ {"version":3,"file":"credential-resolver.js","names":[],"sources":["../../src/agents/credential-resolver.ts"],"sourcesContent":["/**\n * Per-tenant credential resolution seam for deployed (multi-user) servers.\n *\n * Locally, model resolution reads the server-global file-backed `AuthStorage`.\n * A deployed web host registers a {@link CredentialStoreProvider} at boot; from\n * then on `resolveModel` derives the calling tenant from the request context\n * (the web auth gate stashes the authenticated user under the `user` key) and\n * resolves credentials through the tenant's own store — user credentials over\n * org credentials over server env vars, with OAuth refresh owned by the store.\n *\n * When no provider is registered (TUI, local web), everything falls through to\n * the existing global behavior unchanged.\n */\n\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { CredentialStore } from '../auth/types.js';\n\n/** The identity a credential lookup is scoped to. */\nexport interface CredentialTenant {\n /** Org tenant; absent for personal accounts (store impls may synthesize one). */\n orgId?: string;\n /** Stable user id from the web auth adapter. */\n userId: string;\n}\n\n/**\n * Returns a tenant-scoped {@link CredentialStore}, or `undefined` to fall back\n * to the global store (e.g. tenant storage temporarily unavailable). Must be\n * synchronous — implementations serve from a primed snapshot and do\n * authoritative async work inside `getApiKey`.\n */\nexport type CredentialStoreProvider = (tenant: CredentialTenant) => CredentialStore | undefined;\n\nlet credentialStoreProvider: CredentialStoreProvider | undefined;\n\nconst unavailableTenantCredentialStore: CredentialStore = {\n allowEnvironmentFallback: false,\n reload() {},\n get() {\n return undefined;\n },\n getStoredApiKey() {\n return undefined;\n },\n async getApiKey() {\n return undefined;\n },\n};\n\n/** Register (or clear) the tenant credential store provider. Deployed-web only. */\nexport function setCredentialStoreProvider(provider: CredentialStoreProvider | undefined): void {\n credentialStoreProvider = provider;\n}\n\n/**\n * Whether a tenant provider is registered. Used to disable the\n * `loadStoredApiKeysIntoEnv` side-channel in deployed mode — per-tenant\n * credentials must never leak into process-global env vars.\n */\nexport function hasCredentialStoreProvider(): boolean {\n return credentialStoreProvider !== undefined;\n}\n\n/** Shape the web auth gate stashes on the request context under `user`. */\ninterface RequestContextUser {\n workosId?: string;\n id?: string;\n organizationId?: string;\n}\n\n/**\n * Session-shaped `authenticateToken` results (better-auth) arrive as a wrapper\n * whose active org lives on the session half rather than on the user.\n */\ninterface RequestContextSession {\n user?: RequestContextUser;\n session?: { activeOrganizationId?: string };\n}\n\n/**\n * Derive the calling tenant from a request context, if an authenticated web\n * user was stashed on it. Mirrors the web layer's stable-id resolution\n * (`workosId` falling back to the provider `id`).\n *\n * The value under `user` is whatever the active auth provider's\n * `authenticateToken` returned, so its shape follows the provider: a flat user\n * (WorkOS) or a `{ session, user }` wrapper (better-auth). Reading only the\n * flat shape resolves no tenant at all for the wrapper, which in deployed mode\n * fails closed to an empty credential store.\n */\nexport function resolveTenantFromRequestContext(requestContext?: RequestContext): CredentialTenant | undefined {\n const raw = requestContext?.get('user') as (RequestContextUser & RequestContextSession) | undefined;\n if (!raw || typeof raw !== 'object') return undefined;\n\n // Precedence matches `toFactoryAuthUser` in `@mastra/factory`: a wrapper's org\n // comes from the session half only, never from the inner user. The two parsers\n // cannot share code across the package boundary, so they must agree by rule.\n const wrapped = Boolean(raw.user && typeof raw.user === 'object' && raw.session && typeof raw.session === 'object');\n const user = wrapped ? (raw.user as RequestContextUser) : raw;\n const orgId = wrapped ? raw.session?.activeOrganizationId : user.organizationId;\n const userId = user.workosId ?? user.id;\n // The slot holds whatever the provider returned, so the declared string\n // types are hopes, not guarantees. A non-string id must refuse the tenant\n // (fail closed), not flow onward as a mistyped key.\n if (typeof userId !== 'string' || !userId) return undefined;\n if (orgId !== undefined && typeof orgId !== 'string') return undefined;\n return { orgId, userId };\n}\n\n/**\n * Resolve the credential store for a request. Local mode returns `undefined`\n * and keeps the global `AuthStorage` behavior. Once deployed web registers a\n * provider, missing tenant identity or unavailable tenant storage fails closed\n * through an empty store that also disables process-environment fallback.\n */\nexport function resolveCredentialStore(requestContext?: RequestContext): CredentialStore | undefined {\n if (!credentialStoreProvider) return undefined;\n const tenant = resolveTenantFromRequestContext(requestContext);\n if (!tenant) return unavailableTenantCredentialStore;\n return credentialStoreProvider(tenant) ?? unavailableTenantCredentialStore;\n}\n"],"mappings":";AAiCA,IAAI;AAEJ,MAAM,mCAAoD;CACxD,0BAA0B;CAC1B,SAAS,CAAC;CACV,MAAM,CAEN;CACA,kBAAkB,CAElB;CACA,MAAM,YAAY,CAElB;AACF;;AAGA,SAAgB,2BAA2B,UAAqD;CAC9F,0BAA0B;AAC5B;;;;;;AAOA,SAAgB,6BAAsC;CACpD,OAAO,4BAA4B,KAAA;AACrC;;;;;;;;;;;;AA6BA,SAAgB,gCAAgC,gBAA+D;CAC7G,MAAM,MAAM,gBAAgB,IAAI,MAAM;CACtC,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,KAAA;CAK5C,MAAM,UAAU,QAAQ,IAAI,QAAQ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ICodexOAuthFetch, createCodexMiddleware, getEffectiveThinkingLevel, openaiCodexProvider } from "../providers/openai-codex.js";
3
3
  import { getCustomProviderId, loadSettings } from "../onboarding/settings.js";
4
4
  import { resolveCustomProviders } from "./custom-provider-source.js";
5
- import { buildAnthropicOAuthFetch, claudeCodeMiddleware, opencodeClaudeMaxProvider, promptCacheMiddleware } from "../providers/claude-max.js";
5
+ import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, opencodeClaudeMaxProvider, promptCacheMiddleware } from "../providers/claude-max.js";
6
6
  import { getCopilotModelCatalog, githubCopilotProvider } from "../providers/github-copilot.js";
7
7
  import { xaiProvider } from "../providers/xai.js";
8
8
  import { createOpenAI } from "@ai-sdk/openai";
@@ -63,13 +63,15 @@ function getOpenAIApiKey(credentials = authStorage) {
63
63
  if (dedicatedKey) return dedicatedKey;
64
64
  return credentials.allowEnvironmentFallback === false ? void 0 : process.env.OPENAI_API_KEY?.trim() || void 0;
65
65
  }
66
- function anthropicApiKeyProvider(modelId, apiKey, headers) {
66
+ function anthropicApiKeyProvider(modelId, apiKey, headers, thinkingLevel) {
67
+ const anthropic = createAnthropic({
68
+ apiKey,
69
+ headers
70
+ });
71
+ const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);
67
72
  return wrapLanguageModel({
68
- model: createAnthropic({
69
- apiKey,
70
- headers
71
- })(modelId),
72
- middleware: [promptCacheMiddleware]
73
+ model: anthropic(modelId),
74
+ middleware: [promptCacheMiddleware, ...thinkingMiddleware ? [thinkingMiddleware] : []]
73
75
  });
74
76
  }
75
77
  function openaiApiKeyProvider(modelId, apiKey, headers) {
@@ -330,6 +332,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
330
332
  #resolveAnthropicModel(args) {
331
333
  const bareModelId = normalizeAnthropicModelId(args.modelId);
332
334
  const storedCred = this.#credentials.get("anthropic");
335
+ const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);
333
336
  if (this.#routeThroughMastraGateway) {
334
337
  if (storedCred?.type === "oauth") return wrapLanguageModel({
335
338
  model: createAnthropic({
@@ -341,23 +344,34 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
341
344
  },
342
345
  fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials })
343
346
  })(bareModelId),
344
- middleware: [claudeCodeMiddleware, promptCacheMiddleware]
347
+ middleware: [
348
+ claudeCodeMiddleware,
349
+ promptCacheMiddleware,
350
+ ...thinkingMiddleware ? [thinkingMiddleware] : []
351
+ ]
345
352
  });
346
- return this.#mastraGateway.resolveLanguageModel({
353
+ const gatewayModel = this.#mastraGateway.resolveLanguageModel({
347
354
  ...args,
348
355
  modelId: bareModelId
349
356
  });
357
+ if (!thinkingMiddleware) return gatewayModel;
358
+ return wrapLanguageModel({
359
+ model: gatewayModel,
360
+ middleware: [thinkingMiddleware]
361
+ });
350
362
  }
351
363
  if (storedCred?.type === "oauth") return opencodeClaudeMaxProvider(bareModelId, {
352
364
  headers: args.headers,
353
- authStorage: this.#credentials
365
+ authStorage: this.#credentials,
366
+ thinkingLevel: this.#thinkingLevel
354
367
  });
355
- if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return anthropicApiKeyProvider(bareModelId, storedCred.key.trim(), args.headers);
368
+ if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) return anthropicApiKeyProvider(bareModelId, storedCred.key.trim(), args.headers, this.#thinkingLevel);
356
369
  const apiKey = getAnthropicApiKey(this.#credentials);
357
- if (apiKey) return anthropicApiKeyProvider(bareModelId, apiKey, args.headers);
370
+ if (apiKey) return anthropicApiKeyProvider(bareModelId, apiKey, args.headers, this.#thinkingLevel);
358
371
  return opencodeClaudeMaxProvider(bareModelId, {
359
372
  headers: args.headers,
360
- authStorage: this.#credentials
373
+ authStorage: this.#credentials,
374
+ thinkingLevel: this.#thinkingLevel
361
375
  });
362
376
  }
363
377
  #resolveOpenAIModel(args) {
@@ -1 +1 @@
1
- {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\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\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\nconst authStorage = new AuthStorage();\n\nexport function reloadAuthStorage() {\n authStorage.reload();\n}\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\nfunction normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\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;\n }\n\n const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const anthropic = createAnthropic({ apiKey, headers });\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware],\n });\n}\n\nfunction openaiApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(providerId: string, credentials: CredentialStore = authStorage): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n return credentials.getStoredApiKey(authProviderId)?.trim() || undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? authStorage;\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = authStorage,\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const storedCred = credentials.get(getAuthProviderId(request.providerId));\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\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 const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [claudeCodeMiddleware, promptCacheMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel({ ...args, modelId: bareModelId }) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(bareModelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAwCA,MAAa,gBAAgB;AAC7B,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AAErC,MAAM,4BAAoD;CACxD,WAAW;CACX,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,SAAS;AACX;AAqBA,MAAM,cAAc,IAAI,YAAY;AAEpC,SAAgB,oBAAoB;CAClC,YAAY,OAAO;AACrB;AAEA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,QAAQ,W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,YAAY;EACnD,IAAI,QACF,OAAO,wBAAwB,aAAa,QAAQ,KAAK,OAAO;EAIlE,OAAO,0BAA0B,aAAa;GAC5C,SAAS,KAAK;GACd,aAAa,KAAKA;EACpB,CAAC;CACH;CAEA,oBAAoB,MAOiB;EACnC,MAAM,aAAa,KAAKA,aAAa,IAAI,cAAc;EAEvD,IAAI,KAAKJ,4BAA4B;GACnC,IAAI,YAAY,SAAS,SAAS;IAEhC,MAAM,sBADkB,8BAA8B,UAAU,KAAK,SAC3B,CAAC,CAAC,UAAU,CAAoB;IAG1E,MAAM,kBAAkB,mCADD,0BAA0B,qBADX,KAAKC,kBAAkB,QAEW;IACxE,MAAM,aAAa,sBAAsB,eAAe;IAWxD,OAAO,kBAAkB;KACvB,OAXa,aAAa;MAC1B,QAAQ;MACR,SAAS,GAAG,KAAKH,sBAAsB;MACvC,SAAS;QACN,sBAAsB,UAAU,KAAK;OACtC,GAAG,KAAK;MACV;MACA,OAAO,2BAA2B;OAAE,aAAa,KAAKM;OAAc,YAAY;MAAM,CAAC;KACzF,CAGc,CAAC,CAAC,UAAU,mBAAmB;KAC3C,YAAY,CAAC,UAAU;IACzB,CAAC;GACH;GAEA,OAAO,KAAKP,eAAe,qBAAqB,IAAI;EACtD;EAEA,IAAI,YAAY,SAAS,SAEvB,OAAO,oBADiB,8BAA8B,UAAU,KAAK,SAC5B,CAAC,CAAC,UAAU,CAAoB,GAAG;GAC1E,eAAe,KAAKI;GACpB,SAAS,KAAK;GACd,aAAa,KAAKG;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBAAqB,KAAK,SAAS,QAAQ,KAAK,OAAO;CAIlE;AACF"}
1
+ {"version":3,"file":"mastracode-gateway.js","names":["#mastraGateway","#mastraGatewayBaseUrl","#mastraGatewayApiKey","#routeThroughMastraGateway","#thinkingLevel","#customProviders","#settingsPath","#credentials","#getCustomProviders","#resolveAnthropicModel","#resolveOpenAIModel"],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n opencodeClaudeMaxProvider,\n promptCacheMiddleware,\n} from '../providers/claude-max.js';\nimport { getCopilotModelCatalog, githubCopilotProvider } from '../providers/github-copilot.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n getEffectiveThinkingLevel,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nexport const OPENAI_PREFIX = 'openai/';\nexport const MASTRA_GATEWAY_PREFIX = 'mastra/';\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\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\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\nconst authStorage = new AuthStorage();\n\nexport function reloadAuthStorage() {\n authStorage.reload();\n}\n\nexport function stripMastraGatewayPrefix(modelId: string): string {\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;\n}\n\nfunction normalizeAnthropicModelId(modelId: string): string {\n return modelId.replace(/\\.(?=\\d)/g, '-');\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;\n }\n\n const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;\n return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = authStorage): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [promptCacheMiddleware, ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(modelId: string, apiKey: string, headers?: ModelRequestHeaders) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [],\n });\n}\n\nfunction getAuthProviderId(providerId: string): string {\n return providerId === 'openai' ? 'openai-codex' : providerId;\n}\n\nfunction getProviderAuthKey(providerId: string, credentials: CredentialStore = authStorage): string | undefined {\n const authProviderId = getAuthProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n return credentials.getStoredApiKey(authProviderId)?.trim() || undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...(PROVIDER_REGISTRY as Record<string, ProviderConfig>) };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? authStorage;\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n const customProvider = this.#getCustomProviders().find(\n provider => parsed.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = authStorage,\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const storedCred = credentials.get(getAuthProviderId(request.providerId));\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n try {\n const copilotModels = await getCopilotModelCatalog({ authStorage });\n providers['github-copilot'] = {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: copilotModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n }\n\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n const providerId = stripMastraGatewayPrefix(modelId).split('/', 1)[0];\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n return providerId ? (getProviderAuthKey(providerId, this.#credentials) ?? '') : '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#getCustomProviders().find(\n provider => request.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider?.apiKey) {\n return { apiKey: customProvider.apiKey, source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\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 const customProvider = this.#getCustomProviders().find(\n provider => args.providerId === getCustomProviderId(provider.name),\n );\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n });\n return provider.chatModel(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'moonshotai') {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId) as unknown as GatewayLanguageModel;\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return xaiProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (this.#routeThroughMastraGateway) {\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n return new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}` as `${string}/${string}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }) as any,\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n promptCacheMiddleware,\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n }) as unknown as GatewayLanguageModel;\n }\n\n const gatewayModel = this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n }) as GatewayLanguageModel;\n if (!thinkingMiddleware) return gatewayModel;\n return wrapLanguageModel({\n model: gatewayModel as any,\n middleware: [thinkingMiddleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n ) as unknown as GatewayLanguageModel;\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const requestedLevel: ThinkingLevel = this.#thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }) as any,\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware],\n }) as unknown as GatewayLanguageModel;\n }\n\n return this.#mastraGateway.resolveLanguageModel(args) as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel,\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers) as unknown as GatewayLanguageModel;\n }\n\n return undefined;\n }\n}\n"],"mappings":";;;;;;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a,KAAKM;OAAc,YAAY;MAAM,CAAC;KACzF,CAGc,CAAC,CAAC,UAAU,mBAAmB;KAC3C,YAAY,CAAC,UAAU;IACzB,CAAC;GACH;GAEA,OAAO,KAAKP,eAAe,qBAAqB,IAAI;EACtD;EAEA,IAAI,YAAY,SAAS,SAEvB,OAAO,oBADiB,8BAA8B,UAAU,KAAK,SAC5B,CAAC,CAAC,UAAU,CAAoB,GAAG;GAC1E,eAAe,KAAKI;GACpB,SAAS,KAAK;GACd,aAAa,KAAKG;EACpB,CAAC;EAGH,MAAM,SAAS,gBAAgB,KAAKA,YAAY;EAChD,IAAI,QACF,OAAO,qBAAqB,KAAK,SAAS,QAAQ,KAAK,OAAO;CAIlE;AACF"}
@@ -1,3 +1,4 @@
1
+ import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';
1
2
  import type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';
2
3
  import type { RequestContext } from '@mastra/core/request-context';
3
4
  import type { ThinkingLevel } from '../providers/openai-codex.js';
@@ -32,13 +33,27 @@ export declare function resolveModel(modelId: string, options?: {
32
33
  remapForCodexOAuth?: boolean;
33
34
  requestContext?: RequestContext;
34
35
  }): GatewayLanguageModel;
36
+ /**
37
+ * Resolve the effective thinking level for the current request.
38
+ *
39
+ * Precedence:
40
+ * 1. Session override (`state.thinkingLevel`, set via /think or the session
41
+ * settings panel).
42
+ * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).
43
+ * 3. Global default (`preferences.thinkingLevel`).
44
+ *
45
+ * Resolved per-request (not seeded at session start) so configuration changes
46
+ * apply to the next request of every session — including automated
47
+ * (rule-driven) Factory runs that nobody ever opens interactively.
48
+ */
49
+ export declare function resolveRequestThinkingLevel(agentControllerContext: AgentControllerRequestContext<any> | undefined, settingsPath?: string): ThinkingLevel;
35
50
  /**
36
51
  * Dynamic model function that reads the current model from controller state.
37
52
  * This allows runtime model switching via the /models picker.
38
53
  */
39
54
  export declare function getDynamicModel({ requestContext }: {
40
55
  requestContext: RequestContext;
41
- }): ResolvedModel;
56
+ }, settingsPath?: string): ResolvedModel;
42
57
  /**
43
58
  * Goal judge model resolver for the agent's `goal.judge` config. Resolves the
44
59
  * configured goal judge model through mastracode's gateway so provider
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/agents/model.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAGlE,OAAO,EAGL,iBAAiB,EAGlB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAExE,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EACjB,6BAA6B,EAC7B,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAClG,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,0BAA0B,CAAC;AAClC,YAAY,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAC1F,OAAO,EACL,wBAAwB,EACxB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,6BAA6B,CAAC;AACrC,YAAY,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAEzE,KAAK,aAAa,GAAG,oBAAoB,CAAC;AAa1C,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,wBAAwB,GAAG,iBAAiB,CAE5F;AAED,wBAAgB,oCAAoC,CAAC,OAAO,EAAE,2BAA2B,6DAIxF;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM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