mastracode 0.22.3 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/HarnessCompat.d.ts +2 -2
  3. package/dist/HarnessCompat.d.ts.map +1 -1
  4. package/dist/agents/mastracode-gateway.d.ts +58 -0
  5. package/dist/agents/mastracode-gateway.d.ts.map +1 -0
  6. package/dist/agents/model.d.ts +26 -28
  7. package/dist/agents/model.d.ts.map +1 -1
  8. package/dist/agents/{subagents/execute.d.ts → modes/build.d.ts} +3 -3
  9. package/dist/agents/modes/build.d.ts.map +1 -0
  10. package/dist/agents/{subagents → modes}/explore.d.ts +2 -2
  11. package/dist/agents/modes/explore.d.ts.map +1 -0
  12. package/dist/agents/modes/plan.d.ts +6 -0
  13. package/dist/agents/modes/plan.d.ts.map +1 -0
  14. package/dist/{chunk-EATS4KOR.cjs → chunk-3CO7PY6M.cjs} +1094 -239
  15. package/dist/chunk-3CO7PY6M.cjs.map +1 -0
  16. package/dist/{chunk-DJEQBK7L.cjs → chunk-CBPEMMRV.cjs} +1659 -2010
  17. package/dist/chunk-CBPEMMRV.cjs.map +1 -0
  18. package/dist/{chunk-W7Y7QIJA.js → chunk-FXYM4OEI.js} +14 -805
  19. package/dist/chunk-FXYM4OEI.js.map +1 -0
  20. package/dist/{chunk-OXYE6SUY.js → chunk-GKGPZBID.js} +836 -1187
  21. package/dist/chunk-GKGPZBID.js.map +1 -0
  22. package/dist/{chunk-FDDVVRPH.js → chunk-RDIIIT54.js} +1076 -221
  23. package/dist/chunk-RDIIIT54.js.map +1 -0
  24. package/dist/{chunk-NKTZDFIU.cjs → chunk-XPPJHUAD.cjs} +12 -809
  25. package/dist/chunk-XPPJHUAD.cjs.map +1 -0
  26. package/dist/cli.cjs +18 -18
  27. package/dist/cli.js +3 -3
  28. package/dist/index.cjs +3 -3
  29. package/dist/index.d.ts +4 -5
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/mcp/manager.d.ts.map +1 -1
  33. package/dist/onboarding/onboarding-inline.d.ts +2 -2
  34. package/dist/onboarding/onboarding-inline.d.ts.map +1 -1
  35. package/dist/onboarding/settings.d.ts.map +1 -1
  36. package/dist/providers/claude-max.d.ts.map +1 -1
  37. package/dist/tui/chat-boundary-reconciliation.d.ts +18 -1
  38. package/dist/tui/chat-boundary-reconciliation.d.ts.map +1 -1
  39. package/dist/tui/command-dispatch.d.ts.map +1 -1
  40. package/dist/tui/commands/browser.d.ts.map +1 -1
  41. package/dist/tui/commands/goal.d.ts.map +1 -1
  42. package/dist/tui/commands/mode.d.ts.map +1 -1
  43. package/dist/tui/commands/new.d.ts.map +1 -1
  44. package/dist/tui/commands/settings.d.ts.map +1 -1
  45. package/dist/tui/commands/skills.d.ts.map +1 -1
  46. package/dist/tui/components/api-key-dialog.d.ts +2 -2
  47. package/dist/tui/components/api-key-dialog.d.ts.map +1 -1
  48. package/dist/tui/components/ask-question-dialog.d.ts +2 -2
  49. package/dist/tui/components/ask-question-dialog.d.ts.map +1 -1
  50. package/dist/tui/components/ask-question-inline.d.ts +4 -2
  51. package/dist/tui/components/ask-question-inline.d.ts.map +1 -1
  52. package/dist/tui/components/assistant-message.d.ts +2 -2
  53. package/dist/tui/components/assistant-message.d.ts.map +1 -1
  54. package/dist/tui/components/chat-boundary-spacer.d.ts +9 -9
  55. package/dist/tui/components/chat-boundary-spacer.d.ts.map +1 -1
  56. package/dist/tui/components/chat-spacing.d.ts +1 -1
  57. package/dist/tui/components/chat-spacing.d.ts.map +1 -1
  58. package/dist/tui/components/collapsible.d.ts +2 -2
  59. package/dist/tui/components/collapsible.d.ts.map +1 -1
  60. package/dist/tui/components/custom-editor.d.ts +2 -2
  61. package/dist/tui/components/custom-editor.d.ts.map +1 -1
  62. package/dist/tui/components/diff-output.d.ts +3 -1
  63. package/dist/tui/components/diff-output.d.ts.map +1 -1
  64. package/dist/tui/components/error-display.d.ts +4 -2
  65. package/dist/tui/components/error-display.d.ts.map +1 -1
  66. package/dist/tui/components/goal-cycles-dialog.d.ts +2 -2
  67. package/dist/tui/components/goal-cycles-dialog.d.ts.map +1 -1
  68. package/dist/tui/components/idle-counter.d.ts +1 -1
  69. package/dist/tui/components/idle-counter.d.ts.map +1 -1
  70. package/dist/tui/components/judge-display.d.ts +14 -2
  71. package/dist/tui/components/judge-display.d.ts.map +1 -1
  72. package/dist/tui/components/login-dialog.d.ts +2 -2
  73. package/dist/tui/components/login-dialog.d.ts.map +1 -1
  74. package/dist/tui/components/login-mode-selector.d.ts +2 -2
  75. package/dist/tui/components/login-mode-selector.d.ts.map +1 -1
  76. package/dist/tui/components/login-selector.d.ts +1 -1
  77. package/dist/tui/components/login-selector.d.ts.map +1 -1
  78. package/dist/tui/components/masked-input.d.ts +1 -1
  79. package/dist/tui/components/masked-input.d.ts.map +1 -1
  80. package/dist/tui/components/mcp-selector.d.ts +2 -2
  81. package/dist/tui/components/mcp-selector.d.ts.map +1 -1
  82. package/dist/tui/components/model-selector.d.ts +2 -2
  83. package/dist/tui/components/model-selector.d.ts.map +1 -1
  84. package/dist/tui/components/multi-step-progress.d.ts +3 -1
  85. package/dist/tui/components/multi-step-progress.d.ts.map +1 -1
  86. package/dist/tui/components/multiline-input.d.ts +1 -1
  87. package/dist/tui/components/multiline-input.d.ts.map +1 -1
  88. package/dist/tui/components/notification-summary.d.ts +1 -1
  89. package/dist/tui/components/notification-summary.d.ts.map +1 -1
  90. package/dist/tui/components/notification.d.ts +1 -1
  91. package/dist/tui/components/notification.d.ts.map +1 -1
  92. package/dist/tui/components/om-marker.d.ts +3 -1
  93. package/dist/tui/components/om-marker.d.ts.map +1 -1
  94. package/dist/tui/components/om-output.d.ts +3 -1
  95. package/dist/tui/components/om-output.d.ts.map +1 -1
  96. package/dist/tui/components/om-progress.d.ts +1 -1
  97. package/dist/tui/components/om-progress.d.ts.map +1 -1
  98. package/dist/tui/components/om-settings.d.ts +2 -2
  99. package/dist/tui/components/om-settings.d.ts.map +1 -1
  100. package/dist/tui/components/plan-approval-inline.d.ts +2 -2
  101. package/dist/tui/components/plan-approval-inline.d.ts.map +1 -1
  102. package/dist/tui/components/reactive-signal.d.ts +1 -1
  103. package/dist/tui/components/reactive-signal.d.ts.map +1 -1
  104. package/dist/tui/components/settings.d.ts +2 -2
  105. package/dist/tui/components/settings.d.ts.map +1 -1
  106. package/dist/tui/components/shell-output.d.ts +3 -1
  107. package/dist/tui/components/shell-output.d.ts.map +1 -1
  108. package/dist/tui/components/simple-progress.d.ts +1 -1
  109. package/dist/tui/components/simple-progress.d.ts.map +1 -1
  110. package/dist/tui/components/slash-command.d.ts +3 -1
  111. package/dist/tui/components/slash-command.d.ts.map +1 -1
  112. package/dist/tui/components/state-signal.d.ts +1 -1
  113. package/dist/tui/components/state-signal.d.ts.map +1 -1
  114. package/dist/tui/components/subagent-execution.d.ts +2 -2
  115. package/dist/tui/components/subagent-execution.d.ts.map +1 -1
  116. package/dist/tui/components/system-reminder.d.ts +1 -1
  117. package/dist/tui/components/system-reminder.d.ts.map +1 -1
  118. package/dist/tui/components/task-progress.d.ts +1 -1
  119. package/dist/tui/components/task-progress.d.ts.map +1 -1
  120. package/dist/tui/components/temporal-gap.d.ts +3 -1
  121. package/dist/tui/components/temporal-gap.d.ts.map +1 -1
  122. package/dist/tui/components/thinking-settings.d.ts +2 -2
  123. package/dist/tui/components/thinking-settings.d.ts.map +1 -1
  124. package/dist/tui/components/thread-selector.d.ts +2 -2
  125. package/dist/tui/components/thread-selector.d.ts.map +1 -1
  126. package/dist/tui/components/tool-approval-dialog.d.ts +2 -2
  127. package/dist/tui/components/tool-approval-dialog.d.ts.map +1 -1
  128. package/dist/tui/components/tool-execution-enhanced.d.ts +2 -2
  129. package/dist/tui/components/tool-execution-enhanced.d.ts.map +1 -1
  130. package/dist/tui/components/tool-validation-error.d.ts +2 -2
  131. package/dist/tui/components/tool-validation-error.d.ts.map +1 -1
  132. package/dist/tui/components/user-message.d.ts +2 -2
  133. package/dist/tui/components/user-message.d.ts.map +1 -1
  134. package/dist/tui/components/wrapping-autocomplete-list.d.ts +1 -1
  135. package/dist/tui/components/wrapping-autocomplete-list.d.ts.map +1 -1
  136. package/dist/tui/components/wrapping-select-list.d.ts +1 -1
  137. package/dist/tui/components/wrapping-select-list.d.ts.map +1 -1
  138. package/dist/tui/display.d.ts.map +1 -1
  139. package/dist/tui/event-dispatch.d.ts.map +1 -1
  140. package/dist/tui/goal-manager.d.ts +48 -40
  141. package/dist/tui/goal-manager.d.ts.map +1 -1
  142. package/dist/tui/handlers/agent-lifecycle.d.ts +13 -0
  143. package/dist/tui/handlers/agent-lifecycle.d.ts.map +1 -1
  144. package/dist/tui/handlers/index.d.ts +1 -1
  145. package/dist/tui/handlers/index.d.ts.map +1 -1
  146. package/dist/tui/handlers/message.d.ts.map +1 -1
  147. package/dist/tui/handlers/om.d.ts.map +1 -1
  148. package/dist/tui/handlers/tool.d.ts.map +1 -1
  149. package/dist/tui/handlers/types.d.ts +1 -1
  150. package/dist/tui/handlers/types.d.ts.map +1 -1
  151. package/dist/tui/mastra-tui.d.ts.map +1 -1
  152. package/dist/tui/modal-question.d.ts +1 -1
  153. package/dist/tui/modal-question.d.ts.map +1 -1
  154. package/dist/tui/overlay.d.ts +1 -1
  155. package/dist/tui/overlay.d.ts.map +1 -1
  156. package/dist/tui/prompt-api-key.d.ts +1 -1
  157. package/dist/tui/prompt-api-key.d.ts.map +1 -1
  158. package/dist/tui/render-messages.d.ts +1 -1
  159. package/dist/tui/render-messages.d.ts.map +1 -1
  160. package/dist/tui/setup.d.ts.map +1 -1
  161. package/dist/tui/shell.d.ts.map +1 -1
  162. package/dist/tui/state.d.ts +2 -2
  163. package/dist/tui/state.d.ts.map +1 -1
  164. package/dist/tui/status-line.d.ts.map +1 -1
  165. package/dist/tui/theme.d.ts +1 -1
  166. package/dist/tui/theme.d.ts.map +1 -1
  167. package/dist/tui.cjs +19 -19
  168. package/dist/tui.js +2 -2
  169. package/package.json +20 -20
  170. package/dist/agents/coding.d.ts +0 -2
  171. package/dist/agents/coding.d.ts.map +0 -1
  172. package/dist/agents/subagents/execute.d.ts.map +0 -1
  173. package/dist/agents/subagents/explore.d.ts.map +0 -1
  174. package/dist/agents/subagents/plan.d.ts +0 -10
  175. package/dist/agents/subagents/plan.d.ts.map +0 -1
  176. package/dist/chunk-DJEQBK7L.cjs.map +0 -1
  177. package/dist/chunk-EATS4KOR.cjs.map +0 -1
  178. package/dist/chunk-FDDVVRPH.js.map +0 -1
  179. package/dist/chunk-NKTZDFIU.cjs.map +0 -1
  180. package/dist/chunk-OXYE6SUY.js.map +0 -1
  181. package/dist/chunk-W7Y7QIJA.js.map +0 -1
