@mastra/code-sdk 1.1.4-alpha.0 → 1.2.0-alpha.3
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.
- package/CHANGELOG.md +83 -0
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +27 -13
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/model.d.ts +16 -1
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +26 -7
- package/dist/agents/model.js.map +1 -1
- package/dist/headless/flags.js +1 -1
- package/dist/headless/flags.js.map +1 -1
- package/dist/headless/types.d.ts +2 -2
- package/dist/headless/types.d.ts.map +1 -1
- package/dist/headless/types.js +2 -1
- package/dist/headless/types.js.map +1 -1
- package/dist/hooks/executor.d.ts.map +1 -1
- package/dist/hooks/executor.js +1 -0
- package/dist/hooks/executor.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp/manager.d.ts +27 -0
- package/dist/mcp/manager.d.ts.map +1 -1
- package/dist/mcp/manager.js +128 -10
- package/dist/mcp/manager.js.map +1 -1
- package/dist/mcp/state.d.ts +33 -0
- package/dist/mcp/state.d.ts.map +1 -0
- package/dist/mcp/state.js +88 -0
- package/dist/mcp/state.js.map +1 -0
- package/dist/mcp/types.d.ts +13 -0
- package/dist/mcp/types.d.ts.map +1 -1
- package/dist/onboarding/settings.d.ts +37 -1
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +53 -3
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/providers/claude-max.d.ts +13 -0
- package/dist/providers/claude-max.d.ts.map +1 -1
- package/dist/providers/claude-max.js +83 -3
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/openai-codex.d.ts +3 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +13 -2
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/schema.d.ts +8 -2
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +3 -2
- package/dist/schema.js.map +1 -1
- package/package.json +12 -12
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,88 @@
|
|
|
1
1
|
# @mastra/code-sdk
|
|
2
2
|
|
|
3
|
+
## 1.2.0-alpha.3
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Add a reasoning-effort configuration surface across mastracode and Factory (fixes #20766): ([#20884](https://github.com/mastra-ai/mastra/pull/20884))
|
|
8
|
+
|
|
9
|
+
- New `max` thinking level (mapped to `reasoning effort: max` for OpenAI Codex and Anthropic `effort`).
|
|
10
|
+
- 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).
|
|
11
|
+
- 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.
|
|
12
|
+
- Factory: new Settings → Defaults controls for editing global and per-mode thinking defaults in local deployments.
|
|
13
|
+
- 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).
|
|
14
|
+
|
|
15
|
+
Example `settings.json` configuration:
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"preferences": { "thinkingLevel": "medium" },
|
|
20
|
+
"models": {
|
|
21
|
+
"modeThinkingDefaults": {
|
|
22
|
+
"build": "high",
|
|
23
|
+
"plan": "max",
|
|
24
|
+
"fast": "off"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Patch Changes
|
|
31
|
+
|
|
32
|
+
- 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)]:
|
|
33
|
+
- @mastra/core@1.58.0-alpha.3
|
|
34
|
+
- @mastra/observability@1.16.6-alpha.2
|
|
35
|
+
- @mastra/schema-compat@1.3.6-alpha.2
|
|
36
|
+
- @mastra/pg@1.20.0-alpha.1
|
|
37
|
+
- @mastra/memory@1.26.1-alpha.2
|
|
38
|
+
- @mastra/github-signals@0.2.5-alpha.0
|
|
39
|
+
- @mastra/mcp@1.16.0-alpha.1
|
|
40
|
+
|
|
41
|
+
## 1.2.0-alpha.2
|
|
42
|
+
|
|
43
|
+
### Patch Changes
|
|
44
|
+
|
|
45
|
+
- 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)]:
|
|
46
|
+
- @mastra/observability@1.16.6-alpha.1
|
|
47
|
+
- @mastra/core@1.58.0-alpha.2
|
|
48
|
+
- @mastra/schema-compat@1.3.6-alpha.1
|
|
49
|
+
- @mastra/mcp@1.16.0-alpha.0
|
|
50
|
+
- @mastra/memory@1.26.1-alpha.1
|
|
51
|
+
|
|
52
|
+
## 1.2.0-alpha.1
|
|
53
|
+
|
|
54
|
+
### Minor Changes
|
|
55
|
+
|
|
56
|
+
- Added MCP disable-state controls to the MCP manager. Servers can be disabled for the current project or for every project, the state persists across runs in an app-data `mcp-state.json` (user MCP config files are never mutated), and disabled servers stay visible in statuses via the new `disabled`/`disabledScope` fields on `McpServerStatus`. ([#20834](https://github.com/mastra-ai/mastra/pull/20834))
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
await mcpManager.setServerDisabled('filesystem', true); // project scope
|
|
60
|
+
await mcpManager.setServerDisabled('filesystem', true, { global: true }); // all projects
|
|
61
|
+
await mcpManager.setAllDisabled(true, { global: true }); // global kill switch
|
|
62
|
+
mcpManager.isAllDisabledGlobally();
|
|
63
|
+
mcpManager.getDisabledServers();
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Patch Changes
|
|
67
|
+
|
|
68
|
+
- dependencies updates: ([#19783](https://github.com/mastra-ai/mastra/pull/19783))
|
|
69
|
+
- Updated dependency [`posthog-node@^5.46.1` ↗︎](https://www.npmjs.com/package/posthog-node/v/5.46.1) (from `^5.37.0`, in `dependencies`)
|
|
70
|
+
|
|
71
|
+
- dependencies updates: ([#20406](https://github.com/mastra-ai/mastra/pull/20406))
|
|
72
|
+
- Updated dependency [`@aws-sdk/credential-providers@^3.1095.0` ↗︎](https://www.npmjs.com/package/@aws-sdk/credential-providers/v/3.1095.0) (from `^3.864.0`, in `dependencies`)
|
|
73
|
+
|
|
74
|
+
- Fixed custom provider models saved with a stray `mastracode/` prefix in settings, which broke selecting and using them after choosing them from `/models` (#20799) ([#20804](https://github.com/mastra-ai/mastra/pull/20804))
|
|
75
|
+
|
|
76
|
+
- Updated dependencies [[`e7109ee`](https://github.com/mastra-ai/mastra/commit/e7109ee6f731bacc79c885906f3c7dca8d8f013a), [`772c0c8`](https://github.com/mastra-ai/mastra/commit/772c0c897cec383258de2e6178147f8014767c7b), [`772c0c8`](https://github.com/mastra-ai/mastra/commit/772c0c897cec383258de2e6178147f8014767c7b), [`f5a17d9`](https://github.com/mastra-ai/mastra/commit/f5a17d95c19e7d4149996932bd8d1905089f031d), [`578bf2e`](https://github.com/mastra-ai/mastra/commit/578bf2e6a88e9d5b8bf502204e15a95dfbb679ae), [`06b2d87`](https://github.com/mastra-ai/mastra/commit/06b2d87e63bcdd0ed59215c6789692b9b12de376), [`ac01d63`](https://github.com/mastra-ai/mastra/commit/ac01d6355974aec73fdb8781449ed12bac582094), [`8627c23`](https://github.com/mastra-ai/mastra/commit/8627c23d794485fb97d533fc2a7a8323bfec2225), [`a810a05`](https://github.com/mastra-ai/mastra/commit/a810a058f62ad407cfc1701e0be36ae91145d7cf), [`26ff3b9`](https://github.com/mastra-ai/mastra/commit/26ff3b9144132bd8570e4796d436fb57a9a2bf24), [`3ff2be3`](https://github.com/mastra-ai/mastra/commit/3ff2be3a5a579d2e2d7084ba0624ec24faadce4d), [`f8da216`](https://github.com/mastra-ai/mastra/commit/f8da21633e7eb0e31c9ce0fc30567870d19416d3), [`e7a5da4`](https://github.com/mastra-ai/mastra/commit/e7a5da4ef8e4dd452d2f232961b4e682a85ffe43), [`c71e307`](https://github.com/mastra-ai/mastra/commit/c71e3077e69eae3f25aa628e3778f153a9d6ab36), [`e7a5da4`](https://github.com/mastra-ai/mastra/commit/e7a5da4ef8e4dd452d2f232961b4e682a85ffe43), [`a4f6806`](https://github.com/mastra-ai/mastra/commit/a4f68065d082af57770e7ee3d34996fdc914dbd1), [`6104347`](https://github.com/mastra-ai/mastra/commit/61043473ba6bfd0a25156824e853e13165562e6c), [`ffdfa25`](https://github.com/mastra-ai/mastra/commit/ffdfa25b5cdf3ecfd0c5a2e96363c3ba50995ce9), [`45bfb88`](https://github.com/mastra-ai/mastra/commit/45bfb88fd52f1dd3be20e2a38905777c96499c90), [`e3b9307`](https://github.com/mastra-ai/mastra/commit/e3b9307098daefbfae2a52ae2ef51bc9fc701190), [`d6834c5`](https://github.com/mastra-ai/mastra/commit/d6834c5a7866b16734d23900163c2414ed70d791), [`c52d346`](https://github.com/mastra-ai/mastra/commit/c52d3462ec831a5d95926ecd3d3373f5928ad2e5), [`0023e79`](https://github.com/mastra-ai/mastra/commit/0023e7919431078280abd11c89d1edeae35fcc69), [`c2ad51e`](https://github.com/mastra-ai/mastra/commit/c2ad51e2467f901eecba8c9f4a45e22a50bd7c18), [`3dc97ea`](https://github.com/mastra-ai/mastra/commit/3dc97ea415fad353b48a13095fad1835933cc12a), [`3d01cd3`](https://github.com/mastra-ai/mastra/commit/3d01cd387321b6f9c5cac31d487c84bf51b19c78), [`7bf3086`](https://github.com/mastra-ai/mastra/commit/7bf308663f0115ca74ad20554ade740f06640859), [`a8dd139`](https://github.com/mastra-ai/mastra/commit/a8dd1391a9fe9a6632c25809ef236980afa9a020), [`e5786be`](https://github.com/mastra-ai/mastra/commit/e5786be02bb903073082bd9d6da880ebaacc343f), [`e5786be`](https://github.com/mastra-ai/mastra/commit/e5786be02bb903073082bd9d6da880ebaacc343f), [`d6c63e4`](https://github.com/mastra-ai/mastra/commit/d6c63e4b757babb95a735d0e421d4dac67c1dcf1), [`2093fbd`](https://github.com/mastra-ai/mastra/commit/2093fbd53bb744bae19ec89f6d73db9a66fbe8a7), [`e7a5da4`](https://github.com/mastra-ai/mastra/commit/e7a5da4ef8e4dd452d2f232961b4e682a85ffe43), [`e4d3761`](https://github.com/mastra-ai/mastra/commit/e4d376143cf3322885a7e6e4048e536ce441f785), [`7b4393d`](https://github.com/mastra-ai/mastra/commit/7b4393d557411fdcf07b0e30e5acaf7cc85154ae)]:
|
|
77
|
+
- @mastra/core@1.58.0-alpha.1
|
|
78
|
+
- @mastra/libsql@1.20.0-alpha.0
|
|
79
|
+
- @mastra/pg@1.20.0-alpha.0
|
|
80
|
+
- @mastra/schema-compat@1.3.6-alpha.0
|
|
81
|
+
- @mastra/observability@1.16.6-alpha.0
|
|
82
|
+
- @mastra/mcp@1.16.0-alpha.0
|
|
83
|
+
- @mastra/memory@1.26.1-alpha.0
|
|
84
|
+
- @mastra/duckdb@1.6.1-alpha.0
|
|
85
|
+
|
|
3
86
|
## 1.1.4-alpha.0
|
|
4
87
|
|
|
5
88
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mastracode-gateway.d.ts","sourceRoot":"","sources":["../../src/agents/mastracode-gateway.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAwB,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AACtG,OAAO,EAGL,kBAAkB,EAGnB,MAAM,kBAAkB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MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAIrE,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAMjD,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,GAAG,SAAS;IAevE,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;CAsMzB"}
|
|
@@ -2,7 +2,7 @@ import { AuthStorage } from "../auth/storage.js";
|
|
|
2
2
|
import { THINKING_LEVEL_TO_REASONING_EFFORT, buildOpenAICodexOAuthFetch, 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:
|
|
69
|
-
|
|
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: [
|
|
347
|
+
middleware: [
|
|
348
|
+
claudeCodeMiddleware,
|
|
349
|
+
promptCacheMiddleware,
|
|
350
|
+
...thinkingMiddleware ? [thinkingMiddleware] : []
|
|
351
|
+
]
|
|
345
352
|
});
|
|
346
|
-
|
|
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,WAAA,SAAgC,IAAI,QAAQ,UAAU,CAA4B,IAAI;AACvG;AAEA,SAAS,0BAA0B,SAAyB;CAC1D,OAAO,QAAQ,QAAQ,aAAa,GAAG;AACzC;AAEA,SAAgB,8BAA8B,SAAyB;CACrE,MA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AOiB;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":";;;;;;;;;;;;;AAyCA,MAAa,gBAAgB;AAC7B,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AAErC,MAAM,4BAAoD;CACxD,WAAW;CACX,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,SAAS;AAC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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"}
|
package/dist/agents/model.d.ts
CHANGED
|
@@ -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":"
|
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/agents/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAOnE,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,GAAG,MAAM,CAEtD;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,aAAa,CAAC;IAAC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,cAAc,CAAA;CAAE,GACzG,oBAAoB,CA+EtB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,2BAA2B,CACzC,sBAAsB,EAAE,6BAA6B,CAAC,GAAG,CAAC,GAAG,SAAS,EACtE,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,CAKf;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,CAWf;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
|
package/dist/agents/model.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { loadSettings } from "../onboarding/settings.js";
|
|
1
|
+
import { loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
|
|
2
2
|
import { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
|
|
3
3
|
import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
|
|
4
4
|
import { hasCustomProvidersSource, resolveCustomProviders, setCustomProvidersSource } from "./custom-provider-source.js";
|
|
@@ -40,7 +40,9 @@ function resolveModel(modelId, options) {
|
|
|
40
40
|
const headers = getAgentControllerHeaders(options?.requestContext);
|
|
41
41
|
const settings = loadSettings();
|
|
42
42
|
const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;
|
|
43
|
-
const
|
|
43
|
+
const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix) ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1) : modelId;
|
|
44
|
+
const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;
|
|
45
|
+
const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);
|
|
44
46
|
const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);
|
|
45
47
|
const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);
|
|
46
48
|
const [providerId, ...modelParts] = normalizedModelId.split("/");
|
|
@@ -66,7 +68,6 @@ function resolveModel(modelId, options) {
|
|
|
66
68
|
const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();
|
|
67
69
|
const rawGatewayBase = settings.memoryGateway?.baseUrl ?? process.env["MASTRA_GATEWAY_URL"] ?? "https://gateway-api.mastra.ai";
|
|
68
70
|
const credentialStore = resolveCredentialStore(options?.requestContext);
|
|
69
|
-
const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;
|
|
70
71
|
const gateway = createMastraCodeGateway({
|
|
71
72
|
mastraGatewayBaseUrl: rawGatewayBase.replace(/\/+$/, "").replace(/\/v1$/, ""),
|
|
72
73
|
mastraGatewayApiKey: mgApiKey,
|
|
@@ -89,16 +90,34 @@ function resolveModel(modelId, options) {
|
|
|
89
90
|
});
|
|
90
91
|
}
|
|
91
92
|
/**
|
|
93
|
+
* Resolve the effective thinking level for the current request.
|
|
94
|
+
*
|
|
95
|
+
* Precedence:
|
|
96
|
+
* 1. Session override (`state.thinkingLevel`, set via /think or the session
|
|
97
|
+
* settings panel).
|
|
98
|
+
* 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).
|
|
99
|
+
* 3. Global default (`preferences.thinkingLevel`).
|
|
100
|
+
*
|
|
101
|
+
* Resolved per-request (not seeded at session start) so configuration changes
|
|
102
|
+
* apply to the next request of every session — including automated
|
|
103
|
+
* (rule-driven) Factory runs that nobody ever opens interactively.
|
|
104
|
+
*/
|
|
105
|
+
function resolveRequestThinkingLevel(agentControllerContext, settingsPath) {
|
|
106
|
+
const override = agentControllerContext?.state?.thinkingLevel;
|
|
107
|
+
if (override !== void 0) return override;
|
|
108
|
+
const modeId = agentControllerContext?.session?.modeId;
|
|
109
|
+
return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
92
112
|
* Dynamic model function that reads the current model from controller state.
|
|
93
113
|
* This allows runtime model switching via the /models picker.
|
|
94
114
|
*/
|
|
95
|
-
function getDynamicModel({ requestContext }) {
|
|
115
|
+
function getDynamicModel({ requestContext }, settingsPath) {
|
|
96
116
|
const agentControllerContext = requestContext.get("controller");
|
|
97
117
|
const modelId = agentControllerContext?.session?.modelId;
|
|
98
118
|
if (!modelId) throw new Error("No model selected. Use /models to select a model first.");
|
|
99
|
-
const thinkingLevel = agentControllerContext?.state?.thinkingLevel;
|
|
100
119
|
return resolveModel(modelId, {
|
|
101
|
-
thinkingLevel,
|
|
120
|
+
thinkingLevel: resolveRequestThinkingLevel(agentControllerContext, settingsPath),
|
|
102
121
|
remapForCodexOAuth: true,
|
|
103
122
|
requestContext
|
|
104
123
|
});
|
|
@@ -126,6 +145,6 @@ function getGoalJudgeModel({ requestContext }, settingsPath) {
|
|
|
126
145
|
});
|
|
127
146
|
}
|
|
128
147
|
//#endregion
|
|
129
|
-
export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, createMastraCodeGateway, createMastraCodeModelCatalogProvider, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
|
|
148
|
+
export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, createMastraCodeGateway, createMastraCodeModelCatalogProvider, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
|
|
130
149
|
|
|
131
150
|
//# sourceMappingURL=model.js.map
|
package/dist/agents/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevel; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const normalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? mgApiKey ?? '',\n headers,\n });\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel({ requestContext }: { requestContext: RequestContext }): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = agentControllerContext?.state?.thinkingLevel as ThinkingLevel | undefined;\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;AA0CA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAgB,wBAAwB,SAAsD;CAC5F,OAAO,IAAI,kBAAkB,OAAO;AACtC;AAEA,SAAgB,qCAAqC,SAAsC;CACzF,OAAO,mBAAmB,oBACtB,QAAQ,2BAA2B,IACnC,kBAAkB,2BAA2B,OAAO;AAC1D;;;;;;AAOA,SAAgB,eAAe,SAAyB;CACtD,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,aACd,SACA,SACsB;CACtB,kBAAkB;CAClB,MAAM,UAAU,0BAA0B,SAAS,cAAc;CACjE,MAAM,WAAW,aAAa;CAK9B,MAAM,sBAAsB,GAAG,sBAAsB;CACrD,MAAM,kBAAkB,QAAQ,WAAW,mBAAmB,IAC1D,QAAQ,MAAM,sBAAsB,SAAS,CAAC,IAC9C;CACJ,MAAM,uBAAuB,gBAAgB,WAAW,qBAAqB;CAC7E,MAAM,oBAAoB,yBAAyB,eAAe;CAClE,MAAM,CAAC,YAAY,GAAG,cAAc,kBAAkB,MAAM,GAAG;CAC/D,MAAM,cAAc,WAAW,KAAK,GAAG;CACvC,IAAI,CAAC,cAAc,CAAC,aAClB,MA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Ae,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevel; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? mgApiKey ?? '',\n headers,\n });\n}\n\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\nexport function resolveRequestThinkingLevel(\n agentControllerContext: AgentControllerRequestContext<any> | undefined,\n settingsPath?: string,\n): ThinkingLevel {\n const override = agentControllerContext?.state?.thinkingLevel as ThinkingLevel | undefined;\n if (override !== undefined) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;AA8CA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAgB,wBAAwB,SAAsD;CAC5F,OAAO,IAAI,kBAAkB,OAAO;AACtC;AAEA,SAAgB,qCAAqC,SAAsC;CACzF,OAAO,mBAAmB,oBACtB,QAAQ,2BAA2B,IACnC,kBAAkB,2BAA2B,OAAO;AAC1D;;;;;;AAOA,SAAgB,eAAe,SAAyB;CACtD,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,aACd,SACA,SACsB;CACtB,kBAAkB;CAClB,MAAM,UAAU,0BAA0B,SAAS,cAAc;CACjE,MAAM,WAAW,aAAa;CAK9B,MAAM,sBAAsB,GAAG,sBAAsB;CACrD,MAAM,yBAAyB,QAAQ,WAAW,mBAAmB,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BACA,cACe;CACf,MAAM,WAAW,wBAAwB,OAAO;CAChD,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,SAAS,wBAAwB,SAAS;CAChD,OAAO,4BAA4B,aAAa,YAAY,GAAG,MAAM,CAAC,CAAC;AACzE;;;;;AAMA,SAAgB,gBACd,EAAE,kBACF,cACe;CACf,MAAM,yBAAyB,eAAe,IAAI,YAAY;CAE9D,MAAM,UAAU,wBAAwB,SAAS;CACjD,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,yDAAyD;CAK3E,OAAO,aAAa,SAAS;EAAE,eAFT,4BAA4B,wBAAwB,YAE/B;EAAG,oBAAoB;EAAM;CAAe,CAAC;AAC1F;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
|
package/dist/headless/flags.js
CHANGED
|
@@ -140,7 +140,7 @@ const FLAGS = [
|
|
|
140
140
|
field: "thinkingLevel",
|
|
141
141
|
coerce: validate.enum("--thinking-level", VALID_THINKING_LEVELS),
|
|
142
142
|
placeholder: "<level>",
|
|
143
|
-
help: "Thinking level: off, low, medium, high, xhigh"
|
|
143
|
+
help: "Thinking level: off, low, medium, high, xhigh, max"
|
|
144
144
|
},
|
|
145
145
|
{
|
|
146
146
|
key: "settings",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id)',\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;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IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
|
|
1
|
+
{"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id)',\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;EACT;CACF;;CAEA,YAAY,MAAc;EACxB,QAAQ,QAAwB;GAC9B,MAAM,SAAS,OAAO,GAAG;GACzB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;GAEtD,OAAO;EACT;CACF;;CAEA,OAAO,KAAqB;EAC1B,OAAO;CACT;AACF;AAyBA,MAAa,QAAoB;CAC/B;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ,SAAS,YAAY,WAAW;EACxC,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,MAAM;E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,UAAS;EAAE;EAAM,OAAO,KAAK,IAAI;CAAE,EAAE;CAC5D,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAI,MAAK,EAAE,MAAM,MAAM,CAAC,IAAI;CAE3D,OAAO,KACJ,KAAK,EAAE,MAAM,YAAY;EACxB,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;EAG/D,OAAO,CAAC,GAFS,MAAM,OAAO,KAAK,IAAI,MAAM,MAE9B,GADF,MAAM,MAAM,CAAC,CAAC,CAAC,KAAI,SAAQ,GAAG,IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
|
package/dist/headless/types.d.ts
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
import type { AgentController, AgentControllerEvent, Session } from '@mastra/core/agent-controller';
|
|
9
9
|
import type { GoalManager } from '../goal-manager.js';
|
|
10
10
|
export type RunMode = 'build' | 'plan' | 'fast';
|
|
11
|
-
export type ThinkingLevel = 'off' | 'low' | 'medium' | 'high' | 'xhigh';
|
|
11
|
+
export type ThinkingLevel = 'off' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
12
12
|
export declare const VALID_MODES: readonly ["build", "plan", "fast"];
|
|
13
|
-
export declare const VALID_THINKING_LEVELS: readonly ["off", "low", "medium", "high", "xhigh"];
|
|
13
|
+
export declare const VALID_THINKING_LEVELS: readonly ["off", "low", "medium", "high", "xhigh", "max"];
|
|
14
14
|
/**
|
|
15
15
|
* Named permission modes for non-interactive runs. Maps to a built-in
|
|
16
16
|
* {@link ResolutionPolicy}:
|