@mastra/code-sdk 1.21.0-alpha.7 → 1.21.0-alpha.9
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/dist/agents/mastracode-gateway.d.ts +3 -1
- package/dist/agents/mastracode-gateway.js +11 -3
- package/dist/agents/model.js +15 -6
- package/dist/auth/account-rotation-processor.js +3 -3
- package/dist/headless/run-mc.js +7 -2
- package/dist/index.js +12 -5
- package/dist/providers/model-ids.d.ts +22 -0
- package/dist/providers/model-ids.js +55 -1
- package/dist/providers/openai-codex.d.ts +5 -1
- package/dist/providers/openai-codex.js +7 -4
- package/dist/thinking-catalog.d.ts +2 -2
- package/dist/thinking-catalog.js +5 -2
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +2 -1
- package/dist/tools/submit-plan.d.ts +28 -0
- package/dist/tools/submit-plan.js +104 -0
- package/dist/utils/plans.d.ts +19 -1
- package/dist/utils/plans.js +34 -17
- package/package.json +6 -6
|
@@ -4,6 +4,7 @@ import type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, Mastr
|
|
|
4
4
|
import { AuthStorage } from '../auth/storage.js';
|
|
5
5
|
import type { CredentialStore } from '../auth/types.js';
|
|
6
6
|
import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
|
|
7
|
+
import type { CodexServiceTier } from '../providers/model-ids.js';
|
|
7
8
|
import type { ThinkingLevel } from '../providers/openai-codex.js';
|
|
8
9
|
export { MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix, } from '../providers/model-ids.js';
|
|
9
10
|
export declare const MASTRACODE_GATEWAY_ID = "mastracode";
|
|
@@ -63,7 +64,7 @@ export declare class MastraCodeGateway extends MastraModelGateway {
|
|
|
63
64
|
* shared gateway router select MastraCode for auth resolution, so the status
|
|
64
65
|
* bar and `/api-keys` reflect OAuth logins instead of only checking env vars.
|
|
65
66
|
*/
|
|
66
|
-
handlesModel(
|
|
67
|
+
handlesModel(selectionId: string): boolean;
|
|
67
68
|
static resolveProviderAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string, credentials?: CredentialStore): GatewayAuthResult | undefined;
|
|
68
69
|
static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider;
|
|
69
70
|
createModelCatalogProvider(): CustomModelCatalogProvider;
|
|
@@ -78,6 +79,7 @@ export declare class MastraCodeGateway extends MastraModelGateway {
|
|
|
78
79
|
headers?: Record<string, string>;
|
|
79
80
|
transport?: any;
|
|
80
81
|
responsesWebSocket?: any;
|
|
82
|
+
codexServiceTier?: CodexServiceTier;
|
|
81
83
|
}): GatewayLanguageModel;
|
|
82
84
|
}
|
|
83
85
|
//# sourceMappingURL=mastracode-gateway.d.ts.map
|
|
@@ -4,7 +4,7 @@ import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinking
|
|
|
4
4
|
import { githubCopilotProvider } from "../providers/github-copilot.js";
|
|
5
5
|
import { createGoogleThinkingMiddleware } from "../providers/google-thinking.js";
|
|
6
6
|
import { kimiCodingProvider } from "../providers/kimi-coding.js";
|
|
7
|
-
import { MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, getCredentialProviderId, normalizeAnthropicModelId, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix } from "../providers/model-ids.js";
|
|
7
|
+
import { MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, getCredentialProviderId, normalizeAnthropicModelId, parseCodexModelSelection, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix } from "../providers/model-ids.js";
|
|
8
8
|
import { THINKING_LEVEL_TO_REASONING_EFFORT, buildOpenAICodexOAuthFetch, createCodexMiddleware, createPromptCacheKeyMiddleware, createReasoningEffortMiddleware, getEffectiveThinkingLevel, getRequestThreadId, openaiCodexProvider } from "../providers/openai-codex.js";
|
|
9
9
|
import { ModelRouterLanguageModelWithThinking, providerThinkingOptions, withThinkingOptionsModel } from "../providers/provider-thinking.js";
|
|
10
10
|
import { xaiProvider } from "../providers/xai.js";
|
|
@@ -216,7 +216,8 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
216
216
|
* shared gateway router select MastraCode for auth resolution, so the status
|
|
217
217
|
* bar and `/api-keys` reflect OAuth logins instead of only checking env vars.
|
|
218
218
|
*/
|
|
219
|
-
handlesModel(
|
|
219
|
+
handlesModel(selectionId) {
|
|
220
|
+
const { modelId } = parseCodexModelSelection(selectionId);
|
|
220
221
|
const parsed = parseGatewayRouterId(modelId, this);
|
|
221
222
|
if (!parsed.providerId || !parsed.modelId) return false;
|
|
222
223
|
if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;
|
|
@@ -327,6 +328,12 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
327
328
|
}
|
|
328
329
|
resolveLanguageModel(args) {
|
|
329
330
|
const customProvider = this.#customProvider(args.providerId);
|
|
331
|
+
const selection = customProvider ? void 0 : parseCodexModelSelection(`${args.providerId}/${args.modelId}`);
|
|
332
|
+
if (selection && selection.modelId !== `${args.providerId}/${args.modelId}`) args = {
|
|
333
|
+
...args,
|
|
334
|
+
modelId: selection.modelId.slice(OPENAI_PREFIX.length),
|
|
335
|
+
...selection.codexServiceTier ? { codexServiceTier: selection.codexServiceTier } : {}
|
|
336
|
+
};
|
|
330
337
|
if (customProvider) {
|
|
331
338
|
const provider = createOpenAICompatible({
|
|
332
339
|
name: args.providerId,
|
|
@@ -443,7 +450,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
443
450
|
const resolvedBareModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`).substring(OPENAI_PREFIX.length);
|
|
444
451
|
const effectiveLevel = getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel ?? "medium");
|
|
445
452
|
const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
|
|
446
|
-
const middleware = createCodexMiddleware(reasoningEffort);
|
|
453
|
+
const middleware = createCodexMiddleware(reasoningEffort, { serviceTier: args.codexServiceTier });
|
|
447
454
|
const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(args.headers));
|
|
448
455
|
const openai = createOpenAI({
|
|
449
456
|
apiKey: "oauth-gateway-placeholder",
|
|
@@ -468,6 +475,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
468
475
|
const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);
|
|
469
476
|
return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {
|
|
470
477
|
thinkingLevel: this.#thinkingLevel && getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel),
|
|
478
|
+
serviceTier: args.codexServiceTier,
|
|
471
479
|
headers: args.headers,
|
|
472
480
|
authStorage: this.#credentials
|
|
473
481
|
});
|
package/dist/agents/model.js
CHANGED
|
@@ -2,10 +2,10 @@ import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "..
|
|
|
2
2
|
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
3
3
|
import "../constants.js";
|
|
4
4
|
import { toMemoryModelId } from "../onboarding/packs.js";
|
|
5
|
-
import { loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
|
|
5
|
+
import { getCustomProviderId, loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
|
|
6
6
|
import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
|
|
7
7
|
import { GOOGLE_VERTEX_GATEWAY_ID, createGoogleVertexGateway } from "../providers/google-vertex-gateway.js";
|
|
8
|
-
import { MASTRA_GATEWAY_PREFIX, normalizeLegacyModelId, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix } from "../providers/model-ids.js";
|
|
8
|
+
import { MASTRA_GATEWAY_PREFIX, findRouteModelIndex, normalizeLegacyModelId, parseCodexModelSelection, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix } from "../providers/model-ids.js";
|
|
9
9
|
import { isThinkingLevelSetting } from "../thinking.js";
|
|
10
10
|
import { hasCredentialStoreProvider, hasCredentialTenantResolver, prepareCredentialTenant, resolveCredentialScope, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
|
|
11
11
|
import { hasCustomProvidersSource, resolveCustomProviders, setCustomProvidersSource } from "./custom-provider-source.js";
|
|
@@ -112,12 +112,20 @@ function resolveModel(modelId, options) {
|
|
|
112
112
|
return typeof value === "function" ? value.bind(currentModel) : value;
|
|
113
113
|
} });
|
|
114
114
|
}
|
|
115
|
+
/** Whether a model id resolves to a custom provider. A `mastra/...` id never does. */
|
|
116
|
+
function isCustomProviderModel(modelId, customProviders) {
|
|
117
|
+
const input = stripMastraCodeCustomProviderPrefix(normalizeLegacyModelId(modelId), customProviders);
|
|
118
|
+
if (input.startsWith("mastra/")) return false;
|
|
119
|
+
const providerId = input.split("/", 1)[0];
|
|
120
|
+
return customProviders.some((provider) => getCustomProviderId(provider.name) === providerId);
|
|
121
|
+
}
|
|
115
122
|
function resolveModelForRequest(modelId, options) {
|
|
116
123
|
reloadAuthStorage();
|
|
117
124
|
const headers = getAgentControllerHeaders(options?.requestContext);
|
|
118
125
|
const settings = loadSettings();
|
|
119
|
-
const legacyNormalizedInput = normalizeLegacyModelId(modelId);
|
|
120
126
|
const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;
|
|
127
|
+
const { modelId: canonicalModelId, codexServiceTier } = isCustomProviderModel(modelId, customProviders) ? { modelId } : parseCodexModelSelection(modelId);
|
|
128
|
+
const legacyNormalizedInput = normalizeLegacyModelId(canonicalModelId);
|
|
121
129
|
const normalizedInput = stripMastraCodeCustomProviderPrefix(legacyNormalizedInput, customProviders);
|
|
122
130
|
const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);
|
|
123
131
|
const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);
|
|
@@ -184,7 +192,8 @@ function resolveModelForRequest(modelId, options) {
|
|
|
184
192
|
providerId,
|
|
185
193
|
modelId: bareModelId,
|
|
186
194
|
apiKey: auth?.apiKey ?? "",
|
|
187
|
-
headers
|
|
195
|
+
headers,
|
|
196
|
+
codexServiceTier
|
|
188
197
|
});
|
|
189
198
|
}
|
|
190
199
|
/** A tenant's own gateway key wins over the server's, so each org is billed to its own Mastra account. */
|
|
@@ -296,7 +305,7 @@ function getDynamicModel({ requestContext }, settingsPath, { modeless = false, d
|
|
|
296
305
|
const pendingEntryId = pendingFallback && typeof pendingFallback.toEntryId === "string" ? pendingFallback.toEntryId : void 0;
|
|
297
306
|
const startIndex = pendingEntryId ? route?.findIndex((entry) => entry.id === pendingEntryId) : 0;
|
|
298
307
|
const activeRoute = route && startIndex !== void 0 && startIndex >= 0 ? route.slice(startIndex) : void 0;
|
|
299
|
-
if (!activeRoute || activeRoute.length < 2 || activeRoute
|
|
308
|
+
if (!activeRoute || activeRoute.length < 2 || findRouteModelIndex(activeRoute, modelId) !== 0) return primary;
|
|
300
309
|
const firstId = typeof activeRoute[0]?.id === "string" && activeRoute[0].id.length > 0 ? activeRoute[0].id : void 0;
|
|
301
310
|
if (!firstId) return primary;
|
|
302
311
|
const entries = [{
|
|
@@ -324,7 +333,7 @@ function getDynamicModel({ requestContext }, settingsPath, { modeless = false, d
|
|
|
324
333
|
function identifyModel(modelId, model) {
|
|
325
334
|
return {
|
|
326
335
|
model,
|
|
327
|
-
id: toMemoryModelId(modelId)
|
|
336
|
+
id: toMemoryModelId(parseCodexModelSelection(modelId).modelId)
|
|
328
337
|
};
|
|
329
338
|
}
|
|
330
339
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolveCredentialStore } from "../agents/credential-resolver.js";
|
|
2
2
|
import { resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
|
|
3
|
-
import { getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
|
|
3
|
+
import { findRouteModelIndex, getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
|
|
4
4
|
import { isThinkingLevelSetting } from "../thinking.js";
|
|
5
5
|
import { getRequestAccountSelection, isRequestAccountRoutingExhausted, markRequestAccountRoutingExhausted, setRequestAccountSelection } from "./account-routing-context.js";
|
|
6
6
|
import { ProviderAuthRequiredError } from "./provider-auth-error.js";
|
|
@@ -330,7 +330,7 @@ function resolveAccountRoute(args, explicit) {
|
|
|
330
330
|
const pending = state?.mastracodePendingModelFallback;
|
|
331
331
|
const pendingMatchesThread = pending && typeof pending.toEntryId === "string" && typeof pending.toModelId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId);
|
|
332
332
|
const routeEntries = Array.isArray((state?.modelRoute)?.entries) ? (state?.modelRoute).entries ?? [] : [];
|
|
333
|
-
const entry = explicit ? explicit : pendingMatchesThread ? routeEntries.find((candidate) => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId) : routeEntries
|
|
333
|
+
const entry = explicit ? explicit : pendingMatchesThread ? routeEntries.find((candidate) => candidate.id === pending.toEntryId && candidate.modelId === pending.toModelId) : routeEntries[findRouteModelIndex(routeEntries, controller?.session?.modelId)];
|
|
334
334
|
if (!entry || typeof entry.id !== "string" || typeof entry.modelId !== "string") return null;
|
|
335
335
|
const providerId = providerFromModelId(entry.modelId);
|
|
336
336
|
if (!providerId) return null;
|
|
@@ -487,7 +487,7 @@ var AccountRotationProcessor = class {
|
|
|
487
487
|
const state = controller?.getState?.();
|
|
488
488
|
const route = (state?.modelRoute)?.entries;
|
|
489
489
|
const pending = state?.mastracodePendingModelFallback;
|
|
490
|
-
const startIndex = pending && typeof pending.toEntryId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? route?.findIndex((entry) => entry.id === pending.toEntryId) : route
|
|
490
|
+
const startIndex = pending && typeof pending.toEntryId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId) ? route?.findIndex((entry) => entry.id === pending.toEntryId) : route && findRouteModelIndex(route, controller?.session?.modelId);
|
|
491
491
|
if (!route || startIndex === void 0 || startIndex < 0 || route.length - startIndex < 2) {
|
|
492
492
|
args.state.modelRouteCascade = null;
|
|
493
493
|
return null;
|
package/dist/headless/run-mc.js
CHANGED
|
@@ -2,6 +2,7 @@ import { MODEL_FALLBACK_STATE_KEY } from "../auth/account-rotation-processor.js"
|
|
|
2
2
|
import { GoalManager } from "../goal-manager.js";
|
|
3
3
|
import { createGoalReminderSignal } from "../goal-signal.js";
|
|
4
4
|
import { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from "../onboarding/settings.js";
|
|
5
|
+
import { parseCodexModelSelection } from "../providers/model-ids.js";
|
|
5
6
|
import { autoApprovePolicy } from "./policy.js";
|
|
6
7
|
import { isSessionStartupCancelledError } from "@mastra/core/agent-controller";
|
|
7
8
|
// src/headless/run-mc.ts
|
|
@@ -323,7 +324,9 @@ function runMC(options) {
|
|
|
323
324
|
try {
|
|
324
325
|
if (options.mode && !controller.listModes().some((mode) => mode.id === options.mode)) return fail(`Unknown mode: "${options.mode}"`);
|
|
325
326
|
if (modelIdToApply) {
|
|
326
|
-
const
|
|
327
|
+
const available = await controller.listAvailableModels();
|
|
328
|
+
const { modelId } = parseCodexModelSelection(modelIdToApply);
|
|
329
|
+
const match = available.find((model) => model.id === modelId);
|
|
327
330
|
if (!match) {
|
|
328
331
|
if (modelSource === "flag") return fail(`Unknown model: "${modelIdToApply}"`);
|
|
329
332
|
return fail(`Unknown model "${modelIdToApply}" configured for mode "${modeIdForModel}"`);
|
|
@@ -360,7 +363,9 @@ function runMC(options) {
|
|
|
360
363
|
const packModeId = options.mode ?? session.mode.get();
|
|
361
364
|
const packSelection = options.pack.resolve(packModeId);
|
|
362
365
|
if (!packSelection) return fail(`Model pack "${options.pack.id}" has no model for ${packModeId} mode`);
|
|
363
|
-
const
|
|
366
|
+
const available = await controller.listAvailableModels();
|
|
367
|
+
const { modelId } = parseCodexModelSelection(packSelection.modelId);
|
|
368
|
+
const match = available.find((model) => model.id === modelId);
|
|
364
369
|
if (!match) return fail(`Unknown model "${packSelection.modelId}" from pack "${options.pack.id}"`);
|
|
365
370
|
if (!match.hasApiKey) {
|
|
366
371
|
const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : "";
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,7 @@ import { CODE_AGENT_ID, DEFAULT_OM_MODEL_ID, validateConfigDirName } from "./con
|
|
|
21
21
|
import { resolveAgentStreamsOff, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent } from "./experimental-agent.js";
|
|
22
22
|
import "./hooks/index.js";
|
|
23
23
|
import { KnowledgeInspectorError, createKnowledgeInspector } from "./knowledge-inspector.js";
|
|
24
|
+
import { createSubmitPlanTool } from "./tools/submit-plan.js";
|
|
24
25
|
import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeSessionScopes } from "./knowledge-scope.js";
|
|
25
26
|
import "./mcp/index.js";
|
|
26
27
|
import { getAvailableOmPacks, resolveAutoOMModelId } from "./onboarding/packs.js";
|
|
@@ -31,22 +32,24 @@ import { PluginSignalLane } from "./plugins/signal-lane.js";
|
|
|
31
32
|
import { PlanRejectionAbortProcessor } from "./processors/plan-rejection-abort.js";
|
|
32
33
|
import { createAmazonBedrockGateway } from "./providers/amazon-bedrock-gateway.js";
|
|
33
34
|
import { setAuthStorage } from "./providers/claude-max.js";
|
|
34
|
-
import { HookManager } from "./hooks/manager.js";
|
|
35
35
|
import { createGitHubCopilotGateway } from "./providers/github-copilot-gateway.js";
|
|
36
36
|
import { setAuthStorage as setAuthStorage$1 } from "./providers/github-copilot.js";
|
|
37
|
-
import {
|
|
37
|
+
import { HookManager } from "./hooks/manager.js";
|
|
38
38
|
import { createGoogleVertexGateway } from "./providers/google-vertex-gateway.js";
|
|
39
39
|
import { setAuthStorage as setAuthStorage$2 } from "./providers/kimi-coding.js";
|
|
40
|
+
import { createMcpManager } from "./mcp/manager.js";
|
|
41
|
+
import { parseCodexModelSelection } from "./providers/model-ids.js";
|
|
40
42
|
import { setAuthStorage as setAuthStorage$3 } from "./providers/openai-codex.js";
|
|
41
43
|
import { setAuthStorage as setAuthStorage$4 } from "./providers/xai.js";
|
|
42
44
|
import "./schedules/index.js";
|
|
43
45
|
import { stateSchema } from "./schema.js";
|
|
46
|
+
import { mastraBrand } from "./theme-palette.js";
|
|
44
47
|
import { assembleSchedulePrompt } from "./schedules/prompt.js";
|
|
45
48
|
import { ThreadScheduler, scheduleSignalAttributes, shortScheduleId } from "./schedules/scheduler.js";
|
|
46
49
|
import { runScript } from "./schedules/run-script.js";
|
|
47
50
|
import { createScheduleTools } from "./schedules/tools.js";
|
|
48
|
-
import { mastraBrand } from "./theme-palette.js";
|
|
49
51
|
import { isThinkingLevelSetting } from "./thinking.js";
|
|
52
|
+
import "./tools/index.js";
|
|
50
53
|
import { DiscardingScoresStorage } from "./utils/discarding-scores-storage.js";
|
|
51
54
|
import { syncGateways } from "./utils/gateway-sync.js";
|
|
52
55
|
import { openLocalObservabilityStore } from "./utils/local-observability.js";
|
|
@@ -978,6 +981,8 @@ async function createMastraCodeAgentController(config) {
|
|
|
978
981
|
backgroundToolsEnabled,
|
|
979
982
|
plansDir: config?.plansDir
|
|
980
983
|
});
|
|
984
|
+
const registersSubmitPlanTool = !disabledBuiltinTools.has("submit_plan");
|
|
985
|
+
const controllerDisabledBuiltinTools = registersSubmitPlanTool ? [...config?.disableBuiltinTools ?? [], "submit_plan"] : config?.disableBuiltinTools;
|
|
981
986
|
let controller;
|
|
982
987
|
controller = new AgentController({
|
|
983
988
|
id: "mastra-code",
|
|
@@ -1002,7 +1007,8 @@ async function createMastraCodeAgentController(config) {
|
|
|
1002
1007
|
},
|
|
1003
1008
|
agent: codeAgent,
|
|
1004
1009
|
subagents,
|
|
1005
|
-
...
|
|
1010
|
+
...controllerDisabledBuiltinTools?.length ? { disableBuiltinTools: controllerDisabledBuiltinTools } : {},
|
|
1011
|
+
...registersSubmitPlanTool ? { tools: { submit_plan: createSubmitPlanTool({ plansDir: config?.plansDir }) } } : {},
|
|
1006
1012
|
resolveSubagentModel: (modelId, { requestContext }) => routesToOtherGateway(modelId, Object.values(controller.getMastra()?.listGateways() ?? {}), /* @__PURE__ */ new Set([
|
|
1007
1013
|
mastraCodeGateway.id,
|
|
1008
1014
|
amazonBedrockGateway.id,
|
|
@@ -1038,7 +1044,8 @@ async function createMastraCodeAgentController(config) {
|
|
|
1038
1044
|
modelUseCountTracker: (modelId) => {
|
|
1039
1045
|
try {
|
|
1040
1046
|
const settings = loadSettings();
|
|
1041
|
-
|
|
1047
|
+
const { modelId: canonicalModelId } = parseCodexModelSelection(modelId);
|
|
1048
|
+
settings.modelUseCounts[canonicalModelId] = (settings.modelUseCounts[canonicalModelId] ?? 0) + 1;
|
|
1042
1049
|
saveSettings(settings);
|
|
1043
1050
|
} catch (error) {
|
|
1044
1051
|
console.error("Failed to persist model usage count", error);
|
|
@@ -27,5 +27,27 @@ export declare function normalizeLegacyProviderId(providerId: string): string;
|
|
|
27
27
|
export declare function normalizeLegacyModelId(modelId: string): string;
|
|
28
28
|
/** Credential-store id that authenticates a catalog provider id. */
|
|
29
29
|
export declare function getCredentialProviderId(providerId: string): string;
|
|
30
|
+
export type CodexServiceTier = 'fast';
|
|
31
|
+
/** `:fast` is reserved on native OpenAI selections, not a catalog model suffix. */
|
|
32
|
+
export declare function parseCodexModelSelection(modelId: string): {
|
|
33
|
+
modelId: string;
|
|
34
|
+
codexServiceTier?: CodexServiceTier;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Adds a `<model>:fast` entry right after each connected OpenAI model that has
|
|
38
|
+
* a Fast tier, when OpenAI is signed in with Codex (Fast has no effect with an
|
|
39
|
+
* API key). Fast entries already in the list are replaced.
|
|
40
|
+
*/
|
|
41
|
+
export declare function withCodexFastModels<T extends {
|
|
42
|
+
id: string;
|
|
43
|
+
modelName: string;
|
|
44
|
+
hasApiKey: boolean;
|
|
45
|
+
}>(models: T[], { codexOAuth }: {
|
|
46
|
+
codexOAuth: boolean;
|
|
47
|
+
}): T[];
|
|
48
|
+
/** Prefer the exact selection if both standard and Fast entries for a model exist. */
|
|
49
|
+
export declare function findRouteModelIndex(entries: Array<{
|
|
50
|
+
modelId?: unknown;
|
|
51
|
+
}>, selectionId: unknown): number;
|
|
30
52
|
export declare function remapOpenAIModelForCodexOAuth(modelId: string): string;
|
|
31
53
|
//# sourceMappingURL=model-ids.d.ts.map
|
|
@@ -65,6 +65,60 @@ function getCredentialProviderId(providerId) {
|
|
|
65
65
|
if (providerId === "kimi-code-plan-cn") return KIMI_CODING_CREDENTIAL_ID;
|
|
66
66
|
return providerId;
|
|
67
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* OpenAI models with a Fast tier on Codex sign-in, per OpenAI's Codex speed docs
|
|
70
|
+
* and rate card. On any other model the service runs the request at standard
|
|
71
|
+
* speed, so `:fast` is dropped there instead of being sent.
|
|
72
|
+
*/
|
|
73
|
+
const CODEX_FAST_MODELS = /* @__PURE__ */ new Set([
|
|
74
|
+
"gpt-6.2-sol",
|
|
75
|
+
"gpt-6.2-astra",
|
|
76
|
+
"gpt-6.1-sol",
|
|
77
|
+
"gpt-6.1-terra",
|
|
78
|
+
"gpt-6-astra",
|
|
79
|
+
"gpt-6-sol",
|
|
80
|
+
"gpt-6-luna",
|
|
81
|
+
"gpt-5.6",
|
|
82
|
+
"gpt-5.6-sol",
|
|
83
|
+
"gpt-5.5",
|
|
84
|
+
"gpt-5.4"
|
|
85
|
+
]);
|
|
86
|
+
/** `:fast` is reserved on native OpenAI selections, not a catalog model suffix. */
|
|
87
|
+
function parseCodexModelSelection(modelId) {
|
|
88
|
+
const selection = stripMastraGatewayPrefix(modelId);
|
|
89
|
+
if (!/^openai\/[^/:]+:fast$/.test(selection)) return { modelId };
|
|
90
|
+
const canonicalModelId = modelId.slice(0, -5);
|
|
91
|
+
return CODEX_FAST_MODELS.has(selection.slice(7, -5)) ? {
|
|
92
|
+
modelId: canonicalModelId,
|
|
93
|
+
codexServiceTier: "fast"
|
|
94
|
+
} : { modelId: canonicalModelId };
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Adds a `<model>:fast` entry right after each connected OpenAI model that has
|
|
98
|
+
* a Fast tier, when OpenAI is signed in with Codex (Fast has no effect with an
|
|
99
|
+
* API key). Fast entries already in the list are replaced.
|
|
100
|
+
*/
|
|
101
|
+
function withCodexFastModels(models, { codexOAuth }) {
|
|
102
|
+
const listed = [];
|
|
103
|
+
for (const model of models) {
|
|
104
|
+
if (parseCodexModelSelection(model.id).modelId !== model.id) continue;
|
|
105
|
+
listed.push(model);
|
|
106
|
+
if (codexOAuth && model.hasApiKey && model.id.startsWith("openai/") && parseCodexModelSelection(`${model.id}:fast`).codexServiceTier) listed.push({
|
|
107
|
+
...model,
|
|
108
|
+
id: `${model.id}:fast`,
|
|
109
|
+
modelName: `${model.modelName}:fast`
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return listed;
|
|
113
|
+
}
|
|
114
|
+
/** Prefer the exact selection if both standard and Fast entries for a model exist. */
|
|
115
|
+
function findRouteModelIndex(entries, selectionId) {
|
|
116
|
+
if (typeof selectionId !== "string") return -1;
|
|
117
|
+
const exact = entries.findIndex((entry) => entry.modelId === selectionId);
|
|
118
|
+
if (exact !== -1) return exact;
|
|
119
|
+
const { modelId } = parseCodexModelSelection(selectionId);
|
|
120
|
+
return entries.findIndex((entry) => typeof entry.modelId === "string" && parseCodexModelSelection(entry.modelId).modelId === modelId);
|
|
121
|
+
}
|
|
68
122
|
function remapOpenAIModelForCodexOAuth(modelId) {
|
|
69
123
|
const normalizedModelId = stripMastraGatewayPrefix(modelId);
|
|
70
124
|
if (!normalizedModelId.startsWith("openai/")) return modelId;
|
|
@@ -75,4 +129,4 @@ function remapOpenAIModelForCodexOAuth(modelId) {
|
|
|
75
129
|
const remappedModelId = `${OPENAI_PREFIX}${codexModelId}`;
|
|
76
130
|
return modelId.startsWith("mastra/") ? `${MASTRA_GATEWAY_PREFIX}${remappedModelId}` : remappedModelId;
|
|
77
131
|
}
|
|
78
|
-
export { ANTHROPIC_PREFIX, KIMI_CODING_CREDENTIAL_ID, KIMI_CODING_PROVIDER_ID, MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, getCredentialProviderId, normalizeAnthropicModelId, normalizeLegacyModelId, normalizeLegacyProviderId, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix };
|
|
132
|
+
export { ANTHROPIC_PREFIX, KIMI_CODING_CREDENTIAL_ID, KIMI_CODING_PROVIDER_ID, MASTRA_GATEWAY_PREFIX, OPENAI_PREFIX, findRouteModelIndex, getCredentialProviderId, normalizeAnthropicModelId, normalizeLegacyModelId, normalizeLegacyProviderId, parseCodexModelSelection, remapOpenAIModelForCodexOAuth, stripMastraGatewayPrefix, withCodexFastModels };
|
|
@@ -12,6 +12,7 @@ import type { LanguageModelMiddleware } from 'ai';
|
|
|
12
12
|
import { AuthStorage } from '../auth/storage.js';
|
|
13
13
|
import type { CredentialStore } from '../auth/types.js';
|
|
14
14
|
import type { ThinkingLevelSetting } from '../thinking.js';
|
|
15
|
+
import type { CodexServiceTier } from './model-ids.js';
|
|
15
16
|
export { supportsMaxReasoningEffort } from '../thinking.js';
|
|
16
17
|
/**
|
|
17
18
|
* Get or create the shared AuthStorage instance
|
|
@@ -27,7 +28,9 @@ export declare const THINKING_LEVEL_TO_REASONING_EFFORT: Record<ThinkingLevel, s
|
|
|
27
28
|
/**
|
|
28
29
|
* Create Codex middleware with the given reasoning effort level.
|
|
29
30
|
*/
|
|
30
|
-
export declare function createCodexMiddleware(reasoningEffort?: string
|
|
31
|
+
export declare function createCodexMiddleware(reasoningEffort?: string, oauthOptions?: {
|
|
32
|
+
serviceTier?: CodexServiceTier;
|
|
33
|
+
}): LanguageModelMiddleware;
|
|
31
34
|
/**
|
|
32
35
|
* The thread a model request belongs to, from the `x-thread-id` header that
|
|
33
36
|
* model resolution adds for requests made inside a thread.
|
|
@@ -106,5 +109,6 @@ export declare function openaiCodexProvider(modelId?: string, options?: {
|
|
|
106
109
|
thinkingLevel?: ThinkingLevel;
|
|
107
110
|
headers?: Record<string, string>;
|
|
108
111
|
authStorage?: CredentialStore;
|
|
112
|
+
serviceTier?: CodexServiceTier;
|
|
109
113
|
}): MastraModelConfig;
|
|
110
114
|
//# sourceMappingURL=openai-codex.d.ts.map
|
|
@@ -51,18 +51,20 @@ const THINKING_LEVEL_TO_REASONING_EFFORT = {
|
|
|
51
51
|
/**
|
|
52
52
|
* Create Codex middleware with the given reasoning effort level.
|
|
53
53
|
*/
|
|
54
|
-
function createCodexMiddleware(reasoningEffort) {
|
|
54
|
+
function createCodexMiddleware(reasoningEffort, oauthOptions) {
|
|
55
55
|
return {
|
|
56
56
|
specificationVersion: "v4",
|
|
57
57
|
transformParams: async ({ params }) => {
|
|
58
58
|
if (params.temperature !== void 0 && params.temperature !== null) delete params.topP;
|
|
59
|
+
const fast = oauthOptions && (oauthOptions.serviceTier === "fast" || params.providerOptions?.mastracode?.codexServiceTier === "fast");
|
|
59
60
|
params.providerOptions = {
|
|
60
61
|
...params.providerOptions,
|
|
61
62
|
openai: {
|
|
62
63
|
...params.providerOptions?.openai ?? {},
|
|
63
64
|
instructions: CODEX_INSTRUCTIONS,
|
|
64
65
|
store: false,
|
|
65
|
-
...reasoningEffort ? { reasoningEffort } : {}
|
|
66
|
+
...reasoningEffort ? { reasoningEffort } : {},
|
|
67
|
+
...fast ? { serviceTier: "priority" } : {}
|
|
66
68
|
}
|
|
67
69
|
};
|
|
68
70
|
return params;
|
|
@@ -397,9 +399,10 @@ function openaiCodexProvider(modelId = "codex-mini-latest", options) {
|
|
|
397
399
|
const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
|
|
398
400
|
const headers = options?.headers;
|
|
399
401
|
const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));
|
|
400
|
-
const
|
|
402
|
+
const useTestApiKey = process.env.NODE_ENV === "test" || Boolean(process.env.VITEST);
|
|
403
|
+
const middleware = [createCodexMiddleware(reasoningEffort, { serviceTier: options?.serviceTier }), ...promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : []];
|
|
401
404
|
const baseURL = process.env.OPENAI_BASE_URL;
|
|
402
|
-
if (
|
|
405
|
+
if (useTestApiKey) {
|
|
403
406
|
const openai = createOpenAI({
|
|
404
407
|
apiKey: "test-api-key",
|
|
405
408
|
baseURL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { ThinkingLevelSetting } from './thinking.js';
|
|
2
|
-
export declare function runCatalogThinkingLevel(
|
|
3
|
-
export declare function getCatalogThinkingLevels(
|
|
2
|
+
export declare function runCatalogThinkingLevel(selectionId: string, level: ThinkingLevelSetting): ThinkingLevelSetting;
|
|
3
|
+
export declare function getCatalogThinkingLevels(selectionId: string): ThinkingLevelSetting[];
|
|
4
4
|
//# sourceMappingURL=thinking-catalog.d.ts.map
|
package/dist/thinking-catalog.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
+
import { parseCodexModelSelection } from "./providers/model-ids.js";
|
|
1
2
|
import { getAvailableThinkingLevelsForModel, runThinkingLevel } from "./thinking.js";
|
|
2
3
|
import { getModelReasoningOptions } from "@mastra/core/llm";
|
|
3
4
|
// src/thinking-catalog.ts
|
|
4
|
-
function runCatalogThinkingLevel(
|
|
5
|
+
function runCatalogThinkingLevel(selectionId, level) {
|
|
6
|
+
const { modelId } = parseCodexModelSelection(selectionId);
|
|
5
7
|
return runThinkingLevel(modelId, level, getModelReasoningOptions(modelId));
|
|
6
8
|
}
|
|
7
|
-
function getCatalogThinkingLevels(
|
|
9
|
+
function getCatalogThinkingLevels(selectionId) {
|
|
10
|
+
const { modelId } = parseCodexModelSelection(selectionId);
|
|
8
11
|
return getAvailableThinkingLevelsForModel(modelId, getModelReasoningOptions(modelId));
|
|
9
12
|
}
|
|
10
13
|
export { getCatalogThinkingLevels, runCatalogThinkingLevel };
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -3,4 +3,5 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export { createConfiguredWebTools, createParallelWebExtractTool, createParallelWebSearchTool, createWebExtractTool, createWebSearchTool, hasParallelKey, hasTavilyKey, resolveWebSearchProvider, } from './web-search.js';
|
|
5
5
|
export { requestSandboxAccessTool } from './request-sandbox-access.js';
|
|
6
|
+
export { createSubmitPlanTool } from './submit-plan.js';
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/tools/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { createConfiguredWebTools, createParallelWebExtractTool, createParallelWebSearchTool, createWebExtractTool, createWebSearchTool, hasParallelKey, hasTavilyKey, resolveWebSearchProvider } from "./web-search.js";
|
|
2
2
|
import { requestSandboxAccessTool } from "./request-sandbox-access.js";
|
|
3
|
-
|
|
3
|
+
import { createSubmitPlanTool } from "./submit-plan.js";
|
|
4
|
+
export { createConfiguredWebTools, createParallelWebExtractTool, createParallelWebSearchTool, createSubmitPlanTool, createWebExtractTool, createWebSearchTool, hasParallelKey, hasTavilyKey, requestSandboxAccessTool, resolveWebSearchProvider };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-side `submit_plan` for Mastra Code sessions.
|
|
3
|
+
*
|
|
4
|
+
* The core builtin (`@mastra/core/tools`) is deliberately filesystem-free: it suspends with
|
|
5
|
+
* the plan file `path` and expects the host to validate that path, read the plan, and fill
|
|
6
|
+
* `title`/`plan` for approval rendering and history replay. This module is that host.
|
|
7
|
+
*
|
|
8
|
+
* Reading at suspend time is what keeps the approval card renderable: the plan body travels
|
|
9
|
+
* with the suspension, so the card does not depend on a later file read that can fail once
|
|
10
|
+
* the sandbox is recreated, the plans directory moves, or the file is edited after
|
|
11
|
+
* submission (which would make the approved plan differ from the reviewed one).
|
|
12
|
+
*
|
|
13
|
+
* Only the first pass (validate, read, suspend) lives here. The description, schemas, the
|
|
14
|
+
* resumed pass and the no-`suspend` fallback are the builtin's own, because Mastra Code's
|
|
15
|
+
* rejection abort, Factory rules and the TUI match the builtin's result text.
|
|
16
|
+
*
|
|
17
|
+
* Registered through the AgentController's `tools` option, with `submit_plan` added to its
|
|
18
|
+
* `disableBuiltinTools` so the filesystem-free builtin is removed rather than left to be
|
|
19
|
+
* replaced by name in the toolset merge.
|
|
20
|
+
*/
|
|
21
|
+
declare const SUBMIT_PLAN_TOOL_ID = "submit_plan";
|
|
22
|
+
export interface SubmitPlanToolOptions {
|
|
23
|
+
/** Host-configured workspace-relative plans directory (e.g. `.artifacts/plans`). */
|
|
24
|
+
plansDir?: string;
|
|
25
|
+
}
|
|
26
|
+
export declare function createSubmitPlanTool(options?: SubmitPlanToolOptions): any;
|
|
27
|
+
export { SUBMIT_PLAN_TOOL_ID };
|
|
28
|
+
//# sourceMappingURL=submit-plan.d.ts.map
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { getLocalPlansDir, getLocalPlansRelativeDir, isPlanFilePath, parsePlanContent, resolvePlanPath } from "../utils/plans.js";
|
|
2
|
+
import * as path$1 from "path";
|
|
3
|
+
import { createTool, submitPlanTool } from "@mastra/core/tools";
|
|
4
|
+
// src/tools/submit-plan.ts
|
|
5
|
+
/**
|
|
6
|
+
* Host-side `submit_plan` for Mastra Code sessions.
|
|
7
|
+
*
|
|
8
|
+
* The core builtin (`@mastra/core/tools`) is deliberately filesystem-free: it suspends with
|
|
9
|
+
* the plan file `path` and expects the host to validate that path, read the plan, and fill
|
|
10
|
+
* `title`/`plan` for approval rendering and history replay. This module is that host.
|
|
11
|
+
*
|
|
12
|
+
* Reading at suspend time is what keeps the approval card renderable: the plan body travels
|
|
13
|
+
* with the suspension, so the card does not depend on a later file read that can fail once
|
|
14
|
+
* the sandbox is recreated, the plans directory moves, or the file is edited after
|
|
15
|
+
* submission (which would make the approved plan differ from the reviewed one).
|
|
16
|
+
*
|
|
17
|
+
* Only the first pass (validate, read, suspend) lives here. The description, schemas, the
|
|
18
|
+
* resumed pass and the no-`suspend` fallback are the builtin's own, because Mastra Code's
|
|
19
|
+
* rejection abort, Factory rules and the TUI match the builtin's result text.
|
|
20
|
+
*
|
|
21
|
+
* Registered through the AgentController's `tools` option, with `submit_plan` added to its
|
|
22
|
+
* `disableBuiltinTools` so the filesystem-free builtin is removed rather than left to be
|
|
23
|
+
* replaced by name in the toolset merge.
|
|
24
|
+
*/
|
|
25
|
+
const SUBMIT_PLAN_TOOL_ID = "submit_plan";
|
|
26
|
+
/**
|
|
27
|
+
* Where to write a plan and which path to submit. Named in every rejection so the agent can
|
|
28
|
+
* correct itself in one step instead of guessing.
|
|
29
|
+
*/
|
|
30
|
+
function plansDirGuidance(plansDir, plansDirAbs) {
|
|
31
|
+
return `Write the plan to "${plansDirAbs}/<name>.md" and submit "${plansDir}/<name>.md" (e.g. "${plansDir}/add-dark-mode.md").`;
|
|
32
|
+
}
|
|
33
|
+
function planPathError(detail, guidance) {
|
|
34
|
+
return `Cannot submit plan: ${detail} ${guidance}`;
|
|
35
|
+
}
|
|
36
|
+
function createSubmitPlanTool(options = {}) {
|
|
37
|
+
return createTool({
|
|
38
|
+
id: SUBMIT_PLAN_TOOL_ID,
|
|
39
|
+
description: submitPlanTool.description,
|
|
40
|
+
inputSchema: submitPlanTool.inputSchema,
|
|
41
|
+
suspendSchema: submitPlanTool.suspendSchema,
|
|
42
|
+
resumeSchema: submitPlanTool.resumeSchema,
|
|
43
|
+
execute: async (input, context) => {
|
|
44
|
+
const suspend = context?.agent?.suspend;
|
|
45
|
+
if (context?.agent?.resumeData !== void 0 || !suspend) return submitPlanTool.execute(input, context);
|
|
46
|
+
const submittedPath = input.path;
|
|
47
|
+
try {
|
|
48
|
+
const agentControllerCtx = context?.requestContext?.get("controller");
|
|
49
|
+
const state = agentControllerCtx?.getState();
|
|
50
|
+
const projectPath = state?.projectPath?.trim();
|
|
51
|
+
if (!projectPath) return {
|
|
52
|
+
content: "Cannot submit plan: this session has no workspace root, so the plan path cannot be resolved. Submit the plan once the session has a workspace, with the file inside the plans directory your instructions name.",
|
|
53
|
+
isError: true
|
|
54
|
+
};
|
|
55
|
+
const planOptions = {
|
|
56
|
+
factoryProjectId: state?.factoryProjectId,
|
|
57
|
+
plansDir: options.plansDir
|
|
58
|
+
};
|
|
59
|
+
const plansDir = getLocalPlansRelativeDir(planOptions);
|
|
60
|
+
const plansDirAbs = getLocalPlansDir(projectPath, planOptions);
|
|
61
|
+
const guidance = plansDirGuidance(plansDir, plansDirAbs);
|
|
62
|
+
if (!isPlanFilePath(projectPath, submittedPath, planOptions)) return {
|
|
63
|
+
content: planPathError(`"${submittedPath}" resolves to "${resolvePlanPath(projectPath, submittedPath) ?? submittedPath}", which is not a markdown file directly inside the plans directory "${plansDirAbs}".`, `${guidance} The plans directory is relative to the workspace root ("${projectPath}"), so it must not be prefixed with a repository directory name.`),
|
|
64
|
+
isError: true
|
|
65
|
+
};
|
|
66
|
+
const resolvedPath = resolvePlanPath(projectPath, submittedPath);
|
|
67
|
+
const relativePath = path$1.relative(projectPath, resolvedPath);
|
|
68
|
+
const readPath = relativePath && !relativePath.startsWith("..") && !path$1.isAbsolute(relativePath) ? relativePath : resolvedPath;
|
|
69
|
+
const filesystem = agentControllerCtx?.workspace?.filesystem ?? context?.workspace?.filesystem;
|
|
70
|
+
if (!filesystem) return {
|
|
71
|
+
content: planPathError(`the session workspace filesystem is not available, so "${resolvedPath}" could not be read.`, guidance),
|
|
72
|
+
isError: true
|
|
73
|
+
};
|
|
74
|
+
let raw;
|
|
75
|
+
try {
|
|
76
|
+
const content = await filesystem.readFile(readPath, { encoding: "utf-8" });
|
|
77
|
+
raw = typeof content === "string" ? content : content.toString("utf-8");
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
content: planPathError(`"${resolvedPath}" could not be read (${error instanceof Error ? error.message : "unknown error"}).`, `${guidance} Write the plan file first, then submit its path.`),
|
|
81
|
+
isError: true
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
const parsed = parsePlanContent(raw);
|
|
85
|
+
if (parsed.plan.trim().length === 0) return {
|
|
86
|
+
content: planPathError(`"${resolvedPath}" is empty, so there is nothing to review.`, guidance),
|
|
87
|
+
isError: true
|
|
88
|
+
};
|
|
89
|
+
await suspend({
|
|
90
|
+
toolId: SUBMIT_PLAN_TOOL_ID,
|
|
91
|
+
path: submittedPath,
|
|
92
|
+
title: parsed.title,
|
|
93
|
+
plan: parsed.plan
|
|
94
|
+
});
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return {
|
|
97
|
+
content: `Failed to submit plan: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
98
|
+
isError: true
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
export { SUBMIT_PLAN_TOOL_ID, createSubmitPlanTool };
|
package/dist/utils/plans.d.ts
CHANGED
|
@@ -34,6 +34,17 @@ export declare function savePlanToDisk(opts: {
|
|
|
34
34
|
resourceId: string;
|
|
35
35
|
plansDir?: string;
|
|
36
36
|
}): Promise<void>;
|
|
37
|
+
/**
|
|
38
|
+
* Split plan markdown into its title and body.
|
|
39
|
+
*
|
|
40
|
+
* The leading `# <title>` heading (if present) is the title and the remaining content is
|
|
41
|
+
* the plan body. Used both when reading a plan from local disk and when a host reads one
|
|
42
|
+
* through a session workspace filesystem.
|
|
43
|
+
*/
|
|
44
|
+
export declare function parsePlanContent(raw: string): {
|
|
45
|
+
title: string;
|
|
46
|
+
plan: string;
|
|
47
|
+
};
|
|
37
48
|
/**
|
|
38
49
|
* Read a plan markdown file by absolute path.
|
|
39
50
|
*
|
|
@@ -49,13 +60,20 @@ export declare function readPlanFile(absPath: string): Promise<{
|
|
|
49
60
|
* archive so approved plans are findable later. The local named plan file is left in
|
|
50
61
|
* place so the user can review every plan made over time.
|
|
51
62
|
*
|
|
63
|
+
* Pass `plan` — the text the user actually reviewed — whenever the caller has it.
|
|
64
|
+
* The file can be edited, moved or removed while the approval card is open, so
|
|
65
|
+
* re-reading it can archive something the user never approved. Reading the file
|
|
66
|
+
* stays as the fallback for callers with no reviewed text.
|
|
67
|
+
*
|
|
52
68
|
* Returns the local plan filename (e.g. `add-dark-mode.md`), or `undefined` when there
|
|
53
|
-
* was no plan
|
|
69
|
+
* was no plan to approve.
|
|
54
70
|
*/
|
|
55
71
|
export declare function approvePlanFile(opts: {
|
|
56
72
|
planPath: string;
|
|
57
73
|
title: string;
|
|
58
74
|
resourceId: string;
|
|
59
75
|
plansDir?: string;
|
|
76
|
+
/** The reviewed plan text. Preferred over re-reading the file at `planPath`. */
|
|
77
|
+
plan?: string;
|
|
60
78
|
}): Promise<string | undefined>;
|
|
61
79
|
//# sourceMappingURL=plans.d.ts.map
|
package/dist/utils/plans.js
CHANGED
|
@@ -73,18 +73,13 @@ async function savePlanToDisk(opts) {
|
|
|
73
73
|
await fs.writeFile(path.join(dir, filename), content, "utf-8");
|
|
74
74
|
}
|
|
75
75
|
/**
|
|
76
|
-
*
|
|
76
|
+
* Split plan markdown into its title and body.
|
|
77
77
|
*
|
|
78
|
-
* The leading `# <title>` heading (if present) is
|
|
79
|
-
*
|
|
78
|
+
* The leading `# <title>` heading (if present) is the title and the remaining content is
|
|
79
|
+
* the plan body. Used both when reading a plan from local disk and when a host reads one
|
|
80
|
+
* through a session workspace filesystem.
|
|
80
81
|
*/
|
|
81
|
-
|
|
82
|
-
let raw;
|
|
83
|
-
try {
|
|
84
|
-
raw = await fs.readFile(absPath, "utf-8");
|
|
85
|
-
} catch {
|
|
86
|
-
return;
|
|
87
|
-
}
|
|
82
|
+
function parsePlanContent(raw) {
|
|
88
83
|
const lines = raw.split(/\r?\n/);
|
|
89
84
|
const headingIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
90
85
|
const heading = headingIndex >= 0 ? lines[headingIndex] : void 0;
|
|
@@ -98,23 +93,45 @@ async function readPlanFile(absPath) {
|
|
|
98
93
|
};
|
|
99
94
|
}
|
|
100
95
|
/**
|
|
96
|
+
* Read a plan markdown file by absolute path.
|
|
97
|
+
*
|
|
98
|
+
* The leading `# <title>` heading (if present) is parsed as the title and the remaining
|
|
99
|
+
* content is returned as the plan body. Returns `undefined` when the file does not exist.
|
|
100
|
+
*/
|
|
101
|
+
async function readPlanFile(absPath) {
|
|
102
|
+
let raw;
|
|
103
|
+
try {
|
|
104
|
+
raw = await fs.readFile(absPath, "utf-8");
|
|
105
|
+
} catch {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
return parsePlanContent(raw);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
101
111
|
* Approve the plan file at `planPath`: write a timestamped copy to the global plans
|
|
102
112
|
* archive so approved plans are findable later. The local named plan file is left in
|
|
103
113
|
* place so the user can review every plan made over time.
|
|
104
114
|
*
|
|
115
|
+
* Pass `plan` — the text the user actually reviewed — whenever the caller has it.
|
|
116
|
+
* The file can be edited, moved or removed while the approval card is open, so
|
|
117
|
+
* re-reading it can archive something the user never approved. Reading the file
|
|
118
|
+
* stays as the fallback for callers with no reviewed text.
|
|
119
|
+
*
|
|
105
120
|
* Returns the local plan filename (e.g. `add-dark-mode.md`), or `undefined` when there
|
|
106
|
-
* was no plan
|
|
121
|
+
* was no plan to approve.
|
|
107
122
|
*/
|
|
108
123
|
async function approvePlanFile(opts) {
|
|
109
|
-
const { planPath, title, resourceId, plansDir } = opts;
|
|
110
|
-
const
|
|
111
|
-
|
|
124
|
+
const { planPath, title, resourceId, plansDir, plan } = opts;
|
|
125
|
+
const reviewed = plan?.trim() ? plan : void 0;
|
|
126
|
+
const current = reviewed ? void 0 : await readPlanFile(planPath);
|
|
127
|
+
const approvedPlan = reviewed ?? current?.plan;
|
|
128
|
+
if (approvedPlan === void 0) return;
|
|
112
129
|
await savePlanToDisk({
|
|
113
|
-
title: title || current
|
|
114
|
-
plan:
|
|
130
|
+
title: title || current?.title || "Implementation Plan",
|
|
131
|
+
plan: approvedPlan,
|
|
115
132
|
resourceId,
|
|
116
133
|
plansDir
|
|
117
134
|
});
|
|
118
135
|
return path.basename(planPath);
|
|
119
136
|
}
|
|
120
|
-
export { approvePlanFile, getLocalPlansDir, getLocalPlansRelativeDir, getPlanFilename, getPlansDir, getSuggestedPlanRelativePath, isPlanFilePath, readPlanFile, resolvePlanPath, savePlanToDisk };
|
|
137
|
+
export { approvePlanFile, getLocalPlansDir, getLocalPlansRelativeDir, getPlanFilename, getPlansDir, getSuggestedPlanRelativePath, isPlanFilePath, parsePlanContent, readPlanFile, resolvePlanPath, savePlanToDisk };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.21.0-alpha.
|
|
3
|
+
"version": "1.21.0-alpha.9",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -65,16 +65,16 @@
|
|
|
65
65
|
"yaml": "^2.9.1",
|
|
66
66
|
"zod": "^4.6.7",
|
|
67
67
|
"@mastra/agent-browser": "0.7.0-alpha.1",
|
|
68
|
-
"@mastra/client-js": "1.
|
|
68
|
+
"@mastra/client-js": "1.62.0-alpha.8",
|
|
69
69
|
"@mastra/duckdb": "1.19.2-alpha.0",
|
|
70
70
|
"@mastra/fastembed": "1.4.0-alpha.1",
|
|
71
71
|
"@mastra/github-signals": "0.5.4-alpha.0",
|
|
72
|
-
"@mastra/libsql": "1.32.0-alpha.
|
|
72
|
+
"@mastra/libsql": "1.32.0-alpha.2",
|
|
73
73
|
"@mastra/mcp": "2.11.0-alpha.1",
|
|
74
|
-
"@mastra/memory": "1.41.3-alpha.
|
|
74
|
+
"@mastra/memory": "1.41.3-alpha.4",
|
|
75
75
|
"@mastra/observability": "1.24.3-alpha.1",
|
|
76
76
|
"@mastra/parallel": "0.1.6-alpha.0",
|
|
77
|
-
"@mastra/pg": "1.
|
|
77
|
+
"@mastra/pg": "1.38.0-alpha.3",
|
|
78
78
|
"@mastra/schema-compat": "1.4.1-alpha.0",
|
|
79
79
|
"@mastra/stagehand": "0.4.1-alpha.0",
|
|
80
80
|
"@mastra/tavily": "1.1.4-alpha.0",
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
"@internal/lint": "0.0.151",
|
|
96
96
|
"@internal/types-builder": "0.0.126",
|
|
97
97
|
"@internal/workspace-test-utils": "0.0.95",
|
|
98
|
-
"@mastra/core": "1.86.0-alpha.
|
|
98
|
+
"@mastra/core": "1.86.0-alpha.8"
|
|
99
99
|
},
|
|
100
100
|
"peerDependencies": {
|
|
101
101
|
"@mastra/core": ">=1.86.0-0 <2.0.0-0"
|