@@ -1,10 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkNKTZDFIU_cjs = require('./chunk-NKTZDFIU.cjs');
3
+ var chunkXPPJHUAD_cjs = require('./chunk-XPPJHUAD.cjs');
4
4
  var chunkJ3ISOP5J_cjs = require('./chunk-J3ISOP5J.cjs');
5
5
  var chunkJHYTJMKT_cjs = require('./chunk-JHYTJMKT.cjs');
6
- var crypto = require('crypto');
7
- var os = require('os');
8
6
  var path = require('path');
9
7
  var agent = require('@mastra/core/agent');
10
8
  var harness = require('@mastra/core/harness');
@@ -13,13 +11,14 @@ var processors = require('@mastra/core/processors');
13
11
  var requestContext = require('@mastra/core/request-context');
14
12
  var signals = require('@mastra/core/signals');
15
13
  var storage = require('@mastra/core/storage');
14
+ var tools = require('@mastra/core/tools');
16
15
  var duckdb = require('@mastra/duckdb');
17
16
  var githubSignals = require('@mastra/github-signals');
18
17
  var observability = require('@mastra/observability');
19
18
  var child_process = require('child_process');
20
- var tools = require('@mastra/core/tools');
21
19
  var tavily = require('@mastra/tavily');
22
20
  var tokenx = require('tokenx');
21
+ var os = require('os');
23
22
  var workspace = require('@mastra/core/workspace');
24
23
  var zod = require('zod');
25
24
  var fs = require('fs');
@@ -28,9 +27,13 @@ var fastembed = require('@mastra/fastembed');
28
27
  var memory = require('@mastra/memory');
29
28
  var anthropic = require('@ai-sdk/anthropic');
30
29
  var openai = require('@ai-sdk/openai');
30
+ var openaiCompatible = require('@ai-sdk/openai-compatible');
31
+ var ai = require('ai');
32
+ var schemaCompat = require('@mastra/schema-compat');
31
33
  var notifications = require('@mastra/core/notifications');
32
34
  var evals = require('@mastra/core/evals');
33
35
  var mcp = require('@mastra/mcp');
36
+ var crypto = require('crypto');
34
37
  var promises = require('fs/promises');
35
38
  var events = require('@mastra/core/events');
36
39
  var libsql = require('@mastra/libsql');
@@ -55,8 +58,8 @@ function _interopNamespace(e) {
55
58
  return Object.freeze(n);
56
59
  }
57
60
 
58
- var os__namespace = /*#__PURE__*/_interopNamespace(os);
59
61
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
62
+ var os__namespace = /*#__PURE__*/_interopNamespace(os);
60
63
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
61
64
 
62
65
  var COMMON_BINARIES = [
@@ -606,8 +609,8 @@ function getDynamicWorkspace({ requestContext, mastra: mastra2 }) {
606
609
  existing.setToolsConfig(workspaceTools);
607
610
  return existing;
608
611
  }
609
- const userLsp = chunkNKTZDFIU_cjs.loadSettings().lsp ?? {};
610
- const mcModulePath = path.join(path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-EATS4KOR.cjs', document.baseURI).href)))), "..");
612
+ const userLsp = chunkXPPJHUAD_cjs.loadSettings().lsp ?? {};
613
+ const mcModulePath = path.join(path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-3CO7PY6M.cjs', document.baseURI).href)))), "..");
611
614
  const lspConfig = {
612
615
  ...userLsp,
613
616
  packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath),
@@ -1049,6 +1052,982 @@ async function getDynamicInstructions({ requestContext }) {
1049
1052
  };
1050
1053
  return buildFullPrompt(promptCtx);
1051
1054
  }
1055
+ var claudeCodeIdentity = "You are Claude Code, Anthropic's official CLI for Claude.";
1056
+ var OAUTH_REQUIRED_BETAS = [
1057
+ "oauth-2025-04-20",
1058
+ "claude-code-20250219",
1059
+ "interleaved-thinking-2025-05-14",
1060
+ "fine-grained-tool-streaming-2025-05-14"
1061
+ ];
1062
+ var authStorageInstance = null;
1063
+ function getAuthStorage() {
1064
+ if (!authStorageInstance) {
1065
+ authStorageInstance = new chunkJ3ISOP5J_cjs.AuthStorage();
1066
+ }
1067
+ return authStorageInstance;
1068
+ }
1069
+ function setAuthStorage(storage) {
1070
+ authStorageInstance = storage ?? null;
1071
+ }
1072
+ var claudeCodeMiddleware = {
1073
+ specificationVersion: "v3",
1074
+ transformParams: async ({ params }) => {
1075
+ const systemMessage = {
1076
+ role: "system",
1077
+ content: claudeCodeIdentity
1078
+ };
1079
+ if (params.temperature) {
1080
+ delete params.topP;
1081
+ }
1082
+ return {
1083
+ ...params,
1084
+ prompt: [systemMessage, ...params.prompt]
1085
+ };
1086
+ }
1087
+ };
1088
+ var promptCacheMiddleware = {
1089
+ specificationVersion: "v3",
1090
+ transformParams: async ({ params }) => {
1091
+ const prompt = [...params.prompt];
1092
+ const cacheControl = { type: "ephemeral", ttl: "5m" };
1093
+ const addCacheToMessage = (msg) => {
1094
+ if (typeof msg.content === "string") {
1095
+ return {
1096
+ ...msg,
1097
+ providerOptions: {
1098
+ ...msg.providerOptions,
1099
+ anthropic: { ...msg.providerOptions?.anthropic, cacheControl }
1100
+ }
1101
+ };
1102
+ }
1103
+ if (Array.isArray(msg.content) && msg.content.length > 0) {
1104
+ const content = [...msg.content];
1105
+ const lastPart = content[content.length - 1];
1106
+ content[content.length - 1] = {
1107
+ ...lastPart,
1108
+ providerOptions: {
1109
+ ...lastPart.providerOptions,
1110
+ anthropic: { ...lastPart.providerOptions?.anthropic, cacheControl }
1111
+ }
1112
+ };
1113
+ return { ...msg, content };
1114
+ }
1115
+ return msg;
1116
+ };
1117
+ let lastSystemIdx = -1;
1118
+ for (let i = prompt.length - 1; i >= 0; i--) {
1119
+ if (prompt[i].role === "system") {
1120
+ lastSystemIdx = i;
1121
+ break;
1122
+ }
1123
+ }
1124
+ if (lastSystemIdx >= 0) {
1125
+ prompt[lastSystemIdx] = addCacheToMessage(prompt[lastSystemIdx]);
1126
+ }
1127
+ const lastIdx = prompt.length - 1;
1128
+ if (lastIdx >= 0 && lastIdx !== lastSystemIdx) {
1129
+ prompt[lastIdx] = addCacheToMessage(prompt[lastIdx]);
1130
+ }
1131
+ return { ...params, prompt };
1132
+ }
1133
+ };
1134
+ function buildAnthropicOAuthFetch(opts = {}) {
1135
+ return (async (url, init) => {
1136
+ const storage = opts.authStorage ?? getAuthStorage();
1137
+ storage.reload();
1138
+ const storedCred = storage.get("anthropic");
1139
+ if (storedCred?.type === "api_key") {
1140
+ throw new Error("Anthropic API key credential is configured, but OAuth is required.");
1141
+ }
1142
+ const accessToken = await storage.getApiKey("anthropic");
1143
+ if (!accessToken) {
1144
+ throw new Error("Not logged in to Anthropic. Run /login first.");
1145
+ }
1146
+ const headers = new Headers();
1147
+ if (init?.headers) {
1148
+ const source = init.headers instanceof Headers ? init.headers : Array.isArray(init.headers) ? new Headers(init.headers) : new Headers(init.headers);
1149
+ source.forEach((value, key) => {
1150
+ const lower = key.toLowerCase();
1151
+ if (lower !== "authorization" && lower !== "x-api-key") {
1152
+ headers.set(key, value);
1153
+ }
1154
+ });
1155
+ }
1156
+ headers.set("Authorization", `Bearer ${accessToken}`);
1157
+ const requestBetas = (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter(Boolean);
1158
+ headers.set("anthropic-beta", Array.from(/* @__PURE__ */ new Set([...OAUTH_REQUIRED_BETAS, ...requestBetas])).join(","));
1159
+ headers.set("anthropic-version", "2023-06-01");
1160
+ try {
1161
+ return await fetch(url, { ...init, headers });
1162
+ } catch (error) {
1163
+ if (error && typeof error === "object") {
1164
+ Object.assign(error, {
1165
+ requestUrl: url instanceof URL ? url.toString() : typeof url === "string" ? url : url.url
1166
+ });
1167
+ }
1168
+ throw error;
1169
+ }
1170
+ });
1171
+ }
1172
+ function opencodeClaudeMaxProvider(modelId = "claude-sonnet-4-20250514", options) {
1173
+ const headers = options?.headers;
1174
+ if (process.env.NODE_ENV === "test" || process.env.VITEST) {
1175
+ const anthropic2 = anthropic.createAnthropic({
1176
+ apiKey: "test-api-key",
1177
+ headers
1178
+ });
1179
+ return ai.wrapLanguageModel({
1180
+ model: anthropic2(modelId),
1181
+ middleware: [claudeCodeMiddleware, promptCacheMiddleware]
1182
+ });
1183
+ }
1184
+ const anthropic$1 = anthropic.createAnthropic({
1185
+ apiKey: "oauth-placeholder",
1186
+ headers,
1187
+ fetch: buildAnthropicOAuthFetch()
1188
+ });
1189
+ return ai.wrapLanguageModel({
1190
+ model: anthropic$1(modelId),
1191
+ middleware: [claudeCodeMiddleware, promptCacheMiddleware]
1192
+ });
1193
+ }
1194
+ var COPILOT_PROVIDER_ID = "github-copilot";
1195
+ var authStorageInstance2 = null;
1196
+ function getAuthStorage2() {
1197
+ if (!authStorageInstance2) {
1198
+ authStorageInstance2 = new chunkJ3ISOP5J_cjs.AuthStorage();
1199
+ }
1200
+ return authStorageInstance2;
1201
+ }
1202
+ function setAuthStorage2(storage) {
1203
+ authStorageInstance2 = storage ?? null;
1204
+ }
1205
+ function detectIsAgent(body) {
1206
+ if (!body || typeof body !== "object") return false;
1207
+ const obj = body;
1208
+ const messages = obj.messages;
1209
+ if (Array.isArray(messages) && messages.length > 0) {
1210
+ const last = messages[messages.length - 1];
1211
+ if (last?.role && last.role !== "user") return true;
1212
+ if (Array.isArray(last?.content)) {
1213
+ const hasToolResult = last.content.some(
1214
+ (part) => part && typeof part === "object" && part.type === "tool_result"
1215
+ );
1216
+ if (hasToolResult) return true;
1217
+ }
1218
+ }
1219
+ const input = obj.input;
1220
+ if (Array.isArray(input) && input.length > 0) {
1221
+ const last = input[input.length - 1];
1222
+ if (last?.role && last.role !== "user") return true;
1223
+ }
1224
+ return false;
1225
+ }
1226
+ function detectIsVision(body) {
1227
+ if (!body || typeof body !== "object") return false;
1228
+ const obj = body;
1229
+ const matchPart = (part) => {
1230
+ if (!part || typeof part !== "object") return false;
1231
+ const t = part.type;
1232
+ return t === "image" || t === "image_url" || t === "input_image";
1233
+ };
1234
+ const messages = obj.messages;
1235
+ if (Array.isArray(messages)) {
1236
+ return messages.some(
1237
+ (msg) => msg && typeof msg === "object" && Array.isArray(msg.content) && msg.content.some(matchPart)
1238
+ );
1239
+ }
1240
+ const input = obj.input;
1241
+ if (Array.isArray(input)) {
1242
+ return input.some(
1243
+ (item) => item && typeof item === "object" && Array.isArray(item.content) && item.content.some(matchPart)
1244
+ );
1245
+ }
1246
+ return false;
1247
+ }
1248
+ function buildGitHubCopilotOAuthFetch(opts = {}) {
1249
+ return (async (url, init) => {
1250
+ const storage = opts.authStorage ?? getAuthStorage2();
1251
+ storage.reload();
1252
+ const cred = storage.get(COPILOT_PROVIDER_ID);
1253
+ if (!cred || cred.type !== "oauth") {
1254
+ throw new Error("Not logged in to GitHub Copilot. Run /login first.");
1255
+ }
1256
+ const accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);
1257
+ if (!accessToken) {
1258
+ throw new Error("Failed to refresh GitHub Copilot token. Please /login again.");
1259
+ }
1260
+ storage.reload();
1261
+ const enterpriseUrl = cred.enterpriseUrl;
1262
+ let parsedBody;
1263
+ if (typeof init?.body === "string") {
1264
+ try {
1265
+ parsedBody = JSON.parse(init.body);
1266
+ } catch {
1267
+ parsedBody = void 0;
1268
+ }
1269
+ }
1270
+ const isAgent = detectIsAgent(parsedBody);
1271
+ const isVision = detectIsVision(parsedBody);
1272
+ const headers = new Headers();
1273
+ if (init?.headers) {
1274
+ const source = init.headers instanceof Headers ? init.headers : Array.isArray(init.headers) ? new Headers(init.headers) : new Headers(init.headers);
1275
+ source.forEach((value, key) => {
1276
+ const lower = key.toLowerCase();
1277
+ if (lower !== "authorization" && lower !== "x-api-key") {
1278
+ headers.set(key, value);
1279
+ }
1280
+ });
1281
+ }
1282
+ headers.set("Authorization", `Bearer ${accessToken}`);
1283
+ headers.set("x-initiator", isAgent ? "agent" : "user");
1284
+ headers.set("Openai-Intent", "conversation-edits");
1285
+ if (isVision) {
1286
+ headers.set("Copilot-Vision-Request", "true");
1287
+ }
1288
+ for (const [key, value] of Object.entries(chunkJ3ISOP5J_cjs.COPILOT_HEADERS)) {
1289
+ if (!headers.has(key)) {
1290
+ headers.set(key, value);
1291
+ }
1292
+ }
1293
+ const finalUrl = opts.rewriteUrl !== false ? rewriteToCopilotBase(url, accessToken, enterpriseUrl) : url instanceof URL ? url : typeof url === "string" ? new URL(url) : new URL(url.url);
1294
+ try {
1295
+ return await fetch(finalUrl, { ...init, headers });
1296
+ } catch (error) {
1297
+ if (error && typeof error === "object") {
1298
+ Object.assign(error, {
1299
+ requestUrl: finalUrl.toString()
1300
+ });
1301
+ }
1302
+ throw error;
1303
+ }
1304
+ });
1305
+ }
1306
+ function rewriteToCopilotBase(url, token, enterpriseDomain) {
1307
+ const original = url instanceof URL ? url : new URL(typeof url === "string" ? url : url.url);
1308
+ const base = new URL(chunkJ3ISOP5J_cjs.getGitHubCopilotBaseUrl(token, enterpriseDomain));
1309
+ const pathname = original.pathname.replace(/^\/v1(\/|$)/, "/");
1310
+ return new URL(`${pathname}${original.search}`, base);
1311
+ }
1312
+ function isGeminiModel(modelId) {
1313
+ return modelId.startsWith("gemini-");
1314
+ }
1315
+ function applyGeminiSchemaCompatToTools(modelId, tools) {
1316
+ if (!Array.isArray(tools)) {
1317
+ return tools;
1318
+ }
1319
+ const compatLayer = new schemaCompat.GoogleSchemaCompatLayer({
1320
+ provider: COPILOT_PROVIDER_ID,
1321
+ modelId,
1322
+ supportsStructuredOutputs: false
1323
+ });
1324
+ return tools.map((tool) => {
1325
+ if (!tool || typeof tool !== "object" || tool.type !== "function") {
1326
+ return tool;
1327
+ }
1328
+ const functionTool = tool;
1329
+ if (!functionTool.inputSchema) {
1330
+ return tool;
1331
+ }
1332
+ return {
1333
+ ...functionTool,
1334
+ inputSchema: schemaCompat.applyCompatLayer({
1335
+ schema: functionTool.inputSchema,
1336
+ compatLayers: [compatLayer],
1337
+ mode: "aiSdkSchema"
1338
+ }).jsonSchema
1339
+ };
1340
+ });
1341
+ }
1342
+ function createCopilotMiddleware(modelId) {
1343
+ return {
1344
+ specificationVersion: "v3",
1345
+ transformParams: async ({ params }) => {
1346
+ if (params.temperature !== void 0 && params.temperature !== null) {
1347
+ delete params.topP;
1348
+ }
1349
+ if (isGeminiModel(modelId)) {
1350
+ params.tools = applyGeminiSchemaCompatToTools(
1351
+ modelId,
1352
+ params.tools
1353
+ );
1354
+ }
1355
+ return params;
1356
+ }
1357
+ };
1358
+ }
1359
+ function githubCopilotProvider(modelId = "gpt-4.1", options) {
1360
+ const headers = options?.headers;
1361
+ const copilot = openaiCompatible.createOpenAICompatible({
1362
+ name: COPILOT_PROVIDER_ID,
1363
+ baseURL: "https://api.githubcopilot.com",
1364
+ apiKey: process.env.NODE_ENV === "test" || process.env.VITEST ? "test-api-key" : "oauth-placeholder",
1365
+ headers,
1366
+ fetch: process.env.NODE_ENV === "test" || process.env.VITEST ? void 0 : buildGitHubCopilotOAuthFetch({ rewriteUrl: false })
1367
+ });
1368
+ return ai.wrapLanguageModel({
1369
+ model: copilot.chatModel(modelId),
1370
+ middleware: [createCopilotMiddleware(modelId)]
1371
+ });
1372
+ }
1373
+ var COPILOT_FALLBACK_MODELS = [
1374
+ {
1375
+ id: "gpt-4.1",
1376
+ name: "GPT-4.1",
1377
+ vendor: "OpenAI",
1378
+ supportedEndpoints: ["/chat/completions"],
1379
+ isAnthropicShaped: false,
1380
+ supportsVision: true,
1381
+ supportsToolCalls: true
1382
+ }
1383
+ ];
1384
+ var CATALOG_TTL_MS = 10 * 60 * 1e3;
1385
+ var CATALOG_FAILURE_TTL_MS = 60 * 1e3;
1386
+ var CATALOG_FETCH_TIMEOUT_MS = 5e3;
1387
+ var catalogCache = null;
1388
+ var inflightFetch = null;
1389
+ async function getCopilotModelCatalog(opts = {}) {
1390
+ const storage = opts.authStorage ?? getAuthStorage2();
1391
+ storage.reload();
1392
+ const cred = storage.get(COPILOT_PROVIDER_ID);
1393
+ if (!cred || cred.type !== "oauth") {
1394
+ return [];
1395
+ }
1396
+ const now = Date.now();
1397
+ if (catalogCache && now - catalogCache.fetchedAt < catalogCache.ttl) {
1398
+ return catalogCache.models;
1399
+ }
1400
+ if (inflightFetch) return inflightFetch;
1401
+ inflightFetch = (async () => {
1402
+ try {
1403
+ const accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);
1404
+ if (!accessToken) throw new Error("No Copilot bearer token");
1405
+ storage.reload();
1406
+ const refreshed = storage.get(COPILOT_PROVIDER_ID);
1407
+ const enterpriseUrl = refreshed?.enterpriseUrl;
1408
+ const baseUrl = chunkJ3ISOP5J_cjs.getGitHubCopilotBaseUrl(accessToken, enterpriseUrl);
1409
+ const controller = new AbortController();
1410
+ const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);
1411
+ try {
1412
+ const models = await chunkJ3ISOP5J_cjs.fetchCopilotModels({
1413
+ baseUrl,
1414
+ bearerToken: accessToken,
1415
+ signal: controller.signal
1416
+ });
1417
+ catalogCache = { fetchedAt: Date.now(), ttl: CATALOG_TTL_MS, models };
1418
+ return models;
1419
+ } finally {
1420
+ clearTimeout(timer);
1421
+ }
1422
+ } catch (error) {
1423
+ catalogCache = {
1424
+ fetchedAt: Date.now(),
1425
+ ttl: CATALOG_FAILURE_TTL_MS,
1426
+ models: COPILOT_FALLBACK_MODELS
1427
+ };
1428
+ console.warn(
1429
+ "Failed to fetch live GitHub Copilot models, using fallback list:",
1430
+ error instanceof Error ? error.message : error
1431
+ );
1432
+ return COPILOT_FALLBACK_MODELS;
1433
+ } finally {
1434
+ inflightFetch = null;
1435
+ }
1436
+ })();
1437
+ return inflightFetch;
1438
+ }
1439
+ var CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";
1440
+ var CODEX_ORIGINATOR = "mastracode";
1441
+ var CODEX_USER_AGENT = "mastracode";
1442
+ var authStorageInstance3 = null;
1443
+ function getAuthStorage3() {
1444
+ if (!authStorageInstance3) {
1445
+ authStorageInstance3 = new chunkJ3ISOP5J_cjs.AuthStorage();
1446
+ }
1447
+ return authStorageInstance3;
1448
+ }
1449
+ function setAuthStorage3(storage) {
1450
+ authStorageInstance3 = storage ?? null;
1451
+ }
1452
+ var CODEX_INSTRUCTIONS = `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
1453
+
1454
+ IMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;
1455
+ var GPT5_MODEL_RE = /^gpt-5(?:\.|-|$)/;
1456
+ function getEffectiveThinkingLevel(modelId, level) {
1457
+ if (GPT5_MODEL_RE.test(modelId) && level === "off") {
1458
+ return "low";
1459
+ }
1460
+ return level;
1461
+ }
1462
+ var THINKING_LEVEL_TO_REASONING_EFFORT = {
1463
+ off: void 0,
1464
+ low: "low",
1465
+ medium: "medium",
1466
+ high: "high",
1467
+ xhigh: "xhigh"
1468
+ };
1469
+ function createCodexMiddleware(reasoningEffort) {
1470
+ return {
1471
+ specificationVersion: "v3",
1472
+ transformParams: async ({ params }) => {
1473
+ if (params.temperature !== void 0 && params.temperature !== null) {
1474
+ delete params.topP;
1475
+ }
1476
+ params.providerOptions = {
1477
+ ...params.providerOptions,
1478
+ openai: {
1479
+ ...params.providerOptions?.openai ?? {},
1480
+ instructions: CODEX_INSTRUCTIONS,
1481
+ // Codex API requires store to be false
1482
+ store: false,
1483
+ // Enable reasoning for Codex models — without this, the model
1484
+ // skips the reasoning/action phase and goes straight to final_answer,
1485
+ // resulting in narration instead of tool calls.
1486
+ ...reasoningEffort ? { reasoningEffort } : {}
1487
+ }
1488
+ };
1489
+ return params;
1490
+ }
1491
+ };
1492
+ }
1493
+ function buildOpenAICodexOAuthFetch(opts = {}) {
1494
+ return (async (url, init) => {
1495
+ const storage = opts.authStorage ?? getAuthStorage3();
1496
+ storage.reload();
1497
+ const cred = storage.get("openai-codex");
1498
+ if (!cred || cred.type !== "oauth") {
1499
+ throw new Error("Not logged in to OpenAI Codex. Run /login first.");
1500
+ }
1501
+ let accessToken = cred.access;
1502
+ if (Date.now() >= cred.expires) {
1503
+ const refreshedToken = await storage.getApiKey("openai-codex");
1504
+ if (!refreshedToken) {
1505
+ throw new Error("Failed to refresh OpenAI Codex token. Please /login again.");
1506
+ }
1507
+ accessToken = refreshedToken;
1508
+ storage.reload();
1509
+ }
1510
+ const accountId = cred.accountId;
1511
+ const headers = new Headers();
1512
+ if (init?.headers) {
1513
+ if (init.headers instanceof Headers) {
1514
+ init.headers.forEach((value, key) => {
1515
+ if (key.toLowerCase() !== "authorization") {
1516
+ headers.set(key, value);
1517
+ }
1518
+ });
1519
+ } else if (Array.isArray(init.headers)) {
1520
+ for (const [key, value] of init.headers) {
1521
+ if (key.toLowerCase() !== "authorization" && value !== void 0) {
1522
+ headers.set(key, String(value));
1523
+ }
1524
+ }
1525
+ } else {
1526
+ for (const [key, value] of Object.entries(init.headers)) {
1527
+ if (key.toLowerCase() !== "authorization" && value !== void 0) {
1528
+ headers.set(key, String(value));
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+ headers.set("Authorization", `Bearer ${accessToken}`);
1534
+ if (!headers.has("originator")) {
1535
+ headers.set("originator", CODEX_ORIGINATOR);
1536
+ }
1537
+ if (!headers.has("User-Agent")) {
1538
+ headers.set("User-Agent", CODEX_USER_AGENT);
1539
+ }
1540
+ if (accountId) {
1541
+ headers.set("ChatGPT-Account-ID", accountId);
1542
+ }
1543
+ const parsed = url instanceof URL ? url : new URL(typeof url === "string" ? url : url.url);
1544
+ const shouldRewrite = opts.rewriteUrl !== false && (parsed.pathname.includes("/v1/responses") || parsed.pathname.includes("/chat/completions"));
1545
+ const finalUrl = shouldRewrite ? new URL(CODEX_API_ENDPOINT) : parsed;
1546
+ try {
1547
+ return await fetch(finalUrl, { ...init, headers });
1548
+ } catch (error) {
1549
+ if (error && typeof error === "object") {
1550
+ Object.assign(error, {
1551
+ requestUrl: finalUrl.toString()
1552
+ });
1553
+ }
1554
+ throw error;
1555
+ }
1556
+ });
1557
+ }
1558
+ function openaiCodexProvider(modelId = "codex-mini-latest", options) {
1559
+ const requestedLevel = options?.thinkingLevel ?? "medium";
1560
+ const effectiveLevel = getEffectiveThinkingLevel(modelId, requestedLevel);
1561
+ const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
1562
+ const middleware = createCodexMiddleware(reasoningEffort);
1563
+ const headers = options?.headers;
1564
+ const baseURL = process.env.OPENAI_BASE_URL;
1565
+ if (process.env.NODE_ENV === "test" || process.env.VITEST) {
1566
+ const openai2 = openai.createOpenAI({
1567
+ apiKey: "test-api-key",
1568
+ baseURL,
1569
+ headers
1570
+ });
1571
+ return ai.wrapLanguageModel({
1572
+ model: openai2.responses(modelId),
1573
+ middleware: [middleware]
1574
+ });
1575
+ }
1576
+ const openai$1 = openai.createOpenAI({
1577
+ apiKey: "oauth-dummy-key",
1578
+ baseURL,
1579
+ headers,
1580
+ fetch: buildOpenAICodexOAuthFetch()
1581
+ });
1582
+ return ai.wrapLanguageModel({
1583
+ model: openai$1.responses(modelId),
1584
+ middleware: [middleware]
1585
+ });
1586
+ }
1587
+
1588
+ // src/agents/mastracode-gateway.ts
1589
+ var OPENAI_PREFIX = "openai/";
1590
+ var MASTRA_GATEWAY_PREFIX = "mastra/";
1591
+ var MASTRACODE_GATEWAY_ID = "mastracode";
1592
+ var CODEX_OPENAI_MODEL_REMAPS = {
1593
+ "gpt-5.3": "gpt-5.3-codex",
1594
+ "gpt-5.2": "gpt-5.2-codex",
1595
+ "gpt-5.1": "gpt-5.1-codex",
1596
+ "gpt-5.1-mini": "gpt-5.1-codex-mini",
1597
+ "gpt-5": "gpt-5-codex"
1598
+ };
1599
+ var authStorage = new chunkJ3ISOP5J_cjs.AuthStorage();
1600
+ function reloadAuthStorage() {
1601
+ authStorage.reload();
1602
+ }
1603
+ function stripMastraGatewayPrefix(modelId) {
1604
+ return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? modelId.substring(MASTRA_GATEWAY_PREFIX.length) : modelId;
1605
+ }
1606
+ function normalizeAnthropicModelId(modelId) {
1607
+ return modelId.replace(/\.(?=\d)/g, "-");
1608
+ }
1609
+ function remapOpenAIModelForCodexOAuth(modelId) {
1610
+ const normalizedModelId = stripMastraGatewayPrefix(modelId);
1611
+ if (!normalizedModelId.startsWith(OPENAI_PREFIX)) {
1612
+ return modelId;
1613
+ }
1614
+ const openaiModelId = normalizedModelId.substring(OPENAI_PREFIX.length);
1615
+ if (openaiModelId.includes("-codex")) {
1616
+ return modelId;
1617
+ }
1618
+ const codexModelId = CODEX_OPENAI_MODEL_REMAPS[openaiModelId];
1619
+ if (!codexModelId) {
1620
+ return modelId;
1621
+ }
1622
+ const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;
1623
+ return modelId.startsWith(MASTRA_GATEWAY_PREFIX) ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;
1624
+ }
1625
+ function getAnthropicApiKey() {
1626
+ const storedCred = authStorage.get("anthropic");
1627
+ if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) {
1628
+ return storedCred.key.trim();
1629
+ }
1630
+ const dedicatedKey = authStorage.getStoredApiKey("anthropic")?.trim();
1631
+ if (dedicatedKey) return dedicatedKey;
1632
+ return process.env.ANTHROPIC_API_KEY?.trim() || void 0;
1633
+ }
1634
+ function getOpenAIApiKey() {
1635
+ const storedCred = authStorage.get("openai-codex");
1636
+ if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) {
1637
+ return storedCred.key.trim();
1638
+ }
1639
+ const dedicatedKey = authStorage.getStoredApiKey("openai-codex")?.trim();
1640
+ if (dedicatedKey) return dedicatedKey;
1641
+ return process.env.OPENAI_API_KEY?.trim() || void 0;
1642
+ }
1643
+ function anthropicApiKeyProvider(modelId, apiKey, headers) {
1644
+ const anthropic$1 = anthropic.createAnthropic({ apiKey, headers });
1645
+ return ai.wrapLanguageModel({
1646
+ model: anthropic$1(modelId),
1647
+ middleware: [promptCacheMiddleware]
1648
+ });
1649
+ }
1650
+ function openaiApiKeyProvider(modelId, apiKey, headers) {
1651
+ const openai$1 = openai.createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });
1652
+ return ai.wrapLanguageModel({
1653
+ model: openai$1.responses(modelId),
1654
+ middleware: []
1655
+ });
1656
+ }
1657
+ function getAuthProviderId(providerId) {
1658
+ return providerId === "openai" ? "openai-codex" : providerId;
1659
+ }
1660
+ function getProviderAuthKey(providerId) {
1661
+ const authProviderId = getAuthProviderId(providerId);
1662
+ const storedCred = authStorage.get(authProviderId);
1663
+ if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) {
1664
+ return storedCred.key.trim();
1665
+ }
1666
+ return authStorage.getStoredApiKey(authProviderId)?.trim() || void 0;
1667
+ }
1668
+ function getGatewayProviderKey(gatewayId, providerId) {
1669
+ if (gatewayId === "models.dev") return providerId;
1670
+ return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;
1671
+ }
1672
+ function parseGatewayRouterId(routerId, gateway) {
1673
+ const [firstPart = "", secondPart = "", ...restParts] = routerId.split("/");
1674
+ const gatewayId = gateway.id;
1675
+ if (firstPart === gatewayId && secondPart) {
1676
+ return {
1677
+ gatewayId,
1678
+ providerId: secondPart,
1679
+ modelId: restParts.join("/")
1680
+ };
1681
+ }
1682
+ return {
1683
+ gatewayId,
1684
+ providerId: firstPart,
1685
+ modelId: [secondPart, ...restParts].filter(Boolean).join("/")
1686
+ };
1687
+ }
1688
+ function hasResolvedAuth(auth) {
1689
+ if (!auth) return false;
1690
+ if (auth.apiKey || auth.bearerToken) return true;
1691
+ return auth.headers ? Object.keys(auth.headers).length > 0 : false;
1692
+ }
1693
+ async function resolveGatewayProviderAuth(gateway, routerId) {
1694
+ if (!gateway.resolveAuth) return void 0;
1695
+ const parsed = parseGatewayRouterId(routerId, gateway);
1696
+ try {
1697
+ const result = await gateway.resolveAuth({
1698
+ gatewayId: parsed.gatewayId,
1699
+ providerId: parsed.providerId,
1700
+ modelId: parsed.modelId,
1701
+ routerId
1702
+ });
1703
+ return hasResolvedAuth(result) ? result : void 0;
1704
+ } catch {
1705
+ return void 0;
1706
+ }
1707
+ }
1708
+ async function getMastraCodeProviderConfigs(gateway) {
1709
+ const providers = { ...llm.PROVIDER_REGISTRY };
1710
+ try {
1711
+ const gatewayProviders = await gateway.fetchProviders();
1712
+ for (const [providerId, config] of Object.entries(gatewayProviders)) {
1713
+ providers[getGatewayProviderKey(gateway.id, providerId)] = {
1714
+ ...config,
1715
+ gateway: gateway.id
1716
+ };
1717
+ }
1718
+ } catch (error) {
1719
+ console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);
1720
+ }
1721
+ return providers;
1722
+ }
1723
+ function getApiKeyEnvVar(providerConfig) {
1724
+ const envVars = providerConfig?.apiKeyEnvVar;
1725
+ return Array.isArray(envVars) ? envVars[0] : envVars;
1726
+ }
1727
+ var MastraCodeGateway = class _MastraCodeGateway extends llm.MastraModelGateway {
1728
+ id = MASTRACODE_GATEWAY_ID;
1729
+ name = "MastraCode Gateway";
1730
+ #mastraGateway;
1731
+ #mastraGatewayBaseUrl;
1732
+ #mastraGatewayApiKey;
1733
+ #routeThroughMastraGateway;
1734
+ #thinkingLevel;
1735
+ #customProviders;
1736
+ #settingsPath;
1737
+ constructor({
1738
+ mastraGatewayBaseUrl,
1739
+ mastraGatewayApiKey,
1740
+ routeThroughMastraGateway,
1741
+ thinkingLevel,
1742
+ customProviders,
1743
+ settingsPath
1744
+ }) {
1745
+ super();
1746
+ this.#mastraGateway = new llm.MastraGateway({ baseUrl: mastraGatewayBaseUrl });
1747
+ this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;
1748
+ this.#mastraGatewayApiKey = mastraGatewayApiKey;
1749
+ this.#routeThroughMastraGateway = routeThroughMastraGateway;
1750
+ this.#thinkingLevel = thinkingLevel;
1751
+ this.#customProviders = customProviders;
1752
+ this.#settingsPath = settingsPath;
1753
+ }
1754
+ static getMemoryGatewayApiKey() {
1755
+ return authStorage.getStoredApiKey(chunkXPPJHUAD_cjs.MEMORY_GATEWAY_PROVIDER) ?? process.env["MASTRA_GATEWAY_API_KEY"];
1756
+ }
1757
+ static resolveProviderAuth(request, memoryGatewayApiKey) {
1758
+ if (request.gatewayId === "mastra" && memoryGatewayApiKey) {
1759
+ return { apiKey: memoryGatewayApiKey, source: "gateway" };
1760
+ }
1761
+ const storedCred = authStorage.get(getAuthProviderId(request.providerId));
1762
+ if (storedCred?.type === "oauth") {
1763
+ return { bearerToken: "oauth", source: "gateway" };
1764
+ }
1765
+ const apiKey = getProviderAuthKey(request.providerId);
1766
+ return apiKey ? { apiKey, source: "gateway" } : void 0;
1767
+ }
1768
+ static createModelCatalogProvider(gateway) {
1769
+ return async () => {
1770
+ const registry = await getMastraCodeProviderConfigs(gateway);
1771
+ const models = [];
1772
+ for (const [provider, providerConfig] of Object.entries(registry)) {
1773
+ const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);
1774
+ const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;
1775
+ const modelNames = providerConfig.models;
1776
+ if (!Array.isArray(modelNames)) continue;
1777
+ const gatewayAuth = modelNames[0] ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`) : void 0;
1778
+ for (const modelName of modelNames) {
1779
+ const id = `${provider}/${modelName}`;
1780
+ models.push({
1781
+ id,
1782
+ provider,
1783
+ modelName,
1784
+ hasApiKey: hasEnvKey || Boolean(gatewayAuth),
1785
+ apiKeyEnvVar: apiKeyEnvVar || void 0
1786
+ });
1787
+ }
1788
+ }
1789
+ return models;
1790
+ };
1791
+ }
1792
+ createModelCatalogProvider() {
1793
+ return _MastraCodeGateway.createModelCatalogProvider(this);
1794
+ }
1795
+ #getCustomProviders() {
1796
+ return this.#customProviders ?? chunkXPPJHUAD_cjs.loadSettings(this.#settingsPath).customProviders;
1797
+ }
1798
+ async fetchProviders() {
1799
+ const providers = {};
1800
+ for (const provider of this.#getCustomProviders()) {
1801
+ const models = provider.models ?? [];
1802
+ if (!models.length) continue;
1803
+ providers[chunkXPPJHUAD_cjs.getCustomProviderId(provider.name)] = {
1804
+ name: provider.name,
1805
+ url: provider.url,
1806
+ apiKeyEnvVar: "",
1807
+ apiKeyHeader: "Authorization",
1808
+ gateway: this.id,
1809
+ models
1810
+ };
1811
+ }
1812
+ try {
1813
+ const copilotModels = await getCopilotModelCatalog({ authStorage });
1814
+ providers["github-copilot"] = {
1815
+ name: "GitHub Copilot",
1816
+ apiKeyEnvVar: "",
1817
+ apiKeyHeader: "Authorization",
1818
+ gateway: this.id,
1819
+ models: copilotModels.map((model) => model.id)
1820
+ };
1821
+ } catch (error) {
1822
+ console.warn("Failed to load GitHub Copilot model catalog:", error);
1823
+ }
1824
+ return providers;
1825
+ }
1826
+ buildUrl(modelId) {
1827
+ return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;
1828
+ }
1829
+ async getApiKey(modelId) {
1830
+ const providerId = stripMastraGatewayPrefix(modelId).split("/", 1)[0];
1831
+ if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? "";
1832
+ return providerId ? getProviderAuthKey(providerId) ?? "" : "";
1833
+ }
1834
+ resolveAuth(request) {
1835
+ if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {
1836
+ return { apiKey: this.#mastraGatewayApiKey, source: "gateway" };
1837
+ }
1838
+ const customProvider = this.#getCustomProviders().find(
1839
+ (provider) => request.providerId === chunkXPPJHUAD_cjs.getCustomProviderId(provider.name)
1840
+ );
1841
+ if (customProvider?.apiKey) {
1842
+ return { apiKey: customProvider.apiKey, source: "gateway" };
1843
+ }
1844
+ return _MastraCodeGateway.resolveProviderAuth(request);
1845
+ }
1846
+ resolveLanguageModel(args) {
1847
+ const customProvider = this.#getCustomProviders().find(
1848
+ (provider) => args.providerId === chunkXPPJHUAD_cjs.getCustomProviderId(provider.name)
1849
+ );
1850
+ if (customProvider) {
1851
+ const provider = openaiCompatible.createOpenAICompatible({
1852
+ name: args.providerId,
1853
+ baseURL: customProvider.url,
1854
+ apiKey: args.apiKey,
1855
+ headers: args.headers
1856
+ });
1857
+ return provider.chatModel(args.modelId);
1858
+ }
1859
+ if (args.providerId === "github-copilot") {
1860
+ return githubCopilotProvider(args.modelId, { headers: args.headers });
1861
+ }
1862
+ if (args.providerId === "moonshotai") {
1863
+ if (!process.env.MOONSHOT_AI_API_KEY) {
1864
+ throw new Error(`Need MOONSHOT_AI_API_KEY`);
1865
+ }
1866
+ return anthropic.createAnthropic({
1867
+ apiKey: process.env.MOONSHOT_AI_API_KEY,
1868
+ baseURL: "https://api.moonshot.ai/anthropic/v1",
1869
+ name: "moonshotai.anthropicv1",
1870
+ headers: args.headers
1871
+ })(args.modelId);
1872
+ }
1873
+ if (args.providerId === "anthropic") {
1874
+ return this.#resolveAnthropicModel(args);
1875
+ }
1876
+ if (args.providerId === "openai") {
1877
+ const openaiModel = this.#resolveOpenAIModel(args);
1878
+ if (openaiModel) return openaiModel;
1879
+ }
1880
+ if (this.#routeThroughMastraGateway) {
1881
+ return this.#mastraGateway.resolveLanguageModel(args);
1882
+ }
1883
+ return new llm.ModelRouterLanguageModel({
1884
+ id: `${args.providerId}/${args.modelId}`,
1885
+ headers: args.headers
1886
+ });
1887
+ }
1888
+ #resolveAnthropicModel(args) {
1889
+ const bareModelId = normalizeAnthropicModelId(args.modelId);
1890
+ const storedCred = authStorage.get("anthropic");
1891
+ if (this.#routeThroughMastraGateway) {
1892
+ if (storedCred?.type === "oauth") {
1893
+ const anthropic$1 = anthropic.createAnthropic({
1894
+ apiKey: "oauth-gateway-placeholder",
1895
+ baseURL: `${this.#mastraGatewayBaseUrl}/v1`,
1896
+ headers: {
1897
+ [llm.GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,
1898
+ ...args.headers
1899
+ },
1900
+ fetch: buildAnthropicOAuthFetch({ authStorage })
1901
+ });
1902
+ return ai.wrapLanguageModel({
1903
+ model: anthropic$1(bareModelId),
1904
+ middleware: [claudeCodeMiddleware, promptCacheMiddleware]
1905
+ });
1906
+ }
1907
+ return this.#mastraGateway.resolveLanguageModel({ ...args, modelId: bareModelId });
1908
+ }
1909
+ if (storedCred?.type === "oauth") {
1910
+ return opencodeClaudeMaxProvider(bareModelId, { headers: args.headers });
1911
+ }
1912
+ if (storedCred?.type === "api_key" && storedCred.key.trim().length > 0) {
1913
+ return anthropicApiKeyProvider(
1914
+ bareModelId,
1915
+ storedCred.key.trim(),
1916
+ args.headers
1917
+ );
1918
+ }
1919
+ const apiKey = getAnthropicApiKey();
1920
+ if (apiKey) {
1921
+ return anthropicApiKeyProvider(bareModelId, apiKey, args.headers);
1922
+ }
1923
+ return opencodeClaudeMaxProvider(bareModelId, { headers: args.headers });
1924
+ }
1925
+ #resolveOpenAIModel(args) {
1926
+ const storedCred = authStorage.get("openai-codex");
1927
+ if (this.#routeThroughMastraGateway) {
1928
+ if (storedCred?.type === "oauth") {
1929
+ const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);
1930
+ const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);
1931
+ const requestedLevel = this.#thinkingLevel ?? "medium";
1932
+ const effectiveLevel = getEffectiveThinkingLevel(resolvedBareModelId, requestedLevel);
1933
+ const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
1934
+ const middleware = createCodexMiddleware(reasoningEffort);
1935
+ const openai$1 = openai.createOpenAI({
1936
+ apiKey: "oauth-gateway-placeholder",
1937
+ baseURL: `${this.#mastraGatewayBaseUrl}/v1`,
1938
+ headers: {
1939
+ [llm.GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,
1940
+ ...args.headers
1941
+ },
1942
+ fetch: buildOpenAICodexOAuthFetch({ authStorage, rewriteUrl: false })
1943
+ });
1944
+ return ai.wrapLanguageModel({
1945
+ model: openai$1.responses(resolvedBareModelId),
1946
+ middleware: [middleware]
1947
+ });
1948
+ }
1949
+ return this.#mastraGateway.resolveLanguageModel(args);
1950
+ }
1951
+ if (storedCred?.type === "oauth") {
1952
+ const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);
1953
+ return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {
1954
+ thinkingLevel: this.#thinkingLevel,
1955
+ headers: args.headers
1956
+ });
1957
+ }
1958
+ const apiKey = getOpenAIApiKey();
1959
+ if (apiKey) {
1960
+ return openaiApiKeyProvider(args.modelId, apiKey, args.headers);
1961
+ }
1962
+ return void 0;
1963
+ }
1964
+ };
1965
+
1966
+ // src/agents/model.ts
1967
+ function getHarnessHeaders(requestContext) {
1968
+ const harnessContext = requestContext?.get("harness");
1969
+ const headers = {
1970
+ ...harnessContext?.threadId ? { "x-thread-id": harnessContext.threadId } : {},
1971
+ ...harnessContext?.resourceId ? { "x-resource-id": harnessContext.resourceId } : {}
1972
+ };
1973
+ return Object.keys(headers).length > 0 ? headers : void 0;
1974
+ }
1975
+ function createMastraCodeGateway(options) {
1976
+ return new MastraCodeGateway(options);
1977
+ }
1978
+ function createMastraCodeModelCatalogProvider(gateway) {
1979
+ return gateway instanceof MastraCodeGateway ? gateway.createModelCatalogProvider() : MastraCodeGateway.createModelCatalogProvider(gateway);
1980
+ }
1981
+ function resolveModel(modelId, options) {
1982
+ reloadAuthStorage();
1983
+ const headers = getHarnessHeaders(options?.requestContext);
1984
+ const settings = chunkXPPJHUAD_cjs.loadSettings();
1985
+ const isMastraGatewayModel = modelId.startsWith(MASTRA_GATEWAY_PREFIX);
1986
+ const normalizedModelId = stripMastraGatewayPrefix(modelId);
1987
+ const [providerId, ...modelParts] = normalizedModelId.split("/");
1988
+ const bareModelId = modelParts.join("/");
1989
+ if (!providerId || !bareModelId) {
1990
+ throw new Error(`Invalid model id: ${modelId}`);
1991
+ }
1992
+ const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;
1993
+ const mgApiKey = MastraCodeGateway.getMemoryGatewayApiKey();
1994
+ const rawGatewayBase = settings.memoryGateway?.baseUrl ?? process.env["MASTRA_GATEWAY_URL"] ?? "https://gateway-api.mastra.ai";
1995
+ const gateway = createMastraCodeGateway({
1996
+ mastraGatewayBaseUrl: rawGatewayBase.replace(/\/+$/, "").replace(/\/v1$/, ""),
1997
+ mastraGatewayApiKey: mgApiKey,
1998
+ routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),
1999
+ thinkingLevel: options?.thinkingLevel,
2000
+ customProviders: settings.customProviders
2001
+ });
2002
+ const auth = gateway.resolveAuth({
2003
+ gatewayId: MASTRACODE_GATEWAY_ID,
2004
+ providerId,
2005
+ modelId: bareModelId,
2006
+ routerId
2007
+ });
2008
+ return gateway.resolveLanguageModel({
2009
+ providerId,
2010
+ modelId: bareModelId,
2011
+ apiKey: auth?.apiKey ?? mgApiKey ?? "",
2012
+ headers
2013
+ });
2014
+ }
2015
+ function getDynamicModel({ requestContext }) {
2016
+ const harnessContext = requestContext.get("harness");
2017
+ const modelId = harnessContext?.state?.currentModelId;
2018
+ if (!modelId) {
2019
+ throw new Error("No model selected. Use /models to select a model first.");
2020
+ }
2021
+ const thinkingLevel = harnessContext?.state?.thinkingLevel;
2022
+ return resolveModel(modelId, { thinkingLevel, requestContext });
2023
+ }
2024
+ function getGoalJudgeModel({ requestContext }, settingsPath) {
2025
+ const judgeModelId = chunkXPPJHUAD_cjs.loadSettings(settingsPath).models.goalJudgeModel;
2026
+ if (!judgeModelId) return void 0;
2027
+ return resolveModel(judgeModelId, { requestContext });
2028
+ }
2029
+
2030
+ // src/agents/memory.ts
1052
2031
  var cachedMemory = null;
1053
2032
  var cachedMemoryKey = null;
1054
2033
  function getHarnessState(requestContext) {
@@ -1056,15 +2035,13 @@ function getHarnessState(requestContext) {
1056
2035
  }
1057
2036
  function getObserverModel({ requestContext }) {
1058
2037
  const state = getHarnessState(requestContext);
1059
- return chunkNKTZDFIU_cjs.resolveModel(state?.observerModelId ?? chunkJ3ISOP5J_cjs.DEFAULT_OM_MODEL_ID, {
1060
- remapForCodexOAuth: true,
2038
+ return resolveModel(state?.observerModelId ?? chunkJ3ISOP5J_cjs.DEFAULT_OM_MODEL_ID, {
1061
2039
  requestContext
1062
2040
  });
1063
2041
  }
1064
2042
  function getReflectorModel({ requestContext }) {
1065
2043
  const state = getHarnessState(requestContext);
1066
- return chunkNKTZDFIU_cjs.resolveModel(state?.reflectorModelId ?? chunkJ3ISOP5J_cjs.DEFAULT_OM_MODEL_ID, {
1067
- remapForCodexOAuth: true,
2044
+ return resolveModel(state?.reflectorModelId ?? chunkJ3ISOP5J_cjs.DEFAULT_OM_MODEL_ID, {
1068
2045
  requestContext
1069
2046
  });
1070
2047
  }
@@ -1147,10 +2124,10 @@ ${CAVEMAN_OM_INSTRUCTION}` : DYNAMIC_AGENTS_MD_INSTRUCTION;
1147
2124
  };
1148
2125
  }
1149
2126
 
1150
- // src/agents/subagents/execute.ts
1151
- var executeSubagent = {
1152
- id: "execute",
1153
- name: "Execute",
2127
+ // src/agents/modes/build.ts
2128
+ var buildMode = {
2129
+ id: "build",
2130
+ name: "Build",
1154
2131
  description: "Task execution with write capabilities. Use for 'implement feature X', 'fix bug Y', 'refactor module Z'.",
1155
2132
  instructions: `You are a focused execution agent. Your job is to complete a specific, well-defined task by making the necessary changes to the codebase.
1156
2133
 
@@ -1183,14 +2160,19 @@ End with a structured summary:
1183
2160
  . **Completed**: What you implemented (1-2 sentences)
1184
2161
  . **Changes**: Files modified/created
1185
2162
  . **Verification**: How you verified it works
1186
- . **Notes**: Follow-up needed (if any)`
2163
+ . **Notes**: Follow-up needed (if any)`,
2164
+ defaultModelId: "openai/gpt-5.5",
2165
+ metadata: {
2166
+ default: true
2167
+ }
1187
2168
  };
1188
2169
 
1189
- // src/agents/subagents/explore.ts
1190
- var exploreSubagent = {
1191
- id: "explore",
2170
+ // src/agents/modes/explore.ts
2171
+ var fastMode = {
2172
+ id: "fast",
1192
2173
  name: "Explore",
1193
2174
  description: "Read-only codebase exploration. Use for questions like 'find all usages of X', 'how does module Y work'.",
2175
+ defaultModelId: "openai/gpt-5.4-mini",
1194
2176
  instructions: `You are an expert code explorer. Your job is to investigate a codebase and answer a specific question or gather specific information.
1195
2177
 
1196
2178
  ## Rules
@@ -1216,14 +2198,15 @@ End with a structured summary:
1216
2198
  . **Key Files**: Most relevant files with line numbers
1217
2199
  . **Details**: Additional context if needed
1218
2200
 
1219
- Keep your summary under 300 words.`,
1220
- allowedWorkspaceTools: [chunkJHYTJMKT_cjs.MC_TOOLS.VIEW, chunkJHYTJMKT_cjs.MC_TOOLS.SEARCH_CONTENT, chunkJHYTJMKT_cjs.MC_TOOLS.FIND_FILES]
2201
+ Keep your summary under 300 words.`
1221
2202
  };
1222
2203
 
1223
- // src/agents/subagents/plan.ts
1224
- var planSubagent = {
2204
+ // src/agents/modes/plan.ts
2205
+ var planMode = {
1225
2206
  id: "plan",
1226
2207
  name: "Plan",
2208
+ transitionsTo: "build",
2209
+ defaultModelId: "openai/gpt-5.5",
1227
2210
  description: "Read-only analysis and planning. Use for 'create an implementation plan for X', 'analyze the architecture of Y'.",
1228
2211
  instructions: `You are an expert software architect and planner. Your job is to analyze a codebase and produce a detailed implementation plan for a given task.
1229
2212
 
@@ -1253,7 +2236,9 @@ Structure your plan as:
1253
2236
  . **Risks**: Potential issues or edge cases (if any)
1254
2237
 
1255
2238
  Be specific about code locations (file paths, function names, line numbers). Keep the plan actionable and under 500 words.`,
1256
- allowedWorkspaceTools: [chunkJHYTJMKT_cjs.MC_TOOLS.VIEW, chunkJHYTJMKT_cjs.MC_TOOLS.SEARCH_CONTENT, chunkJHYTJMKT_cjs.MC_TOOLS.FIND_FILES]
2239
+ metadata: {
2240
+ default: false
2241
+ }
1257
2242
  };
1258
2243
 
1259
2244
  // src/agents/thread-caveman-state.ts
@@ -1933,17 +2918,6 @@ function createEfficiencyScorer() {
1933
2918
  return parts.join("\n");
1934
2919
  });
1935
2920
  }
1936
- function v1ModeToLegacy(mode, agent) {
1937
- const meta = mode.metadata ?? {};
1938
- return {
1939
- id: mode.id,
1940
- name: mode.description,
1941
- default: meta.default === true,
1942
- defaultModelId: mode.defaultModelId,
1943
- color: typeof meta.color === "string" ? meta.color : void 0,
1944
- agent
1945
- };
1946
- }
1947
2921
  var VALID_EVENTS = [
1948
2922
  "PreToolUse",
1949
2923
  "PostToolUse",
@@ -2581,13 +3555,14 @@ function createMcpManager(projectDir, configDirName = chunkJ3ISOP5J_cjs.DEFAULT_
2581
3555
  });
2582
3556
  try {
2583
3557
  const { toolsets, errors } = await client.listToolsetsWithErrors();
2584
- for (const [serverName, serverTools] of Object.entries(toolsets)) {
3558
+ const typedToolsets = toolsets;
3559
+ for (const [serverName, serverTools] of Object.entries(typedToolsets)) {
2585
3560
  for (const [toolName, toolConfig] of Object.entries(serverTools)) {
2586
3561
  tools[`${serverName}_${toolName}`] = toolConfig;
2587
3562
  }
2588
3563
  }
2589
3564
  for (const name of serverNames) {
2590
- const serverTools = toolsets[name];
3565
+ const serverTools = typedToolsets[name];
2591
3566
  if (serverTools && Object.keys(serverTools).length > 0) {
2592
3567
  const toolNames = Object.keys(serverTools).map((t) => `${name}_${t}`);
2593
3568
  serverStatuses.set(name, {
@@ -3064,31 +4039,8 @@ async function createVectorStore(config, effectiveBackend = config.backend) {
3064
4039
  }
3065
4040
 
3066
4041
  // src/index.ts
3067
- var PROVIDER_TO_OAUTH_ID = {
3068
- anthropic: "anthropic",
3069
- openai: "openai-codex",
3070
- "github-copilot": "github-copilot"
3071
- };
3072
4042
  var CODE_AGENT_ID = "code-agent";
3073
- function hash(value) {
3074
- return crypto.createHash("sha256").update(value).digest("hex").slice(0, 32);
3075
- }
3076
- function legacyModeToV1(mode, fallbackAgent) {
3077
- const agent = typeof mode.agent === "function" ? mode.agent({}) : mode.agent;
3078
- return {
3079
- id: mode.id,
3080
- defaultModelId: mode.defaultModelId ?? "openai/gpt-5.5",
3081
- description: mode.name,
3082
- ...mode.id === "plan" ? { transitionsTo: "build" } : {},
3083
- metadata: {
3084
- agentId: (agent ?? fallbackAgent).id,
3085
- color: mode.color,
3086
- default: mode.default,
3087
- name: mode.name
3088
- }
3089
- };
3090
- }
3091
- function applyEffectiveDefaultsToV1Modes(modes, effectiveDefaults) {
4043
+ function applyEffectiveDefaultsToModes(modes, effectiveDefaults) {
3092
4044
  return modes.map((mode) => {
3093
4045
  const savedModel = effectiveDefaults[mode.id];
3094
4046
  if (!savedModel) {
@@ -3101,16 +4053,16 @@ function applyEffectiveDefaultsToV1Modes(modes, effectiveDefaults) {
3101
4053
  });
3102
4054
  }
3103
4055
  function createAuthStorage() {
3104
- const authStorage = new chunkJ3ISOP5J_cjs.AuthStorage();
3105
- chunkNKTZDFIU_cjs.setAuthStorage(authStorage);
3106
- chunkNKTZDFIU_cjs.setAuthStorage3(authStorage);
3107
- chunkNKTZDFIU_cjs.setAuthStorage2(authStorage);
3108
- return authStorage;
4056
+ const authStorage2 = new chunkJ3ISOP5J_cjs.AuthStorage();
4057
+ setAuthStorage(authStorage2);
4058
+ setAuthStorage3(authStorage2);
4059
+ setAuthStorage2(authStorage2);
4060
+ return authStorage2;
3109
4061
  }
3110
- function resolveCloudObservabilityConfig(settings, authStorage, resourceId) {
4062
+ function resolveCloudObservabilityConfig(settings, authStorage2, resourceId) {
3111
4063
  const resourceConfig = settings.observability.resources[resourceId];
3112
4064
  if (resourceConfig) {
3113
- const token = authStorage.getStoredApiKey(`${chunkNKTZDFIU_cjs.OBSERVABILITY_AUTH_PREFIX}${resourceId}`);
4065
+ const token = authStorage2.getStoredApiKey(`${chunkXPPJHUAD_cjs.OBSERVABILITY_AUTH_PREFIX}${resourceId}`);
3114
4066
  if (token) {
3115
4067
  return { accessToken: token, projectId: resourceConfig.projectId };
3116
4068
  }
@@ -3130,10 +4082,9 @@ async function createMastraCode(config) {
3130
4082
  process.loadEnvFile(path__namespace.default.join(cwd, ".env"));
3131
4083
  } catch {
3132
4084
  }
3133
- const gatewayRegistry = llm.GatewayRegistry.getInstance({ useDynamicLoading: true });
3134
- const authStorage = createAuthStorage();
3135
- const globalSettings = chunkNKTZDFIU_cjs.loadSettings(config?.settingsPath);
3136
- const storedGatewayKey = authStorage.getStoredApiKey(chunkNKTZDFIU_cjs.MEMORY_GATEWAY_PROVIDER);
4085
+ const authStorage2 = createAuthStorage();
4086
+ const globalSettings = chunkXPPJHUAD_cjs.loadSettings(config?.settingsPath);
4087
+ const storedGatewayKey = authStorage2.getStoredApiKey(chunkXPPJHUAD_cjs.MEMORY_GATEWAY_PROVIDER);
3137
4088
  const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;
3138
4089
  if (storedGatewayKey) {
3139
4090
  process.env["MASTRA_GATEWAY_API_KEY"] ??= storedGatewayKey;
@@ -3148,11 +4099,11 @@ async function createMastraCode(config) {
3148
4099
  const envVars = cfg?.apiKeyEnvVar;
3149
4100
  providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;
3150
4101
  }
3151
- providerEnvVars[chunkNKTZDFIU_cjs.MEMORY_GATEWAY_PROVIDER] ??= "MASTRA_GATEWAY_API_KEY";
3152
- authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);
4102
+ providerEnvVars[chunkXPPJHUAD_cjs.MEMORY_GATEWAY_PROVIDER] ??= "MASTRA_GATEWAY_API_KEY";
4103
+ authStorage2.loadStoredApiKeysIntoEnv(providerEnvVars);
3153
4104
  } catch {
3154
- authStorage.loadStoredApiKeysIntoEnv({
3155
- [chunkNKTZDFIU_cjs.MEMORY_GATEWAY_PROVIDER]: "MASTRA_GATEWAY_API_KEY",
4105
+ authStorage2.loadStoredApiKeysIntoEnv({
4106
+ [chunkXPPJHUAD_cjs.MEMORY_GATEWAY_PROVIDER]: "MASTRA_GATEWAY_API_KEY",
3156
4107
  anthropic: "ANTHROPIC_API_KEY",
3157
4108
  openai: "OPENAI_API_KEY",
3158
4109
  google: "GOOGLE_GENERATIVE_AI_API_KEY",
@@ -3160,9 +4111,14 @@ async function createMastraCode(config) {
3160
4111
  deepseek: "DEEPSEEK_API_KEY"
3161
4112
  });
3162
4113
  }
3163
- void Promise.resolve(gatewayRegistry.syncGateways(true)).catch(() => {
4114
+ const mgApiKey = process.env["MASTRA_GATEWAY_API_KEY"] ?? storedGatewayKey;
4115
+ const mastraGatewayBaseUrl = (process.env["MASTRA_GATEWAY_URL"] ?? storedGatewayUrl ?? "https://gateway-api.mastra.ai").replace(/\/+$/, "").replace(/\/v1$/, "");
4116
+ const mastraCodeGateway = createMastraCodeGateway({
4117
+ mastraGatewayBaseUrl,
4118
+ mastraGatewayApiKey: mgApiKey,
4119
+ routeThroughMastraGateway: false,
4120
+ settingsPath: config?.settingsPath
3164
4121
  });
3165
- const mgApiKey = storedGatewayKey ?? process.env["MASTRA_GATEWAY_API_KEY"];
3166
4122
  const project = chunkJ3ISOP5J_cjs.detectProject(cwd);
3167
4123
  const resourceIdOverride = chunkJ3ISOP5J_cjs.getResourceIdOverride(project.rootPath, configDir);
3168
4124
  if (resourceIdOverride) {
@@ -3251,8 +4207,12 @@ async function createMastraCode(config) {
3251
4207
  "harness.state.reflectionThreshold"
3252
4208
  ],
3253
4209
  exporters: [
3254
- new observability.MastraStorageExporter({ strategy: "event-sourced" }),
3255
- new observability.MastraPlatformExporter(resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId))
4210
+ // Only persist traces locally when DuckDB observability is available
4211
+ // (via `/observability local on`). Without this guard the storage
4212
+ // exporter falls through to the default libsql backend and silently
4213
+ // fills the main database with gigabytes of span data.
4214
+ ...observabilityDomain ? [new observability.MastraStorageExporter({ strategy: "event-sourced" })] : [],
4215
+ new observability.MastraPlatformExporter(resolveCloudObservabilityConfig(globalSettings, authStorage2, project.resourceId))
3256
4216
  ],
3257
4217
  spanOutputProcessors: [new observability.SensitiveDataFilter()]
3258
4218
  }
@@ -3294,7 +4254,7 @@ async function createMastraCode(config) {
3294
4254
  id: CODE_AGENT_ID,
3295
4255
  name: "Code Agent",
3296
4256
  instructions: getDynamicInstructions,
3297
- model: chunkNKTZDFIU_cjs.getDynamicModel,
4257
+ model: getDynamicModel,
3298
4258
  tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage$1),
3299
4259
  hooks: createToolHooks(hookManager),
3300
4260
  scorers: {
@@ -3311,6 +4271,22 @@ async function createMastraCode(config) {
3311
4271
  // the tools into the toolset and registers the task state-signal processor,
3312
4272
  // so the task list persists across turns and survives OM truncation.
3313
4273
  signals: [new signals.TaskSignalProvider(), ...githubSignals$1 ? [githubSignals$1] : []],
4274
+ // Native goal mechanism: the in-loop goal step judges the thread's active
4275
+ // objective each qualifying iteration. The judge model is required for any
4276
+ // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires
4277
+ // the GoalStateProcessor so the `<current-objective>` signal persists across
4278
+ // turns. Per-thread overrides live in the ThreadState `goal` record and win
4279
+ // over these defaults.
4280
+ goal: {
4281
+ // Resolve the judge model through mastracode's gateway (a model-resolver
4282
+ // function) so provider credentials are injected; returns undefined when no
4283
+ // judge model is configured, keeping the goal step a no-op. Bind the same
4284
+ // `settingsPath` used above so the judge model and `maxRuns` come from one
4285
+ // config (a custom settings file would otherwise diverge).
4286
+ judge: (ctx) => getGoalJudgeModel(ctx, config?.settingsPath),
4287
+ maxRuns: globalSettings.models.goalMaxTurns ?? 50,
4288
+ prompt: tools.DEFAULT_GOAL_JUDGE_PROMPT
4289
+ },
3314
4290
  inputProcessors: [
3315
4291
  new processors.AgentsMDInjector({
3316
4292
  getIgnoredInstructionPaths: ({ requestContext }) => {
@@ -3323,35 +4299,26 @@ async function createMastraCode(config) {
3323
4299
  ],
3324
4300
  errorProcessors: [new processors.StreamErrorRetryProcessor(), new processors.PrefillErrorHandler(), new processors.ProviderHistoryCompat()]
3325
4301
  });
3326
- const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];
3327
- const defaultModesV1 = [
4302
+ const defaultModes = [
3328
4303
  {
3329
- id: "build",
3330
- description: "Build",
3331
- defaultModelId: "anthropic/claude-opus-4-7",
4304
+ ...buildMode,
3332
4305
  metadata: {
3333
- agentId: CODE_AGENT_ID,
3334
- color: chunkNKTZDFIU_cjs.mastra.green,
3335
- default: true
4306
+ ...buildMode.metadata,
4307
+ color: chunkXPPJHUAD_cjs.mastra.green
3336
4308
  }
3337
4309
  },
3338
4310
  {
3339
- id: "plan",
3340
- description: "Plan",
3341
- transitionsTo: "build",
3342
- defaultModelId: "openai/gpt-5.5",
4311
+ ...planMode,
3343
4312
  metadata: {
3344
- agentId: CODE_AGENT_ID,
3345
- color: chunkNKTZDFIU_cjs.mastra.purple
4313
+ ...planMode.metadata,
4314
+ color: chunkXPPJHUAD_cjs.mastra.purple
3346
4315
  }
3347
4316
  },
3348
4317
  {
3349
- id: "fast",
3350
- description: "Fast",
3351
- defaultModelId: "cerebras/zai-glm-4.7",
4318
+ ...fastMode,
3352
4319
  metadata: {
3353
- agentId: CODE_AGENT_ID,
3354
- color: chunkNKTZDFIU_cjs.mastra.orange
4320
+ ...fastMode.metadata,
4321
+ color: chunkXPPJHUAD_cjs.mastra.orange
3355
4322
  }
3356
4323
  }
3357
4324
  ];
@@ -3359,13 +4326,14 @@ async function createMastraCode(config) {
3359
4326
  {
3360
4327
  id: "gateway-sync",
3361
4328
  intervalMs: 5 * 60 * 1e3,
4329
+ immediate: false,
3362
4330
  handler: () => syncGateways()
3363
4331
  }
3364
4332
  ];
3365
4333
  const heartbeatHandlers = config?.heartbeatHandlers ?? defaultHeartbeatHandlers;
3366
- const anthropicCred = authStorage.get("anthropic");
3367
- const openaiCred = authStorage.get("openai-codex");
3368
- const githubCopilotCred = authStorage.get("github-copilot");
4334
+ const anthropicCred = authStorage2.get("anthropic");
4335
+ const openaiCred = authStorage2.get("openai-codex");
4336
+ const githubCopilotCred = authStorage2.get("github-copilot");
3369
4337
  const startupAccess = {
3370
4338
  anthropic: anthropicCred?.type === "oauth" ? "oauth" : anthropicCred?.type === "api_key" && anthropicCred.key.trim().length > 0 ? "apikey" : false,
3371
4339
  openai: openaiCred?.type === "oauth" ? "oauth" : openaiCred?.type === "api_key" && openaiCred.key.trim().length > 0 ? "apikey" : false,
@@ -3391,45 +4359,20 @@ async function createMastraCode(config) {
3391
4359
  }
3392
4360
  } catch {
3393
4361
  }
3394
- const builtinPacks = chunkNKTZDFIU_cjs.getAvailableModePacks(startupAccess);
3395
- const builtinOmPacks = chunkNKTZDFIU_cjs.getAvailableOmPacks(startupAccess);
3396
- const effectiveDefaults = chunkNKTZDFIU_cjs.resolveModelDefaults(globalSettings, builtinPacks);
3397
- const effectiveObserverModel = chunkNKTZDFIU_cjs.resolveOmRoleModel(globalSettings, "observer", builtinOmPacks);
3398
- const effectiveReflectorModel = chunkNKTZDFIU_cjs.resolveOmRoleModel(globalSettings, "reflector", builtinOmPacks);
4362
+ const builtinPacks = chunkXPPJHUAD_cjs.getAvailableModePacks(startupAccess);
4363
+ const builtinOmPacks = chunkXPPJHUAD_cjs.getAvailableOmPacks(startupAccess);
4364
+ const effectiveDefaults = chunkXPPJHUAD_cjs.resolveModelDefaults(globalSettings, builtinPacks);
4365
+ const effectiveObserverModel = chunkXPPJHUAD_cjs.resolveOmRoleModel(globalSettings, "observer", builtinOmPacks);
4366
+ const effectiveReflectorModel = chunkXPPJHUAD_cjs.resolveOmRoleModel(globalSettings, "reflector", builtinOmPacks);
3399
4367
  const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? void 0;
3400
4368
  const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? void 0;
3401
4369
  const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? void 0;
3402
4370
  const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? "auto";
3403
- const modesV1 = applyEffectiveDefaultsToV1Modes(
3404
- config?.modes ? config.modes.map((mode) => legacyModeToV1(mode, codeAgent)) : defaultModesV1,
3405
- effectiveDefaults
3406
- );
3407
- const defaultModeId = modesV1.find((mode) => mode.metadata?.default === true)?.id ?? modesV1.find((mode) => mode.id === "plan")?.id ?? modesV1[0]?.id;
4371
+ const modes = applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults);
4372
+ const defaultModeId = modes.find((mode) => mode.metadata?.default === true)?.id ?? modes.find((mode) => mode.id === "build")?.id ?? modes[0]?.id;
3408
4373
  if (!defaultModeId) {
3409
4374
  throw new Error("MastraCode requires at least one mode");
3410
4375
  }
3411
- const modes = modesV1.map((mode) => v1ModeToLegacy(mode, codeAgent));
3412
- const subagentModeMap = { explore: "fast", plan: "plan", execute: "build" };
3413
- const subagents = (config?.subagents ?? defaultSubagents).map((sa) => {
3414
- const modeId = subagentModeMap[sa.id];
3415
- const model = modeId ? effectiveDefaults[modeId] : void 0;
3416
- let filtered = sa;
3417
- if (config?.disabledTools?.length) {
3418
- if (sa.allowedWorkspaceTools) {
3419
- filtered = {
3420
- ...filtered,
3421
- allowedWorkspaceTools: sa.allowedWorkspaceTools.filter((t) => !config.disabledTools.includes(t))
3422
- };
3423
- }
3424
- if (sa.tools) {
3425
- filtered = {
3426
- ...filtered,
3427
- tools: Object.fromEntries(Object.entries(sa.tools).filter(([k]) => !config.disabledTools.includes(k)))
3428
- };
3429
- }
3430
- }
3431
- return model ? { ...filtered, defaultModelId: model } : filtered;
3432
- });
3433
4376
  const globalInitialState = {};
3434
4377
  if (effectiveObserverModel) {
3435
4378
  globalInitialState.observerModelId = effectiveObserverModel;
@@ -3463,33 +4406,6 @@ async function createMastraCode(config) {
3463
4406
  globalInitialState[`subagentModelId_${key}`] = modelId;
3464
4407
  }
3465
4408
  }
3466
- const { threads } = await (await storage$1.getStore("memory"))?.listThreads({
3467
- perPage: false,
3468
- filter: {
3469
- resourceId: project.resourceId
3470
- }
3471
- }) ?? { threads: [] };
3472
- const ownerId = `mastracode-${hash(`${os.hostname()}\0${project.rootPath}`)}`;
3473
- await Promise.all(
3474
- threads.map((thread) => {
3475
- const sessionHash = hash(`${thread.resourceId}\0${thread.id}`);
3476
- const meta = thread.metadata;
3477
- const modeId = typeof meta?.currentModeId === "string" ? meta.currentModeId : defaultModeId;
3478
- const mode = modesV1.find((mode2) => mode2.id === modeId) ?? modesV1.find((mode2) => mode2.id === defaultModeId);
3479
- const modelId = typeof meta?.currentModelId === "string" ? meta.currentModelId : mode.defaultModelId;
3480
- return harnessStorage.saveSession({
3481
- id: `sess-${sessionHash}`,
3482
- ownerId,
3483
- resourceId: thread.resourceId,
3484
- threadId: thread.id,
3485
- modeId: mode.id,
3486
- modelId,
3487
- origin: "top-level",
3488
- createdAt: thread.createdAt,
3489
- lastActivityAt: thread.updatedAt
3490
- });
3491
- })
3492
- );
3493
4409
  const typedStateSchema = stateSchema;
3494
4410
  const harness$1 = new harness.Harness({
3495
4411
  id: "mastra-code",
@@ -3499,8 +4415,9 @@ async function createMastraCode(config) {
3499
4415
  memory,
3500
4416
  pubsub: signalsPubSub,
3501
4417
  stateSchema: typedStateSchema,
3502
- subagents,
3503
- resolveModel: (modelId) => chunkNKTZDFIU_cjs.resolveModel(modelId),
4418
+ agent: codeAgent,
4419
+ subagents: config?.subagents ?? [],
4420
+ gateways: [mastraCodeGateway],
3504
4421
  toolCategoryResolver: chunkJHYTJMKT_cjs.getToolCategory,
3505
4422
  initialState: {
3506
4423
  projectPath: project.rootPath,
@@ -3517,83 +4434,21 @@ async function createMastraCode(config) {
3517
4434
  browser: config?.browser,
3518
4435
  modes,
3519
4436
  heartbeatHandlers,
3520
- modelAuthChecker: (provider) => {
3521
- const gatewayKey = authStorage.getStoredApiKey(chunkNKTZDFIU_cjs.MEMORY_GATEWAY_PROVIDER) ?? process.env["MASTRA_GATEWAY_API_KEY"];
3522
- if (gatewayKey) {
3523
- const providerConfig = gatewayRegistry.getProviders()[provider];
3524
- if (providerConfig?.gateway === "mastra") return true;
3525
- }
3526
- const oauthId = PROVIDER_TO_OAUTH_ID[provider];
3527
- if (oauthId && authStorage.isLoggedIn(oauthId)) {
3528
- return true;
3529
- }
3530
- if (authStorage.hasStoredApiKey(provider)) {
3531
- return true;
3532
- }
3533
- if (provider === "anthropic") {
3534
- const cred = authStorage.get("anthropic");
3535
- if (cred?.type === "api_key" && cred.key.trim().length > 0) {
3536
- return true;
3537
- }
3538
- }
3539
- if (provider === "openai") {
3540
- const cred = authStorage.get("openai-codex");
3541
- if (cred?.type === "api_key" && cred.key.trim().length > 0) {
3542
- return true;
3543
- }
3544
- }
3545
- const customProvider = chunkNKTZDFIU_cjs.loadSettings().customProviders.find((entry) => {
3546
- return provider === chunkNKTZDFIU_cjs.getCustomProviderId(entry.name);
3547
- });
3548
- if (customProvider) {
3549
- return true;
3550
- }
3551
- return void 0;
3552
- },
3553
- modelUseCountProvider: () => chunkNKTZDFIU_cjs.loadSettings().modelUseCounts,
4437
+ resolveModel,
4438
+ customModelCatalogProvider: createMastraCodeModelCatalogProvider(mastraCodeGateway),
4439
+ modelUseCountProvider: () => chunkXPPJHUAD_cjs.loadSettings().modelUseCounts,
3554
4440
  modelUseCountTracker: (modelId) => {
3555
4441
  try {
3556
- const settings = chunkNKTZDFIU_cjs.loadSettings();
4442
+ const settings = chunkXPPJHUAD_cjs.loadSettings();
3557
4443
  settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;
3558
- chunkNKTZDFIU_cjs.saveSettings(settings);
4444
+ chunkXPPJHUAD_cjs.saveSettings(settings);
3559
4445
  } catch (error) {
3560
4446
  console.error("Failed to persist model usage count", error);
3561
4447
  }
3562
4448
  },
3563
- customModelCatalogProvider: async () => {
3564
- const settings = chunkNKTZDFIU_cjs.loadSettings();
3565
- const customModels = [];
3566
- for (const provider of settings.customProviders) {
3567
- const providerId = chunkNKTZDFIU_cjs.getCustomProviderId(provider.name);
3568
- for (const modelName of provider.models) {
3569
- customModels.push({
3570
- id: chunkNKTZDFIU_cjs.toCustomProviderModelId(provider.name, modelName),
3571
- provider: providerId,
3572
- modelName,
3573
- hasApiKey: true,
3574
- apiKeyEnvVar: void 0
3575
- });
3576
- }
3577
- }
3578
- try {
3579
- const copilotModels = await chunkNKTZDFIU_cjs.getCopilotModelCatalog({ authStorage });
3580
- for (const m of copilotModels) {
3581
- customModels.push({
3582
- id: `github-copilot/${m.id}`,
3583
- provider: "github-copilot",
3584
- modelName: m.id,
3585
- hasApiKey: true,
3586
- apiKeyEnvVar: void 0
3587
- });
3588
- }
3589
- } catch (error) {
3590
- console.warn("Failed to load GitHub Copilot model catalog:", error);
3591
- }
3592
- return customModels;
3593
- },
3594
4449
  threadLock: crossProcessPubSub ? void 0 : {
3595
- acquire: chunkNKTZDFIU_cjs.acquireThreadLock,
3596
- release: chunkNKTZDFIU_cjs.releaseThreadLock
4450
+ acquire: chunkXPPJHUAD_cjs.acquireThreadLock,
4451
+ release: chunkXPPJHUAD_cjs.releaseThreadLock
3597
4452
  }
3598
4453
  // , harnessV1
3599
4454
  });
@@ -3611,8 +4466,8 @@ async function createMastraCode(config) {
3611
4466
  if (!threadId) return;
3612
4467
  githubSignals$1.stopAllPolling();
3613
4468
  try {
3614
- const threads2 = await harness$1.listThreads({ allResources: true });
3615
- const thread = threads2.find((item) => item.id === threadId);
4469
+ const threads = await harness$1.listThreads({ allResources: true });
4470
+ const thread = threads.find((item) => item.id === threadId);
3616
4471
  await githubSignals$1.startPollingForThread(
3617
4472
  {
3618
4473
  threadId,
@@ -3639,8 +4494,8 @@ async function createMastraCode(config) {
3639
4494
  mcpManager,
3640
4495
  hookManager,
3641
4496
  signalsPubSub,
3642
- authStorage,
3643
- resolveModel: chunkNKTZDFIU_cjs.resolveModel,
4497
+ authStorage: authStorage2,
4498
+ resolveModel,
3644
4499
  storageWarning,
3645
4500
  observabilityWarning,
3646
4501
  builtinPacks,
@@ -3652,5 +4507,5 @@ async function createMastraCode(config) {
3652
4507
 
3653
4508
  exports.createAuthStorage = createAuthStorage;
3654
4509
  exports.createMastraCode = createMastraCode;
3655
- //# sourceMappingURL=chunk-EATS4KOR.cjs.map
3656
- //# sourceMappingURL=chunk-EATS4KOR.cjs.map
4510
+ //# sourceMappingURL=chunk-3CO7PY6M.cjs.map
4511
+ //# sourceMappingURL=chunk-3CO7PY6M.cjs.map