@mastra/code-sdk 1.21.0 → 1.22.0-alpha.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.
- package/dist/agents/model.d.ts +23 -21
- package/dist/agents/model.js +97 -18
- package/dist/auth/account-rotation-processor.d.ts +19 -53
- package/dist/auth/account-rotation-processor.js +28 -69
- package/dist/auth/index.js +2 -1
- package/dist/headless/run-mc.js +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -7
- package/dist/model-fallback.d.ts +75 -0
- package/dist/model-fallback.js +48 -0
- package/dist/processors/route-aware-stream-error-retry.d.ts +6 -0
- package/dist/processors/route-aware-stream-error-retry.js +15 -0
- package/dist/restricted.d.ts +115 -0
- package/dist/restricted.js +257 -0
- package/dist/schema.d.ts +5 -8
- package/dist/schema.js +2 -8
- package/package.json +10 -10
package/dist/agents/model.d.ts
CHANGED
|
@@ -4,7 +4,10 @@ import type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInt
|
|
|
4
4
|
import { RequestContext } from '@mastra/core/request-context';
|
|
5
5
|
import type { RequestContextReader } from '../auth/account-routing-context.js';
|
|
6
6
|
import type { CredentialStore } from '../auth/types.js';
|
|
7
|
+
import { MODEL_FALLBACK_STATE_KEY } from '../model-fallback.js';
|
|
8
|
+
import type { ModelFallback } from '../model-fallback.js';
|
|
7
9
|
import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
|
|
10
|
+
import type { ModelRouteEntry } from '../schema.js';
|
|
8
11
|
import type { ThinkingLevelSetting } from '../thinking.js';
|
|
9
12
|
import { MastraCodeGateway } from './mastracode-gateway.js';
|
|
10
13
|
import type { MastraCodeGatewayOptions } from './mastracode-gateway.js';
|
|
@@ -95,6 +98,22 @@ export interface ThinkingRequestContext {
|
|
|
95
98
|
* (rule-driven) Factory runs that nobody ever opens interactively.
|
|
96
99
|
*/
|
|
97
100
|
export declare function resolveRequestThinkingLevel(agentControllerContext: ThinkingRequestContext | undefined, settingsPath?: string, hostDefault?: ThinkingLevelSetting): ThinkingLevelSetting;
|
|
101
|
+
export declare function setHostModelRoute(requestContext: RequestContext, route: readonly ModelFallback[] | undefined): void;
|
|
102
|
+
export declare function advanceHostModelRoute(requestContext: RequestContext): void;
|
|
103
|
+
export declare function requestRouteHasNextModel(requestContext: RequestContextReader | undefined, controller: Parameters<typeof requestModelRoute>[1]): boolean;
|
|
104
|
+
interface RequestModelRoute {
|
|
105
|
+
entries: ModelRouteEntry[];
|
|
106
|
+
host: boolean;
|
|
107
|
+
modelId: string | undefined;
|
|
108
|
+
thinkingLevel: ThinkingLevelSetting | undefined;
|
|
109
|
+
}
|
|
110
|
+
export declare function requestModelRoute(requestContext: RequestContextReader | undefined, controller: {
|
|
111
|
+
getState?: () => Record<string, unknown> | undefined;
|
|
112
|
+
threadId?: unknown;
|
|
113
|
+
session?: {
|
|
114
|
+
modelId?: unknown;
|
|
115
|
+
};
|
|
116
|
+
} | undefined): RequestModelRoute;
|
|
98
117
|
/**
|
|
99
118
|
* Dynamic model function that reads the current model and optional ordered
|
|
100
119
|
* fallback route from controller state. Route entry ids are opaque host-owned
|
|
@@ -107,31 +126,14 @@ export declare function getDynamicModel({ requestContext }: {
|
|
|
107
126
|
modeless?: boolean;
|
|
108
127
|
defaultThinkingLevel?: ThinkingLevelSetting;
|
|
109
128
|
}): IdentifiedModelConfig | ModelWithRetries[];
|
|
110
|
-
type MemoryRouteState = {
|
|
111
|
-
modelRoute?: {
|
|
112
|
-
entries?: Array<{
|
|
113
|
-
id?: unknown;
|
|
114
|
-
memoryModelId?: unknown;
|
|
115
|
-
}>;
|
|
116
|
-
};
|
|
117
|
-
mastracodePendingModelFallback?: {
|
|
118
|
-
toEntryId?: unknown;
|
|
119
|
-
threadId?: unknown;
|
|
120
|
-
} | null;
|
|
121
|
-
};
|
|
122
129
|
/**
|
|
123
130
|
* The active model route for memory: the session route, starting at a pending
|
|
124
131
|
* fallback hop captured for this thread.
|
|
125
132
|
*/
|
|
126
|
-
export declare function getActiveMemoryRoute
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
130
|
-
modelRoute?: {
|
|
131
|
-
entries?: TEntry[];
|
|
132
|
-
};
|
|
133
|
-
mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];
|
|
134
|
-
} | undefined, threadId?: string | null): TEntry[];
|
|
133
|
+
export declare function getActiveMemoryRoute(state: {
|
|
134
|
+
modelRoute?: unknown;
|
|
135
|
+
[MODEL_FALLBACK_STATE_KEY]?: unknown;
|
|
136
|
+
} | undefined, threadId?: string | null): ModelRouteEntry[];
|
|
135
137
|
/**
|
|
136
138
|
* The memory model the active route applies to both OM roles: `'auto'`, the
|
|
137
139
|
* first concrete memory model, or `undefined` when the route sets none (both
|
package/dist/agents/model.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getRequestAccountSelection, isRequestAccountRoutingExhausted } from "../auth/account-routing-context.js";
|
|
2
2
|
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
3
3
|
import "../constants.js";
|
|
4
|
+
import { MODEL_FALLBACK_STATE_KEY, parsePendingModelFallback } from "../model-fallback.js";
|
|
4
5
|
import { toMemoryModelId } from "../onboarding/packs.js";
|
|
5
6
|
import { getCustomProviderId, loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
|
|
6
7
|
import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
|
|
@@ -279,6 +280,87 @@ function resolveRequestThinkingLevel(agentControllerContext, settingsPath, hostD
|
|
|
279
280
|
const modeId = agentControllerContext?.session?.modeId;
|
|
280
281
|
return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;
|
|
281
282
|
}
|
|
283
|
+
const HOST_MODEL_ROUTE_CONTEXT_KEY = "mastracodeHostModelRoute";
|
|
284
|
+
const HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY = "mastracodeHostModelRoutePosition";
|
|
285
|
+
function setHostModelRoute(requestContext, route) {
|
|
286
|
+
requestContext.delete(HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY);
|
|
287
|
+
if (!route) {
|
|
288
|
+
requestContext.delete(HOST_MODEL_ROUTE_CONTEXT_KEY);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const [primary, ...fallbacks] = route;
|
|
292
|
+
const entries = primary ? [primary, ...modelFallbacksToTry(primary.modelId, fallbacks, requestContext)] : [];
|
|
293
|
+
requestContext.set(HOST_MODEL_ROUTE_CONTEXT_KEY, entries.map(hostRouteEntry));
|
|
294
|
+
}
|
|
295
|
+
function advanceHostModelRoute(requestContext) {
|
|
296
|
+
requestContext.set(HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY, hostModelRoutePosition(requestContext) + 1);
|
|
297
|
+
}
|
|
298
|
+
function hostModelRoutePosition(requestContext) {
|
|
299
|
+
const position = requestContext?.get(HOST_MODEL_ROUTE_POSITION_CONTEXT_KEY);
|
|
300
|
+
return typeof position === "number" ? position : 0;
|
|
301
|
+
}
|
|
302
|
+
function requestRouteHasNextModel(requestContext, controller) {
|
|
303
|
+
const route = requestModelRoute(requestContext, controller);
|
|
304
|
+
const position = route.host ? hostModelRoutePosition(requestContext) : 0;
|
|
305
|
+
return route.entries.length - 1 > position;
|
|
306
|
+
}
|
|
307
|
+
function modelFallbacksToTry(primaryModelId, fallbacks, requestContext) {
|
|
308
|
+
const usable = [];
|
|
309
|
+
const seen = /* @__PURE__ */ new Set([primaryModelId]);
|
|
310
|
+
for (const fallback of fallbacks) {
|
|
311
|
+
if (seen.has(fallback.modelId)) continue;
|
|
312
|
+
seen.add(fallback.modelId);
|
|
313
|
+
if (canAuthenticateModel(fallback.modelId, requestContext)) usable.push(fallback);
|
|
314
|
+
}
|
|
315
|
+
return usable;
|
|
316
|
+
}
|
|
317
|
+
function hostRouteEntry({ modelId, thinkingLevel }) {
|
|
318
|
+
return {
|
|
319
|
+
id: modelId,
|
|
320
|
+
label: modelId,
|
|
321
|
+
modelId,
|
|
322
|
+
...thinkingLevel ? { thinkingLevel } : {}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
function requestModelRoute(requestContext, controller) {
|
|
326
|
+
const sessionModelId = typeof controller?.session?.modelId === "string" ? controller.session.modelId : void 0;
|
|
327
|
+
const hostRoute = requestContext?.get(HOST_MODEL_ROUTE_CONTEXT_KEY);
|
|
328
|
+
if (hostRoute) return {
|
|
329
|
+
entries: hostRoute,
|
|
330
|
+
host: true,
|
|
331
|
+
modelId: hostRoute[0]?.modelId ?? sessionModelId,
|
|
332
|
+
thinkingLevel: hostRoute[0]?.thinkingLevel
|
|
333
|
+
};
|
|
334
|
+
const { entries, pending, pendingIndex } = sessionModelRoute(controller?.getState?.(), controller?.threadId);
|
|
335
|
+
const modelId = pending?.toModelId ?? sessionModelId;
|
|
336
|
+
const startIndex = pending ? pendingIndex : findRouteModelIndex(entries, modelId);
|
|
337
|
+
const active = startIndex < 0 ? [] : entries.slice(startIndex);
|
|
338
|
+
return {
|
|
339
|
+
entries: findRouteModelIndex(active, modelId) === 0 ? active : [],
|
|
340
|
+
host: false,
|
|
341
|
+
modelId,
|
|
342
|
+
thinkingLevel: void 0
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
function sessionModelRoute(state, threadId) {
|
|
346
|
+
const route = (state?.modelRoute)?.entries;
|
|
347
|
+
const entries = Array.isArray(route) ? route.slice(0, 32) : [];
|
|
348
|
+
const pending = parsePendingModelFallback(state?.[MODEL_FALLBACK_STATE_KEY]);
|
|
349
|
+
const threadPending = pending && (pending.threadId === void 0 || pending.threadId === threadId) ? pending : null;
|
|
350
|
+
return {
|
|
351
|
+
entries,
|
|
352
|
+
pending: threadPending,
|
|
353
|
+
pendingIndex: threadPending ? entries.findIndex((entry) => entry.id === threadPending.toEntryId) : -1
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
function canAuthenticateModel(modelId, requestContext) {
|
|
357
|
+
try {
|
|
358
|
+
resolveModelForRequest(modelId, { requestContext });
|
|
359
|
+
return true;
|
|
360
|
+
} catch {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
282
364
|
/**
|
|
283
365
|
* Dynamic model function that reads the current model and optional ordered
|
|
284
366
|
* fallback route from controller state. Route entry ids are opaque host-owned
|
|
@@ -287,25 +369,22 @@ function resolveRequestThinkingLevel(agentControllerContext, settingsPath, hostD
|
|
|
287
369
|
*/
|
|
288
370
|
function getDynamicModel({ requestContext }, settingsPath, { modeless = false, defaultThinkingLevel } = {}) {
|
|
289
371
|
const controller = requestContext.get("controller");
|
|
290
|
-
const
|
|
291
|
-
const pendingState = state?.mastracodePendingModelFallback;
|
|
292
|
-
const pendingFallback = pendingState && (pendingState.threadId === void 0 || typeof pendingState.threadId === "string" && pendingState.threadId === controller?.threadId) ? pendingState : void 0;
|
|
293
|
-
const modelId = (pendingFallback && typeof pendingFallback.toModelId === "string" && pendingFallback.toModelId.length > 0 ? pendingFallback.toModelId : void 0) ?? controller?.session?.modelId;
|
|
372
|
+
const { entries: activeRoute, modelId, thinkingLevel: primaryThinkingLevel } = requestModelRoute(requestContext, controller);
|
|
294
373
|
if (!modelId) {
|
|
295
374
|
if (!controller) throw new Error("No model available: this run started without a controller session context, so no model selection could be resolved.");
|
|
296
375
|
throw new Error("No model selected. Use /models to select a model first.");
|
|
297
376
|
}
|
|
377
|
+
const thinkingLevel = resolveRequestThinkingLevel(modeless ? { state: controller?.state } : controller, settingsPath, defaultThinkingLevel);
|
|
298
378
|
const resolveOptions = {
|
|
299
|
-
thinkingLevel
|
|
379
|
+
thinkingLevel,
|
|
300
380
|
remapForCodexOAuth: true,
|
|
301
381
|
requestContext
|
|
302
382
|
};
|
|
303
|
-
const primary = identifyModel(modelId, resolveModel(modelId,
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
if (!activeRoute || activeRoute.length < 2 || findRouteModelIndex(activeRoute, modelId) !== 0) return primary;
|
|
383
|
+
const primary = identifyModel(modelId, resolveModel(modelId, {
|
|
384
|
+
...resolveOptions,
|
|
385
|
+
thinkingLevel: primaryThinkingLevel ?? thinkingLevel
|
|
386
|
+
}));
|
|
387
|
+
if (activeRoute.length < 2) return primary;
|
|
309
388
|
const firstId = typeof activeRoute[0]?.id === "string" && activeRoute[0].id.length > 0 ? activeRoute[0].id : void 0;
|
|
310
389
|
if (!firstId) return primary;
|
|
311
390
|
const entries = [{
|
|
@@ -317,7 +396,10 @@ function getDynamicModel({ requestContext }, settingsPath, { modeless = false, d
|
|
|
317
396
|
if (typeof routeEntry.id !== "string" || routeEntry.id.length === 0 || typeof routeEntry.modelId !== "string" || routeEntry.modelId.length === 0) break;
|
|
318
397
|
let entryModel;
|
|
319
398
|
try {
|
|
320
|
-
entryModel = resolveModel(routeEntry.modelId,
|
|
399
|
+
entryModel = resolveModel(routeEntry.modelId, {
|
|
400
|
+
...resolveOptions,
|
|
401
|
+
thinkingLevel: routeEntry.thinkingLevel ?? thinkingLevel
|
|
402
|
+
});
|
|
321
403
|
} catch {
|
|
322
404
|
break;
|
|
323
405
|
}
|
|
@@ -341,11 +423,8 @@ function identifyModel(modelId, model) {
|
|
|
341
423
|
* fallback hop captured for this thread.
|
|
342
424
|
*/
|
|
343
425
|
function getActiveMemoryRoute(state, threadId) {
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
const routeEntries = state?.modelRoute?.entries?.slice(0, 32) ?? [];
|
|
347
|
-
const pendingIndex = sameThreadPending ? routeEntries.findIndex((entry) => entry.id === sameThreadPending.toEntryId) : -1;
|
|
348
|
-
return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;
|
|
426
|
+
const { entries, pendingIndex } = sessionModelRoute(state, threadId);
|
|
427
|
+
return pendingIndex >= 0 ? entries.slice(pendingIndex) : entries;
|
|
349
428
|
}
|
|
350
429
|
/**
|
|
351
430
|
* The memory model the active route applies to both OM roles: `'auto'`, the
|
|
@@ -379,4 +458,4 @@ function getGoalJudgeModel({ requestContext }, settingsPath) {
|
|
|
379
458
|
requestContext
|
|
380
459
|
});
|
|
381
460
|
}
|
|
382
|
-
export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, canUseProvider, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getActiveMemoryRoute, getActiveRouteMemoryModelId, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, prepareProviderWebSearchRoute, remapOpenAIModelForCodexOAuth, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveProviderWebSearchRoute, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource };
|
|
461
|
+
export { MASTRACODE_GATEWAY_ID, MastraCodeGateway, advanceHostModelRoute, canUseProvider, createMastraCodeGateway, createMastraCodeModelCatalogProvider, createRequestScopedCredentialStore, getActiveMemoryRoute, getActiveRouteMemoryModelId, getAnthropicApiKey, getDynamicModel, getGoalJudgeModel, getOpenAIApiKey, hasCredentialStoreProvider, hasCustomProvidersSource, prepareProviderWebSearchRoute, remapOpenAIModelForCodexOAuth, requestModelRoute, requestRouteHasNextModel, resolveAuth, resolveCustomProviders, resolveModel, resolveModelId, resolveProviderWebSearchRoute, resolveRequestThinkingLevel, resolveTenantFromRequestContext, setCredentialStoreProvider, setCustomProvidersSource, setHostModelRoute };
|
|
@@ -1,7 +1,22 @@
|
|
|
1
|
-
import type { ProcessAPIErrorArgs, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';
|
|
1
|
+
import type { ProcessAPIErrorArgs, ProcessAPIErrorResult, ProcessInputArgs, ProcessInputResult, Processor } from '@mastra/core/processors';
|
|
2
2
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
3
|
+
import type { ModelFallbackReason } from '../model-fallback.js';
|
|
3
4
|
import type { ThinkingLevelSetting } from '../thinking.js';
|
|
4
5
|
import type { CredentialStore } from './types.js';
|
|
6
|
+
export {
|
|
7
|
+
/** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
|
|
8
|
+
MODEL_FALLBACK_PART_TYPE,
|
|
9
|
+
/** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
|
|
10
|
+
MODEL_FALLBACK_STATE_KEY,
|
|
11
|
+
/** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
|
|
12
|
+
modelFallbackNoticeText, } from '../model-fallback.js';
|
|
13
|
+
export type {
|
|
14
|
+
/** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
|
|
15
|
+
ModelFallbackPartData,
|
|
16
|
+
/** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
|
|
17
|
+
PendingModelFallback, } from '../model-fallback.js';
|
|
18
|
+
/** @deprecated Parse the whole part with `parseModelFallbackPart` from `@mastra/code-sdk/model-fallback`. */
|
|
19
|
+
export declare function isModelFallbackReason(value: unknown): value is ModelFallbackReason;
|
|
5
20
|
export declare const ACCOUNT_SWITCH_PART_TYPE = "data-mastracode-account-switch";
|
|
6
21
|
/** Labels and instance ids only — never token material (do-not list). */
|
|
7
22
|
export interface AccountSwitchPartData {
|
|
@@ -14,7 +29,7 @@ export interface AccountSwitchPartData {
|
|
|
14
29
|
id: string;
|
|
15
30
|
label: string;
|
|
16
31
|
} | null;
|
|
17
|
-
reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' |
|
|
32
|
+
reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed' | ModelFallbackReason | 'preferred-routing';
|
|
18
33
|
at: string;
|
|
19
34
|
/**
|
|
20
35
|
* Set on a `to: null` part when a route pinned to a single account reported
|
|
@@ -34,32 +49,6 @@ export type RotationCredentialStore = CredentialStore & {
|
|
|
34
49
|
*/
|
|
35
50
|
forceRefreshActiveAccount?(providerId: string, accountInstanceId?: string): Promise<string | undefined>;
|
|
36
51
|
};
|
|
37
|
-
/** Persisted data-part type for a model-route hop. */
|
|
38
|
-
export declare const MODEL_FALLBACK_PART_TYPE: 'data-mastracode-model-fallback';
|
|
39
|
-
/** Non-secret transcript payload for a model-route hop. */
|
|
40
|
-
export interface ModelFallbackPartData {
|
|
41
|
-
from: {
|
|
42
|
-
entryId: string;
|
|
43
|
-
label: string;
|
|
44
|
-
};
|
|
45
|
-
to: {
|
|
46
|
-
entryId: string;
|
|
47
|
-
label: string;
|
|
48
|
-
};
|
|
49
|
-
reason: 'pool-exhausted' | 'persistent-outage';
|
|
50
|
-
at: string;
|
|
51
|
-
}
|
|
52
|
-
/** Session-state key set when account rotation advances the model route. */
|
|
53
|
-
export declare const MODEL_FALLBACK_STATE_KEY: 'mastracodePendingModelFallback';
|
|
54
|
-
/** Payload written to session state under MODEL_FALLBACK_STATE_KEY. */
|
|
55
|
-
export interface PendingModelFallback {
|
|
56
|
-
fromEntryId: string;
|
|
57
|
-
toEntryId: string;
|
|
58
|
-
toModelId: string;
|
|
59
|
-
threadId?: string;
|
|
60
|
-
reason: 'pool-exhausted' | 'persistent-outage';
|
|
61
|
-
at: string;
|
|
62
|
-
}
|
|
63
52
|
export type RotationClassification = {
|
|
64
53
|
kind: 'rotate';
|
|
65
54
|
reason: 'rate-limit' | 'quota-exhausted' | 'auth-failed';
|
|
@@ -119,16 +108,6 @@ export declare function isAccountSwitchReason(value: unknown): value is AccountS
|
|
|
119
108
|
* history rendering of the persisted part — one formatter, identical text.
|
|
120
109
|
*/
|
|
121
110
|
export declare function accountSwitchNoticeText(data: AccountSwitchPartData): string;
|
|
122
|
-
/** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
|
|
123
|
-
export declare function modelFallbackNoticeText(data: ModelFallbackPartData): string;
|
|
124
|
-
/**
|
|
125
|
-
* Whether a persisted model-fallback reason is one this build understands.
|
|
126
|
-
* `REASON_TEXT` also covers the account-switch reasons, so the notice text
|
|
127
|
-
* alone would happily render a foreign value such as `rate-limit` as a
|
|
128
|
-
* model-fallback reason; history parsed from another build's part must be
|
|
129
|
-
* rejected instead.
|
|
130
|
-
*/
|
|
131
|
-
export declare function isModelFallbackReason(value: unknown): value is ModelFallbackPartData['reason'];
|
|
132
111
|
export type RoutingControllerContext = {
|
|
133
112
|
session?: {
|
|
134
113
|
modelId?: unknown;
|
|
@@ -158,27 +137,14 @@ export declare class AccountRotationProcessor implements Processor {
|
|
|
158
137
|
requestContext: RequestContext;
|
|
159
138
|
}) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>;
|
|
160
139
|
});
|
|
161
|
-
processAPIError(args: ProcessAPIErrorArgs): Promise<
|
|
162
|
-
retry: boolean;
|
|
163
|
-
}>;
|
|
140
|
+
processAPIError(args: ProcessAPIErrorArgs): Promise<ProcessAPIErrorResult>;
|
|
164
141
|
/**
|
|
165
142
|
* Resolve the request's host-supplied model route once and cache the reachable
|
|
166
143
|
* prefix in processor state. Resolution mirrors getDynamicModel so a hop is
|
|
167
144
|
* never announced for an entry core cannot reach.
|
|
168
145
|
*/
|
|
169
146
|
private getModelRouteCascade;
|
|
170
|
-
|
|
171
|
-
* Q14 gate: 400/unknown/unattributable errors never advance routes. Core's
|
|
172
|
-
* fallback array advances on ANY thrown error except TripWire
|
|
173
|
-
* (llm-execution-step.ts), so when the session route has another entry and the
|
|
174
|
-
* current entry is non-last, a bare `retry: false` would silently hop on an
|
|
175
|
-
* error class the user excluded from hop triggers. TripWire is the only
|
|
176
|
-
* no-advance escape: the runner rethrows it and the fallback loop declines
|
|
177
|
-
* to advance. No chain (or already on the last entry) → return and let the
|
|
178
|
-
* plain `retry: false` surface the error exactly as before.
|
|
179
|
-
*/
|
|
180
|
-
private gateChainHop;
|
|
181
|
-
/** Announce and persist the next model-route hop before core advances. */
|
|
147
|
+
private hopToNextModel;
|
|
182
148
|
private emitModelFallbackPart;
|
|
183
149
|
/**
|
|
184
150
|
* Pool done for this request: every instance recorded in the tried-set and
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { resolveCredentialStore } from "../agents/credential-resolver.js";
|
|
2
|
-
import { resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
|
|
3
|
-
import {
|
|
2
|
+
import { advanceHostModelRoute, requestModelRoute, resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
|
|
3
|
+
import { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText, pendingModelFallbackSchema } from "../model-fallback.js";
|
|
4
|
+
import { getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
|
|
4
5
|
import { isThinkingLevelSetting } from "../thinking.js";
|
|
5
6
|
import { getRequestAccountSelection, isRequestAccountRoutingExhausted, markRequestAccountRoutingExhausted, setRequestAccountSelection } from "./account-routing-context.js";
|
|
6
7
|
import { ProviderAuthRequiredError } from "./provider-auth-error.js";
|
|
7
8
|
import { getOAuthProviders } from "./storage.js";
|
|
8
|
-
import { TripWire } from "@mastra/core/agent";
|
|
9
9
|
import { classifyProviderError } from "@mastra/core/error";
|
|
10
10
|
// src/auth/account-rotation-processor.ts
|
|
11
11
|
/**
|
|
@@ -29,6 +29,10 @@ import { classifyProviderError } from "@mastra/core/error";
|
|
|
29
29
|
* `StreamErrorRetryProcessor`; `AccountStartNoticeProcessor` implements
|
|
30
30
|
* `processInput` only and is registered in `inputProcessors`.
|
|
31
31
|
*/
|
|
32
|
+
/** @deprecated Parse the whole part with `parseModelFallbackPart` from `@mastra/code-sdk/model-fallback`. */
|
|
33
|
+
function isModelFallbackReason(value) {
|
|
34
|
+
return pendingModelFallbackSchema.shape.reason.safeParse(value).success;
|
|
35
|
+
}
|
|
32
36
|
const ACCOUNT_SWITCH_PART_TYPE = "data-mastracode-account-switch";
|
|
33
37
|
/** Rotatable providers = the OAuth provider registry; API-key-only providers never rotate. */
|
|
34
38
|
const KNOWN_PROVIDER_IDS = new Set(getOAuthProviders().map((provider) => provider.id));
|
|
@@ -54,10 +58,6 @@ const NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
|
54
58
|
]);
|
|
55
59
|
const NETWORK_MESSAGE_PATTERN = /fetch failed|network error|socket hang up|getaddrinfo|econnrefused|enotfound|etimedout|connection (?:refused|reset|closed|timed out)|other side closed|write epipe/i;
|
|
56
60
|
const MAX_CAUSE_DEPTH = 4;
|
|
57
|
-
/** Persisted data-part type for a model-route hop. */
|
|
58
|
-
const MODEL_FALLBACK_PART_TYPE = "data-mastracode-model-fallback";
|
|
59
|
-
/** Session-state key set when account rotation advances the model route. */
|
|
60
|
-
const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
|
|
61
61
|
/**
|
|
62
62
|
* Same-account retries for a stream the provider cut after accepting the
|
|
63
63
|
* request. Each one can cost a full stream (900 s on the ChatGPT Codex route),
|
|
@@ -276,21 +276,6 @@ function accountSwitchNoticeText(data) {
|
|
|
276
276
|
}
|
|
277
277
|
return `Switched ${provider} account: ${data.from?.label ?? "unknown"} → ${data.to.label} (${reason})`;
|
|
278
278
|
}
|
|
279
|
-
/** Transcript line for a model-route hop; shared by the live info event and the TUI's history render. */
|
|
280
|
-
function modelFallbackNoticeText(data) {
|
|
281
|
-
const reason = REASON_TEXT[data.reason] ?? data.reason;
|
|
282
|
-
return `Switched model route: ${data.from.label} → ${data.to.label} (${reason})`;
|
|
283
|
-
}
|
|
284
|
-
/**
|
|
285
|
-
* Whether a persisted model-fallback reason is one this build understands.
|
|
286
|
-
* `REASON_TEXT` also covers the account-switch reasons, so the notice text
|
|
287
|
-
* alone would happily render a foreign value such as `rate-limit` as a
|
|
288
|
-
* model-fallback reason; history parsed from another build's part must be
|
|
289
|
-
* rejected instead.
|
|
290
|
-
*/
|
|
291
|
-
function isModelFallbackReason(value) {
|
|
292
|
-
return value === "pool-exhausted" || value === "persistent-outage";
|
|
293
|
-
}
|
|
294
279
|
async function emitAccountSwitchPart(args, data) {
|
|
295
280
|
await args.writer?.custom({
|
|
296
281
|
type: ACCOUNT_SWITCH_PART_TYPE,
|
|
@@ -308,8 +293,8 @@ async function emitAccountSwitchPart(args, data) {
|
|
|
308
293
|
* before any HTTP request exists).
|
|
309
294
|
*/
|
|
310
295
|
function providerFromSession(args) {
|
|
311
|
-
const modelId = (args.requestContext
|
|
312
|
-
return
|
|
296
|
+
const { modelId } = requestModelRoute(args.requestContext, getRoutingController(args));
|
|
297
|
+
return modelId ? providerFromModelId(modelId) : void 0;
|
|
313
298
|
}
|
|
314
299
|
function getRoutingController(args) {
|
|
315
300
|
return args.requestContext?.get("controller");
|
|
@@ -325,12 +310,7 @@ function getRequestActiveAccount(args, store, providerId) {
|
|
|
325
310
|
return store.getActiveAccount?.(providerId) ?? store.listAccounts?.(providerId).find((account) => account.active);
|
|
326
311
|
}
|
|
327
312
|
function resolveAccountRoute(args, explicit) {
|
|
328
|
-
const
|
|
329
|
-
const state = controller?.getState?.();
|
|
330
|
-
const pending = state?.mastracodePendingModelFallback;
|
|
331
|
-
const pendingMatchesThread = pending && typeof pending.toEntryId === "string" && typeof pending.toModelId === "string" && (pending.threadId === void 0 || pending.threadId === controller?.threadId);
|
|
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[findRouteModelIndex(routeEntries, controller?.session?.modelId)];
|
|
313
|
+
const entry = explicit ?? requestModelRoute(args.requestContext, getRoutingController(args)).entries[0];
|
|
334
314
|
if (!entry || typeof entry.id !== "string" || typeof entry.modelId !== "string") return null;
|
|
335
315
|
const providerId = providerFromModelId(entry.modelId);
|
|
336
316
|
if (!providerId) return null;
|
|
@@ -401,22 +381,13 @@ var AccountRotationProcessor = class {
|
|
|
401
381
|
}
|
|
402
382
|
async processAPIError(args) {
|
|
403
383
|
const { error, state } = args;
|
|
404
|
-
if (args.retryCount >= this.options.maxProcessorRetries)
|
|
405
|
-
await this.gateChainHop(args, error);
|
|
406
|
-
return { retry: false };
|
|
407
|
-
}
|
|
384
|
+
if (args.retryCount >= this.options.maxProcessorRetries) return this.hopToNextModel(args);
|
|
408
385
|
const classification = classifyRotationError(error);
|
|
409
|
-
if (classification.kind === "never")
|
|
410
|
-
await this.gateChainHop(args, error);
|
|
411
|
-
return { retry: false };
|
|
412
|
-
}
|
|
386
|
+
if (classification.kind === "never") return this.hopToNextModel(args);
|
|
413
387
|
if (classification.kind === "stream-cut") {
|
|
414
388
|
const budget = state.streamCutRetries;
|
|
415
389
|
const cuts = budget?.step === args.stepNumber ? budget.count : 0;
|
|
416
|
-
if (cuts >= 2)
|
|
417
|
-
await this.gateChainHop(args, error);
|
|
418
|
-
return { retry: false };
|
|
419
|
-
}
|
|
390
|
+
if (cuts >= 2) return this.hopToNextModel(args);
|
|
420
391
|
state.streamCutRetries = {
|
|
421
392
|
step: args.stepNumber,
|
|
422
393
|
count: cuts + 1
|
|
@@ -485,10 +456,8 @@ var AccountRotationProcessor = class {
|
|
|
485
456
|
if (args.state.modelRouteCascade !== void 0) return args.state.modelRouteCascade ?? null;
|
|
486
457
|
const controller = getRoutingController(args);
|
|
487
458
|
const state = controller?.getState?.();
|
|
488
|
-
const route = (
|
|
489
|
-
|
|
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
|
-
if (!route || startIndex === void 0 || startIndex < 0 || route.length - startIndex < 2) {
|
|
459
|
+
const { entries: route } = requestModelRoute(args.requestContext, controller);
|
|
460
|
+
if (route.length < 2) {
|
|
492
461
|
args.state.modelRouteCascade = null;
|
|
493
462
|
return null;
|
|
494
463
|
}
|
|
@@ -497,7 +466,7 @@ var AccountRotationProcessor = class {
|
|
|
497
466
|
...!this.options.modeless && { session: { modeId: typeof controller?.session?.modeId === "string" ? controller.session.modeId : "build" } }
|
|
498
467
|
}, this.options.settingsPath, args.requestContext && !isThinkingLevelSetting(state?.thinkingLevel) ? await this.options.resolveDefaultThinkingLevel?.({ requestContext: args.requestContext }) : void 0);
|
|
499
468
|
const entries = [];
|
|
500
|
-
for (const entry of route
|
|
469
|
+
for (const entry of route) {
|
|
501
470
|
if (typeof entry.id !== "string" || entry.id.length === 0 || typeof entry.modelId !== "string" || entry.modelId.length === 0) break;
|
|
502
471
|
if (entries.length > 0) try {
|
|
503
472
|
resolveModel(entry.modelId, {
|
|
@@ -526,24 +495,10 @@ var AccountRotationProcessor = class {
|
|
|
526
495
|
args.state.modelRouteCascade = cascade;
|
|
527
496
|
return cascade;
|
|
528
497
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
* (llm-execution-step.ts), so when the session route has another entry and the
|
|
533
|
-
* current entry is non-last, a bare `retry: false` would silently hop on an
|
|
534
|
-
* error class the user excluded from hop triggers. TripWire is the only
|
|
535
|
-
* no-advance escape: the runner rethrows it and the fallback loop declines
|
|
536
|
-
* to advance. No chain (or already on the last entry) → return and let the
|
|
537
|
-
* plain `retry: false` surface the error exactly as before.
|
|
538
|
-
*/
|
|
539
|
-
async gateChainHop(args, error) {
|
|
540
|
-
const cascade = await this.getModelRouteCascade(args);
|
|
541
|
-
if (!cascade) return;
|
|
542
|
-
if (cascade.position >= cascade.entries.length - 1) return;
|
|
543
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
544
|
-
throw new TripWire(reason, {}, this.id);
|
|
498
|
+
async hopToNextModel(args) {
|
|
499
|
+
await this.emitModelFallbackPart(args, "pool-exhausted");
|
|
500
|
+
return { retry: false };
|
|
545
501
|
}
|
|
546
|
-
/** Announce and persist the next model-route hop before core advances. */
|
|
547
502
|
async emitModelFallbackPart(args, reason) {
|
|
548
503
|
const cascade = await this.getModelRouteCascade(args);
|
|
549
504
|
if (!cascade) return;
|
|
@@ -552,6 +507,7 @@ var AccountRotationProcessor = class {
|
|
|
552
507
|
if (!from || !to) return;
|
|
553
508
|
const controller = args.requestContext?.get("controller");
|
|
554
509
|
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
510
|
+
const failure = { kind: isProviderAuthRequiredError(args.error) ? "auth" : classifyProviderError(args.error) };
|
|
555
511
|
const threadId = typeof controller?.threadId === "string" ? controller.threadId : void 0;
|
|
556
512
|
const pending = {
|
|
557
513
|
fromEntryId: from.id,
|
|
@@ -561,7 +517,8 @@ var AccountRotationProcessor = class {
|
|
|
561
517
|
reason,
|
|
562
518
|
at
|
|
563
519
|
};
|
|
564
|
-
|
|
520
|
+
const sticky = !requestModelRoute(args.requestContext, getRoutingController(args)).host;
|
|
521
|
+
if (sticky) await controller?.setThreadSetting?.({
|
|
565
522
|
key: MODEL_FALLBACK_STATE_KEY,
|
|
566
523
|
value: pending
|
|
567
524
|
});
|
|
@@ -575,7 +532,8 @@ var AccountRotationProcessor = class {
|
|
|
575
532
|
label: to.label
|
|
576
533
|
},
|
|
577
534
|
reason,
|
|
578
|
-
at
|
|
535
|
+
at,
|
|
536
|
+
failure
|
|
579
537
|
};
|
|
580
538
|
try {
|
|
581
539
|
await args.writer?.custom({
|
|
@@ -583,21 +541,22 @@ var AccountRotationProcessor = class {
|
|
|
583
541
|
data
|
|
584
542
|
});
|
|
585
543
|
} catch (error) {
|
|
586
|
-
await controller?.setThreadSetting?.({
|
|
544
|
+
if (sticky) await controller?.setThreadSetting?.({
|
|
587
545
|
key: MODEL_FALLBACK_STATE_KEY,
|
|
588
546
|
value: void 0
|
|
589
547
|
});
|
|
590
548
|
throw error;
|
|
591
549
|
}
|
|
592
|
-
await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
|
|
550
|
+
if (sticky) await controller?.setState?.({ [MODEL_FALLBACK_STATE_KEY]: pending });
|
|
593
551
|
args.state.startNoticeEmitted = false;
|
|
594
552
|
const targetRoute = resolveAccountRoute(args, to);
|
|
595
553
|
if (targetRoute) await applyPreferredAccountRoute(args, resolveCredentialStore(args.requestContext) ?? this.options.credentialStore, targetRoute).catch(() => void 0);
|
|
596
|
-
controller?.emitEvent?.({
|
|
554
|
+
if (sticky) controller?.emitEvent?.({
|
|
597
555
|
type: "info",
|
|
598
556
|
message: modelFallbackNoticeText(data)
|
|
599
557
|
});
|
|
600
558
|
cascade.position++;
|
|
559
|
+
if (!sticky && args.requestContext) advanceHostModelRoute(args.requestContext);
|
|
601
560
|
}
|
|
602
561
|
/**
|
|
603
562
|
* Pool done for this request: every instance recorded in the tried-set and
|
package/dist/auth/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse } from "./provider-auth-error.js";
|
|
2
2
|
import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
|
|
3
|
-
import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES,
|
|
3
|
+
import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MAX_STREAM_CUT_RETRIES, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
|
|
4
4
|
import { anthropicOAuthProvider } from "./providers/anthropic.js";
|
|
5
5
|
import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
|
|
6
6
|
import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
|
|
7
7
|
import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
|
|
8
|
+
import { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText } from "../model-fallback.js";
|
|
8
9
|
import { xaiOAuthProvider } from "./providers/xai.js";
|
|
9
10
|
export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, AuthStorage, MAX_STREAM_CUT_RETRIES, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, PROVIDER_DISPLAY_NAMES, ProviderAuthRequiredError, accountSwitchNoticeText, anthropicOAuthProvider, classifyRotationError, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, isAccountSwitchReason, isModelFallbackReason, isStreamCutAfterResponse, kimiCodingOAuthProvider, modelFallbackNoticeText, openaiCodexOAuthProvider, providerFromError, providerFromModelId, rejectUnauthorizedResponse, xaiOAuthProvider };
|
package/dist/headless/run-mc.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { MODEL_FALLBACK_STATE_KEY } from "../auth/account-rotation-processor.js";
|
|
2
1
|
import { GoalManager } from "../goal-manager.js";
|
|
3
2
|
import { createGoalReminderSignal } from "../goal-signal.js";
|
|
3
|
+
import { MODEL_FALLBACK_STATE_KEY } from "../model-fallback.js";
|
|
4
4
|
import { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from "../onboarding/settings.js";
|
|
5
5
|
import { parseCodexModelSelection } from "../providers/model-ids.js";
|
|
6
6
|
import { autoApprovePolicy } from "./policy.js";
|
package/dist/index.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { PostToolObserver, ToolLike } from './agents/tools.js';
|
|
|
19
19
|
import { AuthStorage } from './auth/storage.js';
|
|
20
20
|
import { HookManager } from './hooks/index.js';
|
|
21
21
|
import type { McpServerConfig } from './mcp/index.js';
|
|
22
|
+
import type { ModelFallback } from './model-fallback.js';
|
|
22
23
|
import { loadSettings } from './onboarding/settings.js';
|
|
23
24
|
import { PluginManager } from './plugins/manager.js';
|
|
24
25
|
import { ThreadScheduler } from './schedules/index.js';
|
|
@@ -136,6 +137,10 @@ export interface MastraCodeConfig {
|
|
|
136
137
|
resolveDefaultThinkingLevel?: (ctx: {
|
|
137
138
|
requestContext: RequestContext;
|
|
138
139
|
}) => ThinkingLevelSetting | Promise<ThinkingLevelSetting>;
|
|
140
|
+
/** Host-owned model route for the current request, called on every model resolution. */
|
|
141
|
+
resolveModelRoute?: (ctx: {
|
|
142
|
+
requestContext: RequestContext;
|
|
143
|
+
}) => readonly ModelFallback[] | Promise<readonly ModelFallback[]>;
|
|
139
144
|
/** Create a thread during local boot when no existing thread matches. Default: true */
|
|
140
145
|
createInitialThread?: boolean;
|
|
141
146
|
/** Trusted host instructions resolved outside mutable session state. */
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { createBackgroundCompletionCallbacks } from "./agents/background-complet
|
|
|
5
5
|
import { hasCredentialStoreProvider, setCredentialLogger, withCredentialTenantPreparation } from "./agents/credential-resolver.js";
|
|
6
6
|
import { getDynamicInstructions } from "./agents/instructions.js";
|
|
7
7
|
import { getDynamicMemory } from "./agents/memory.js";
|
|
8
|
-
import { canUseProvider, createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from "./agents/model.js";
|
|
8
|
+
import { canUseProvider, createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel, setHostModelRoute } from "./agents/model.js";
|
|
9
9
|
import { buildMode } from "./agents/modes/build.js";
|
|
10
10
|
import { fastMode } from "./agents/modes/explore.js";
|
|
11
11
|
import { createPlanMode } from "./agents/modes/plan.js";
|
|
@@ -14,30 +14,32 @@ import { builtinSubagents, resolveSubagentsSetting } from "./agents/subagents/in
|
|
|
14
14
|
import { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from "./agents/thread-caveman-state.js";
|
|
15
15
|
import { createDynamicTools, createToolHooks } from "./agents/tools.js";
|
|
16
16
|
import { getDynamicWorkspace, getGoalJudgeTools } from "./agents/workspace.js";
|
|
17
|
-
import { AccountRotationProcessor, AccountStartNoticeProcessor,
|
|
17
|
+
import { AccountRotationProcessor, AccountStartNoticeProcessor, isStreamCutAfterResponse } from "./auth/account-rotation-processor.js";
|
|
18
18
|
import { isKimiCodingDeviceId } from "./auth/providers/kimi-coding.js";
|
|
19
19
|
import { AuthStorage } from "./auth/storage.js";
|
|
20
20
|
import { CODE_AGENT_ID, DEFAULT_OM_MODEL_ID, validateConfigDirName } from "./constants.js";
|
|
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";
|
|
25
24
|
import { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeSessionScopes } from "./knowledge-scope.js";
|
|
25
|
+
import { createSubmitPlanTool } from "./tools/submit-plan.js";
|
|
26
26
|
import "./mcp/index.js";
|
|
27
|
+
import { MODEL_FALLBACK_STATE_KEY } from "./model-fallback.js";
|
|
27
28
|
import { getAvailableOmPacks, resolveAutoOMModelId } from "./onboarding/packs.js";
|
|
28
29
|
import { MASTRA_GATEWAY_PROVIDER, OBSERVABILITY_AUTH_PREFIX, loadSettings, resolveOmRoleModel, saveSettings } from "./onboarding/settings.js";
|
|
29
30
|
import { getToolCategory } from "./permissions.js";
|
|
30
31
|
import { PluginManager } from "./plugins/manager.js";
|
|
31
32
|
import { PluginSignalLane } from "./plugins/signal-lane.js";
|
|
32
33
|
import { PlanRejectionAbortProcessor } from "./processors/plan-rejection-abort.js";
|
|
34
|
+
import { RouteAwareStreamErrorRetryProcessor } from "./processors/route-aware-stream-error-retry.js";
|
|
33
35
|
import { createAmazonBedrockGateway } from "./providers/amazon-bedrock-gateway.js";
|
|
34
36
|
import { setAuthStorage } from "./providers/claude-max.js";
|
|
35
37
|
import { createGitHubCopilotGateway } from "./providers/github-copilot-gateway.js";
|
|
36
|
-
import { setAuthStorage as setAuthStorage$1 } from "./providers/github-copilot.js";
|
|
37
38
|
import { HookManager } from "./hooks/manager.js";
|
|
39
|
+
import { setAuthStorage as setAuthStorage$1 } from "./providers/github-copilot.js";
|
|
38
40
|
import { createGoogleVertexGateway } from "./providers/google-vertex-gateway.js";
|
|
39
|
-
import { setAuthStorage as setAuthStorage$2 } from "./providers/kimi-coding.js";
|
|
40
41
|
import { createMcpManager } from "./mcp/manager.js";
|
|
42
|
+
import { setAuthStorage as setAuthStorage$2 } from "./providers/kimi-coding.js";
|
|
41
43
|
import { parseCodexModelSelection } from "./providers/model-ids.js";
|
|
42
44
|
import { setAuthStorage as setAuthStorage$3 } from "./providers/openai-codex.js";
|
|
43
45
|
import { setAuthStorage as setAuthStorage$4 } from "./providers/xai.js";
|
|
@@ -79,7 +81,7 @@ import { classifyProviderError, getErrorFromUnknown } from "@mastra/core/error";
|
|
|
79
81
|
import { Knowledge, knowledgeMemoryScopes } from "@mastra/core/knowledge";
|
|
80
82
|
import { Mastra } from "@mastra/core/mastra";
|
|
81
83
|
import { defaultNotificationDeliveryDecision, readNotificationRoutingRequirement } from "@mastra/core/notifications";
|
|
82
|
-
import { AgentsMDInjector, CyberRefusalHandler, ProviderHistoryCompat,
|
|
84
|
+
import { AgentsMDInjector, CyberRefusalHandler, ProviderHistoryCompat, createBackgroundWorkSignalProcessor, isBadRequestError } from "@mastra/core/processors";
|
|
83
85
|
import { RequestContext } from "@mastra/core/request-context";
|
|
84
86
|
import { TaskSignalProvider } from "@mastra/core/signals";
|
|
85
87
|
import { MastraCompositeStore } from "@mastra/core/storage";
|
|
@@ -721,6 +723,7 @@ async function createMastraCodeAgentController(config) {
|
|
|
721
723
|
const resolveTenantSessionModel = withCredentialTenantPreparation(async (ctx) => {
|
|
722
724
|
const controller = ctx.requestContext.get("controller");
|
|
723
725
|
const hasSessionLevel = isThinkingLevelSetting(controller?.state?.thinkingLevel);
|
|
726
|
+
setHostModelRoute(ctx.requestContext, await config?.resolveModelRoute?.(ctx));
|
|
724
727
|
return getDynamicModel(ctx, config?.settingsPath, {
|
|
725
728
|
modeless,
|
|
726
729
|
defaultThinkingLevel: hasSessionLevel ? void 0 : await config?.resolveDefaultThinkingLevel?.(ctx)
|
|
@@ -837,7 +840,7 @@ async function createMastraCodeAgentController(config) {
|
|
|
837
840
|
errorProcessors: [
|
|
838
841
|
new ProviderHistoryCompat(),
|
|
839
842
|
new CyberRefusalHandler(),
|
|
840
|
-
new
|
|
843
|
+
new RouteAwareStreamErrorRetryProcessor({ matchers: [
|
|
841
844
|
{
|
|
842
845
|
match: isStreamCutAfterResponse,
|
|
843
846
|
maxRetries: 0
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { ThinkingLevelSetting } from './thinking.js';
|
|
3
|
+
export declare const MODEL_FALLBACK_PART_TYPE: 'data-mastracode-model-fallback';
|
|
4
|
+
export declare const MODEL_FALLBACK_STATE_KEY: 'mastracodePendingModelFallback';
|
|
5
|
+
declare const modelFallbackReasonSchema: z.ZodEnum<{
|
|
6
|
+
"persistent-outage": "persistent-outage";
|
|
7
|
+
"pool-exhausted": "pool-exhausted";
|
|
8
|
+
}>;
|
|
9
|
+
export type ModelFallbackReason = z.infer<typeof modelFallbackReasonSchema>;
|
|
10
|
+
declare const modelRouteFailureSchema: z.ZodObject<{
|
|
11
|
+
kind: z.ZodEnum<{
|
|
12
|
+
auth: "auth";
|
|
13
|
+
context_overflow: "context_overflow";
|
|
14
|
+
invalid_request: "invalid_request";
|
|
15
|
+
model_rejected: "model_rejected";
|
|
16
|
+
quota: "quota";
|
|
17
|
+
rate_limited: "rate_limited";
|
|
18
|
+
timeout: "timeout";
|
|
19
|
+
tool_history_rejected: "tool_history_rejected";
|
|
20
|
+
unavailable: "unavailable";
|
|
21
|
+
unknown: "unknown";
|
|
22
|
+
}>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
export type ModelRouteFailure = z.infer<typeof modelRouteFailureSchema>;
|
|
25
|
+
export declare const pendingModelFallbackSchema: z.ZodObject<{
|
|
26
|
+
fromEntryId: z.ZodString;
|
|
27
|
+
toEntryId: z.ZodString;
|
|
28
|
+
toModelId: z.ZodString;
|
|
29
|
+
threadId: z.ZodOptional<z.ZodString>;
|
|
30
|
+
reason: z.ZodEnum<{
|
|
31
|
+
"persistent-outage": "persistent-outage";
|
|
32
|
+
"pool-exhausted": "pool-exhausted";
|
|
33
|
+
}>;
|
|
34
|
+
at: z.ZodString;
|
|
35
|
+
}, z.core.$strip>;
|
|
36
|
+
export type PendingModelFallback = z.infer<typeof pendingModelFallbackSchema>;
|
|
37
|
+
export declare function parsePendingModelFallback(value: unknown): PendingModelFallback | null;
|
|
38
|
+
declare const modelFallbackPartSchema: z.ZodObject<{
|
|
39
|
+
from: z.ZodObject<{
|
|
40
|
+
entryId: z.ZodString;
|
|
41
|
+
label: z.ZodString;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
to: z.ZodObject<{
|
|
44
|
+
entryId: z.ZodString;
|
|
45
|
+
label: z.ZodString;
|
|
46
|
+
}, z.core.$strip>;
|
|
47
|
+
reason: z.ZodEnum<{
|
|
48
|
+
"persistent-outage": "persistent-outage";
|
|
49
|
+
"pool-exhausted": "pool-exhausted";
|
|
50
|
+
}>;
|
|
51
|
+
at: z.ZodCatch<z.ZodString>;
|
|
52
|
+
failure: z.ZodCatch<z.ZodOptional<z.ZodObject<{
|
|
53
|
+
kind: z.ZodEnum<{
|
|
54
|
+
auth: "auth";
|
|
55
|
+
context_overflow: "context_overflow";
|
|
56
|
+
invalid_request: "invalid_request";
|
|
57
|
+
model_rejected: "model_rejected";
|
|
58
|
+
quota: "quota";
|
|
59
|
+
rate_limited: "rate_limited";
|
|
60
|
+
timeout: "timeout";
|
|
61
|
+
tool_history_rejected: "tool_history_rejected";
|
|
62
|
+
unavailable: "unavailable";
|
|
63
|
+
unknown: "unknown";
|
|
64
|
+
}>;
|
|
65
|
+
}, z.core.$strip>>>;
|
|
66
|
+
}, z.core.$strip>;
|
|
67
|
+
export type ModelFallbackPartData = z.infer<typeof modelFallbackPartSchema>;
|
|
68
|
+
export declare function modelFallbackNoticeText(data: ModelFallbackPartData, modelName?: (label: string) => string): string;
|
|
69
|
+
export interface ModelFallback {
|
|
70
|
+
modelId: string;
|
|
71
|
+
thinkingLevel?: ThinkingLevelSetting;
|
|
72
|
+
}
|
|
73
|
+
export declare function parseModelFallbackPart(data: unknown): ModelFallbackPartData | null;
|
|
74
|
+
export {};
|
|
75
|
+
//# sourceMappingURL=model-fallback.d.ts.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { PROVIDER_FAILURE_KINDS } from "@mastra/core/error";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// src/model-fallback.ts
|
|
4
|
+
const MODEL_FALLBACK_PART_TYPE = "data-mastracode-model-fallback";
|
|
5
|
+
const MODEL_FALLBACK_STATE_KEY = "mastracodePendingModelFallback";
|
|
6
|
+
const modelFallbackReasonSchema = z.enum(["pool-exhausted", "persistent-outage"]);
|
|
7
|
+
const REASON_CLAUSE = {
|
|
8
|
+
"pool-exhausted": (model) => `${model} failed`,
|
|
9
|
+
"persistent-outage": (model) => `${model} keeps failing`
|
|
10
|
+
};
|
|
11
|
+
const modelRouteFailureSchema = z.object({ kind: z.enum(PROVIDER_FAILURE_KINDS) });
|
|
12
|
+
const pendingModelFallbackSchema = z.object({
|
|
13
|
+
fromEntryId: z.string().min(1),
|
|
14
|
+
toEntryId: z.string().min(1),
|
|
15
|
+
toModelId: z.string().min(1),
|
|
16
|
+
threadId: z.string().optional(),
|
|
17
|
+
reason: modelFallbackReasonSchema,
|
|
18
|
+
at: z.string()
|
|
19
|
+
});
|
|
20
|
+
function parsePendingModelFallback(value) {
|
|
21
|
+
return pendingModelFallbackSchema.safeParse(value).data ?? null;
|
|
22
|
+
}
|
|
23
|
+
const routeEndpointSchema = z.object({
|
|
24
|
+
entryId: z.string(),
|
|
25
|
+
label: z.string()
|
|
26
|
+
});
|
|
27
|
+
const modelFallbackPartSchema = z.object({
|
|
28
|
+
from: routeEndpointSchema,
|
|
29
|
+
to: routeEndpointSchema,
|
|
30
|
+
reason: modelFallbackReasonSchema,
|
|
31
|
+
at: z.string().catch(""),
|
|
32
|
+
failure: modelRouteFailureSchema.optional().catch(void 0)
|
|
33
|
+
});
|
|
34
|
+
const FAILURE_CLAUSE = {
|
|
35
|
+
rate_limited: (model) => `${model} is rate-limited`,
|
|
36
|
+
quota: (model) => `${model} is out of credits or quota`,
|
|
37
|
+
auth: (model) => `${model} has missing or invalid credentials`,
|
|
38
|
+
unavailable: (model) => `${model} is unavailable`,
|
|
39
|
+
timeout: (model) => `${model} timed out`,
|
|
40
|
+
model_rejected: (model) => `${model} was not found by its provider`
|
|
41
|
+
};
|
|
42
|
+
function modelFallbackNoticeText(data, modelName = (label) => label) {
|
|
43
|
+
return `${((data.failure && FAILURE_CLAUSE[data.failure.kind]) ?? REASON_CLAUSE[data.reason])(modelName(data.from.label))}, switched to ${modelName(data.to.label)}`;
|
|
44
|
+
}
|
|
45
|
+
function parseModelFallbackPart(data) {
|
|
46
|
+
return modelFallbackPartSchema.safeParse(data).data ?? null;
|
|
47
|
+
}
|
|
48
|
+
export { MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, modelFallbackNoticeText, parseModelFallbackPart, parsePendingModelFallback, pendingModelFallbackSchema };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { StreamErrorRetryProcessor } from '@mastra/core/processors';
|
|
2
|
+
import type { ProcessAPIErrorArgs, ProcessAPIErrorResult } from '@mastra/core/processors';
|
|
3
|
+
export declare class RouteAwareStreamErrorRetryProcessor extends StreamErrorRetryProcessor {
|
|
4
|
+
processAPIError(args: ProcessAPIErrorArgs): Promise<ProcessAPIErrorResult | void>;
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=route-aware-stream-error-retry.d.ts.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { requestRouteHasNextModel } from "../agents/model.js";
|
|
2
|
+
import { classifyProviderError } from "@mastra/core/error";
|
|
3
|
+
import { StreamErrorRetryProcessor } from "@mastra/core/processors";
|
|
4
|
+
// src/processors/route-aware-stream-error-retry.ts
|
|
5
|
+
var RouteAwareStreamErrorRetryProcessor = class extends StreamErrorRetryProcessor {
|
|
6
|
+
async processAPIError(args) {
|
|
7
|
+
if (classifyProviderError(args.error) === "rate_limited" && routeCanHop(args)) return;
|
|
8
|
+
return super.processAPIError(args);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
function routeCanHop({ requestContext }) {
|
|
12
|
+
const controller = requestContext?.get("controller");
|
|
13
|
+
return requestRouteHasNextModel(requestContext, controller);
|
|
14
|
+
}
|
|
15
|
+
export { RouteAwareStreamErrorRetryProcessor };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { AgentConfig, ToolsInput } from '@mastra/core/agent';
|
|
2
|
+
import { AgentController } from '@mastra/core/agent-controller';
|
|
3
|
+
import type { AgentControllerConfig, AgentControllerMode } from '@mastra/core/agent-controller';
|
|
4
|
+
import type { PubSub } from '@mastra/core/events';
|
|
5
|
+
import type { GatewayLanguageModel } from '@mastra/core/llm';
|
|
6
|
+
import { Mastra } from '@mastra/core/mastra';
|
|
7
|
+
import type { InputProcessor } from '@mastra/core/processors';
|
|
8
|
+
import type { RequestContext } from '@mastra/core/request-context';
|
|
9
|
+
import type { ApiRoute } from '@mastra/core/server';
|
|
10
|
+
import type { MastraCompositeStore } from '@mastra/core/storage';
|
|
11
|
+
import type { ToolAfterHookContext } from '@mastra/core/tools';
|
|
12
|
+
import type { Workspace } from '@mastra/core/workspace';
|
|
13
|
+
import type { MastraCodeState } from './schema.js';
|
|
14
|
+
/**
|
|
15
|
+
* Session tags are seeded into session state without validation, so a tag
|
|
16
|
+
* must not name a state field.
|
|
17
|
+
*/
|
|
18
|
+
declare class RestrictedAgentController extends AgentController<MastraCodeState> {
|
|
19
|
+
createSession(options?: Parameters<AgentController<MastraCodeState>['createSession']>[0]): Promise<import("@mastra/core/harness").Session<MastraCodeState>>;
|
|
20
|
+
}
|
|
21
|
+
export type RestrictedModel = GatewayLanguageModel | ((args: {
|
|
22
|
+
requestContext: RequestContext;
|
|
23
|
+
mastra?: Mastra;
|
|
24
|
+
}) => GatewayLanguageModel | Promise<GatewayLanguageModel>);
|
|
25
|
+
export type RestrictedToolProvider = Record<string, ToolsInput[string] | undefined> | ((args: {
|
|
26
|
+
requestContext: RequestContext;
|
|
27
|
+
}) => Record<string, ToolsInput[string] | undefined> | Promise<Record<string, ToolsInput[string] | undefined>>);
|
|
28
|
+
/**
|
|
29
|
+
* A controller mode for the restricted entry point. Per-mode agents are not
|
|
30
|
+
* accepted because they would replace the host-supplied model, instructions,
|
|
31
|
+
* and tools.
|
|
32
|
+
*/
|
|
33
|
+
export type RestrictedMode = AgentControllerMode & {
|
|
34
|
+
agent?: never;
|
|
35
|
+
};
|
|
36
|
+
export interface RestrictedProjectMetadata {
|
|
37
|
+
/** Stable resource id used to scope controller threads. */
|
|
38
|
+
resourceId: string;
|
|
39
|
+
/** Human-readable project name exposed in controller state. */
|
|
40
|
+
name: string;
|
|
41
|
+
/** Workspace path understood by the injected workspace. It is never inspected by this factory. */
|
|
42
|
+
rootPath: string;
|
|
43
|
+
/** Optional branch name supplied by the embedding host. */
|
|
44
|
+
gitBranch?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Fail-closed configuration for embedding Mastra Code in a credentialed server.
|
|
48
|
+
*
|
|
49
|
+
* Every capability is supplied by the embedding host. This factory does not
|
|
50
|
+
* discover local settings, credentials, projects, instructions, tools, or
|
|
51
|
+
* workspaces. Subagents, goals, workflows, plugins, discovered hooks, MCP, provider login,
|
|
52
|
+
* browser automation, and polling signal providers are not registered.
|
|
53
|
+
*/
|
|
54
|
+
export interface RestrictedMastraCodeConfig {
|
|
55
|
+
project: RestrictedProjectMetadata;
|
|
56
|
+
/** A pre-resolved model instance or resolver. Construct it with host-owned credentials. */
|
|
57
|
+
model: RestrictedModel;
|
|
58
|
+
/** Complete system instructions. No repository or global instruction files are loaded. */
|
|
59
|
+
instructions: AgentConfig['instructions'];
|
|
60
|
+
/** Explicit controller modes. Each mode is permanently bounded by `allowedTools`. */
|
|
61
|
+
modes: RestrictedMode[];
|
|
62
|
+
/** Explicit global tool allowlist. An empty array creates a tool-free agent. */
|
|
63
|
+
allowedTools: string[];
|
|
64
|
+
/** Host-supplied non-workspace tools. Built-in Mastra Code tools are not added. */
|
|
65
|
+
tools?: RestrictedToolProvider;
|
|
66
|
+
/** Host-supplied workspace. No local fallback is available. */
|
|
67
|
+
workspace: Workspace;
|
|
68
|
+
/** Host-supplied persistence. No settings-based storage fallback is available. */
|
|
69
|
+
storage: MastraCompositeStore;
|
|
70
|
+
/** Host-supplied memory, or false to disable memory. */
|
|
71
|
+
memory: AgentControllerConfig<MastraCodeState>['memory'] | false;
|
|
72
|
+
/** Initial state owned by the host. Project identity always wins over these values. */
|
|
73
|
+
initialState?: Partial<MastraCodeState>;
|
|
74
|
+
inputProcessors?: InputProcessor[];
|
|
75
|
+
/** Observe completed tool calls. The observer cannot add or replace tools. */
|
|
76
|
+
postToolObserver?: (context: ToolAfterHookContext) => void | Promise<void>;
|
|
77
|
+
pubsub?: PubSub;
|
|
78
|
+
idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];
|
|
79
|
+
}
|
|
80
|
+
export interface RestrictedMastraCodeMountConfig extends RestrictedMastraCodeConfig {
|
|
81
|
+
mastra?: Mastra;
|
|
82
|
+
controllerId?: string;
|
|
83
|
+
buildApiRoutes?: (deps: {
|
|
84
|
+
controller: AgentController<MastraCodeState>;
|
|
85
|
+
}) => ApiRoute[];
|
|
86
|
+
buildServerConfig?: (deps: {
|
|
87
|
+
controller: AgentController<MastraCodeState>;
|
|
88
|
+
}) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Creates an uninitialized, restricted Mastra Code controller.
|
|
92
|
+
*
|
|
93
|
+
* Use {@link mountRestrictedAgentControllerOnMastra} for the normal server
|
|
94
|
+
* lifecycle. This lower-level function is useful when the host owns controller
|
|
95
|
+
* registration and initialization.
|
|
96
|
+
*/
|
|
97
|
+
export declare function createRestrictedMastraCodeAgentController(config: RestrictedMastraCodeConfig): Promise<{
|
|
98
|
+
controller: RestrictedAgentController;
|
|
99
|
+
storage: MastraCompositeStore;
|
|
100
|
+
memory: import("@mastra/core/base").DynamicArgument<import("@mastra/core/memory").MastraMemory> | undefined;
|
|
101
|
+
workspace: Workspace<import("@mastra/core/workspace").WorkspaceFilesystem | undefined, import("@mastra/core/workspace").WorkspaceSandbox | undefined, undefined>;
|
|
102
|
+
codeAgent: import("@mastra/core/agent").Agent<string, ToolsInput, undefined, any, import("@mastra/core/agent").AgentEditorConfig | undefined>;
|
|
103
|
+
projectPath: string;
|
|
104
|
+
allowedTools: string[];
|
|
105
|
+
}>;
|
|
106
|
+
export type RestrictedMastraCodeAgentController = Awaited<ReturnType<typeof createRestrictedMastraCodeAgentController>>;
|
|
107
|
+
/**
|
|
108
|
+
* Mounts a restricted Mastra Code controller without registering local
|
|
109
|
+
* workflows or any discovery-backed capability.
|
|
110
|
+
*/
|
|
111
|
+
export declare function mountRestrictedAgentControllerOnMastra(config: RestrictedMastraCodeMountConfig): Promise<RestrictedMastraCodeAgentController & {
|
|
112
|
+
mastra: Mastra;
|
|
113
|
+
}>;
|
|
114
|
+
export {};
|
|
115
|
+
//# sourceMappingURL=restricted.d.ts.map
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { AgentController } from "@mastra/core/agent-controller";
|
|
2
|
+
import { createCodingAgent } from "@mastra/core/coding-agent";
|
|
3
|
+
import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
|
|
4
|
+
import { Mastra } from "@mastra/core/mastra";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
// src/restricted.ts
|
|
7
|
+
const disabledModel = z.never().optional();
|
|
8
|
+
/**
|
|
9
|
+
* Persisted "allow" rules skip tool approval just like yolo. Session state may
|
|
10
|
+
* only keep the "allow" rules the host set in `initialState`; clients can still
|
|
11
|
+
* tighten approval or answer individual approval prompts.
|
|
12
|
+
*/
|
|
13
|
+
function restrictedPermissionRules(hostRules) {
|
|
14
|
+
const policies = z.record(z.string(), z.enum([
|
|
15
|
+
"allow",
|
|
16
|
+
"ask",
|
|
17
|
+
"deny"
|
|
18
|
+
])).default({});
|
|
19
|
+
return z.object({
|
|
20
|
+
categories: policies,
|
|
21
|
+
tools: policies
|
|
22
|
+
}).superRefine((rules, ctx) => {
|
|
23
|
+
for (const scope of ["categories", "tools"]) for (const [name, policy] of Object.entries(rules[scope])) if (policy === "allow" && hostRules?.[scope]?.[name] !== "allow") ctx.addIssue({
|
|
24
|
+
code: "custom",
|
|
25
|
+
path: [scope, name],
|
|
26
|
+
message: `Restricted Mastra Code can't auto-approve "${name}" unless the host allows it`
|
|
27
|
+
});
|
|
28
|
+
}).default({
|
|
29
|
+
categories: {},
|
|
30
|
+
tools: {}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const restrictedStateSchema = z.looseObject({
|
|
34
|
+
currentModelId: z.string().optional(),
|
|
35
|
+
modeId: z.string().optional(),
|
|
36
|
+
subagentModelId: z.string().optional(),
|
|
37
|
+
projectPath: z.string().optional(),
|
|
38
|
+
projectName: z.string().optional(),
|
|
39
|
+
factoryProjectId: z.string().optional(),
|
|
40
|
+
factoryOrgId: z.string().optional(),
|
|
41
|
+
factoryOrgUnresolved: z.boolean().optional(),
|
|
42
|
+
projectRepositoryId: z.string().optional(),
|
|
43
|
+
branch: z.string().optional(),
|
|
44
|
+
untrustedCheckout: z.boolean().optional(),
|
|
45
|
+
baseRef: z.string().optional(),
|
|
46
|
+
skipGlobalInstructions: z.literal(true).default(true),
|
|
47
|
+
configDir: z.string().default(".mastracode"),
|
|
48
|
+
homeDir: z.string().optional(),
|
|
49
|
+
gitBranch: z.string().optional(),
|
|
50
|
+
lastCommand: z.string().optional(),
|
|
51
|
+
observerModelId: disabledModel,
|
|
52
|
+
reflectorModelId: disabledModel,
|
|
53
|
+
observerModelSelection: disabledModel,
|
|
54
|
+
reflectorModelSelection: disabledModel,
|
|
55
|
+
observationThreshold: z.number().default(3e4),
|
|
56
|
+
reflectionThreshold: z.number().default(4e4),
|
|
57
|
+
cavemanObservations: z.boolean().default(false),
|
|
58
|
+
observeAttachments: z.union([z.literal("auto"), z.boolean()]).default("auto"),
|
|
59
|
+
omScope: z.enum(["thread", "resource"]).optional(),
|
|
60
|
+
thinkingLevel: z.enum([
|
|
61
|
+
"off",
|
|
62
|
+
"low",
|
|
63
|
+
"medium",
|
|
64
|
+
"high",
|
|
65
|
+
"xhigh",
|
|
66
|
+
"max"
|
|
67
|
+
]).optional(),
|
|
68
|
+
yolo: z.literal(false).default(false),
|
|
69
|
+
permissionRules: restrictedPermissionRules(),
|
|
70
|
+
smartEditing: z.boolean().default(true),
|
|
71
|
+
notifications: z.enum([
|
|
72
|
+
"bell",
|
|
73
|
+
"system",
|
|
74
|
+
"both",
|
|
75
|
+
"off"
|
|
76
|
+
]).default("off"),
|
|
77
|
+
tasks: z.array(z.object({
|
|
78
|
+
id: z.string().optional(),
|
|
79
|
+
content: z.string(),
|
|
80
|
+
status: z.enum([
|
|
81
|
+
"pending",
|
|
82
|
+
"in_progress",
|
|
83
|
+
"completed"
|
|
84
|
+
]),
|
|
85
|
+
activeForm: z.string()
|
|
86
|
+
})).default([]),
|
|
87
|
+
sandboxAllowedPaths: z.array(z.string()).default([]),
|
|
88
|
+
pluginSkillPaths: z.array(z.string()).max(0).default([]),
|
|
89
|
+
pluginCommandPaths: z.array(z.string()).max(0).default([]),
|
|
90
|
+
pluginInstructions: z.array(z.string()).max(0).default([]),
|
|
91
|
+
activePlan: z.object({
|
|
92
|
+
title: z.string(),
|
|
93
|
+
plan: z.string(),
|
|
94
|
+
approvedAt: z.string()
|
|
95
|
+
}).nullable().default(null),
|
|
96
|
+
activeBrowserSettings: z.never().optional()
|
|
97
|
+
});
|
|
98
|
+
const restrictedStateKeys = new Set(Object.keys(restrictedStateSchema.shape));
|
|
99
|
+
/**
|
|
100
|
+
* Session tags are seeded into session state without validation, so a tag
|
|
101
|
+
* must not name a state field.
|
|
102
|
+
*/
|
|
103
|
+
var RestrictedAgentController = class extends AgentController {
|
|
104
|
+
async createSession(options = {}) {
|
|
105
|
+
const stateTags = Object.keys(options.tags ?? {}).filter((key) => restrictedStateKeys.has(key));
|
|
106
|
+
if (stateTags.length > 0) throw new MastraError({
|
|
107
|
+
id: "RESTRICTED_MASTRA_CODE_STATE_TAGS",
|
|
108
|
+
domain: ErrorDomain.AGENT,
|
|
109
|
+
category: ErrorCategory.USER,
|
|
110
|
+
details: { status: 400 },
|
|
111
|
+
text: `Restricted Mastra Code session tags can't set state fields: ${stateTags.join(", ")}`
|
|
112
|
+
});
|
|
113
|
+
return super.createSession(options);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
/** Validates required host authority decisions and returns the fixed tool allowlist. */
|
|
117
|
+
function validateRestrictedConfig(config) {
|
|
118
|
+
if (config.instructions === void 0) throw new Error("Restricted Mastra Code requires explicit instructions");
|
|
119
|
+
if (config.storage === void 0) throw new Error("Restricted Mastra Code requires explicit storage");
|
|
120
|
+
if (!config.project.resourceId.trim()) throw new Error("Restricted Mastra Code requires project.resourceId");
|
|
121
|
+
if (!config.project.name.trim()) throw new Error("Restricted Mastra Code requires project.name");
|
|
122
|
+
if (!config.project.rootPath.trim()) throw new Error("Restricted Mastra Code requires project.rootPath");
|
|
123
|
+
if (config.modes.length === 0) throw new Error("Restricted Mastra Code requires at least one mode");
|
|
124
|
+
for (const mode of config.modes) if (mode.agent !== void 0) throw new Error(`Restricted Mastra Code mode "${mode.id}" must not define its own agent`);
|
|
125
|
+
if (config.memory === void 0) throw new Error("Restricted Mastra Code requires an explicit memory policy");
|
|
126
|
+
const allowedTools = /* @__PURE__ */ new Set();
|
|
127
|
+
for (const name of config.allowedTools) {
|
|
128
|
+
if (!name.trim()) throw new Error("Restricted Mastra Code tool names must not be empty");
|
|
129
|
+
allowedTools.add(name);
|
|
130
|
+
}
|
|
131
|
+
return allowedTools;
|
|
132
|
+
}
|
|
133
|
+
/** Bounds every controller mode by the host's global tool allowlist. */
|
|
134
|
+
function restrictModes(modes, allowedTools) {
|
|
135
|
+
return modes.map((mode) => ({
|
|
136
|
+
...mode,
|
|
137
|
+
availableTools: (mode.availableTools ?? [...allowedTools]).filter((name) => allowedTools.has(name))
|
|
138
|
+
}));
|
|
139
|
+
}
|
|
140
|
+
/** Filters static and request-scoped host tools before exposing them to the agent. */
|
|
141
|
+
function createRestrictedToolProvider(provider, allowedTools) {
|
|
142
|
+
return async ({ requestContext }) => {
|
|
143
|
+
const resolved = typeof provider === "function" ? await provider({ requestContext }) : provider;
|
|
144
|
+
if (!resolved) return {};
|
|
145
|
+
return Object.fromEntries(Object.entries(resolved).filter((entry) => allowedTools.has(entry[0]) && entry[1] !== void 0));
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/** Adapts an explicit host observer without enabling discovered hook configuration. */
|
|
149
|
+
function createRestrictedToolHooks(observer) {
|
|
150
|
+
if (!observer) return void 0;
|
|
151
|
+
return { afterToolCall: async (context) => {
|
|
152
|
+
await observer(context);
|
|
153
|
+
} };
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Creates an uninitialized, restricted Mastra Code controller.
|
|
157
|
+
*
|
|
158
|
+
* Use {@link mountRestrictedAgentControllerOnMastra} for the normal server
|
|
159
|
+
* lifecycle. This lower-level function is useful when the host owns controller
|
|
160
|
+
* registration and initialization.
|
|
161
|
+
*/
|
|
162
|
+
async function createRestrictedMastraCodeAgentController(config) {
|
|
163
|
+
const allowedTools = validateRestrictedConfig(config);
|
|
164
|
+
const modes = restrictModes(config.modes, allowedTools);
|
|
165
|
+
const defaultModeId = modes.find((mode) => mode.metadata?.default === true)?.id ?? modes.find((mode) => mode.id === "build")?.id ?? modes[0].id;
|
|
166
|
+
const memory = config.memory === false ? void 0 : config.memory;
|
|
167
|
+
const codeAgent = createCodingAgent({
|
|
168
|
+
id: "restricted-code-agent",
|
|
169
|
+
name: "Code Agent",
|
|
170
|
+
workspace: void 0,
|
|
171
|
+
model: config.model,
|
|
172
|
+
instructions: config.instructions,
|
|
173
|
+
tools: createRestrictedToolProvider(config.tools, allowedTools),
|
|
174
|
+
hooks: createRestrictedToolHooks(config.postToolObserver),
|
|
175
|
+
inputProcessors: config.inputProcessors ?? [],
|
|
176
|
+
memory,
|
|
177
|
+
signals: [],
|
|
178
|
+
notifications: { deliveryPolicy: { default: {
|
|
179
|
+
action: "persist",
|
|
180
|
+
reason: "restricted-persist-only"
|
|
181
|
+
} } }
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
controller: new RestrictedAgentController({
|
|
185
|
+
id: "mastra-code",
|
|
186
|
+
resourceId: config.project.resourceId,
|
|
187
|
+
storage: config.storage,
|
|
188
|
+
memory,
|
|
189
|
+
pubsub: config.pubsub,
|
|
190
|
+
stateSchema: restrictedStateSchema.extend({ permissionRules: restrictedPermissionRules(config.initialState?.permissionRules) }),
|
|
191
|
+
agent: codeAgent,
|
|
192
|
+
subagents: [],
|
|
193
|
+
gateways: [],
|
|
194
|
+
includeDefaultGateways: false,
|
|
195
|
+
modelFallbacks: false,
|
|
196
|
+
registerAgents: false,
|
|
197
|
+
workspace: config.workspace,
|
|
198
|
+
initialState: {
|
|
199
|
+
...config.initialState,
|
|
200
|
+
yolo: false,
|
|
201
|
+
skipGlobalInstructions: true,
|
|
202
|
+
observerModelId: void 0,
|
|
203
|
+
reflectorModelId: void 0,
|
|
204
|
+
observerModelSelection: void 0,
|
|
205
|
+
reflectorModelSelection: void 0,
|
|
206
|
+
projectPath: config.project.rootPath,
|
|
207
|
+
projectName: config.project.name,
|
|
208
|
+
gitBranch: config.project.gitBranch,
|
|
209
|
+
pluginSkillPaths: [],
|
|
210
|
+
pluginCommandPaths: [],
|
|
211
|
+
pluginInstructions: []
|
|
212
|
+
},
|
|
213
|
+
modes,
|
|
214
|
+
defaultModeId,
|
|
215
|
+
intervalHandlers: [],
|
|
216
|
+
idGenerator: config.idGenerator
|
|
217
|
+
}),
|
|
218
|
+
storage: config.storage,
|
|
219
|
+
memory,
|
|
220
|
+
workspace: config.workspace,
|
|
221
|
+
codeAgent,
|
|
222
|
+
projectPath: config.project.rootPath,
|
|
223
|
+
allowedTools: [...allowedTools]
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Mounts a restricted Mastra Code controller without registering local
|
|
228
|
+
* workflows or any discovery-backed capability.
|
|
229
|
+
*/
|
|
230
|
+
async function mountRestrictedAgentControllerOnMastra(config) {
|
|
231
|
+
const base = await createRestrictedMastraCodeAgentController(config);
|
|
232
|
+
const controllerId = config.controllerId ?? base.controller.id;
|
|
233
|
+
let mastra = config.mastra;
|
|
234
|
+
if (mastra) {
|
|
235
|
+
mastra.listAgentControllers()[controllerId] = base.controller;
|
|
236
|
+
base.controller.__registerMastra(mastra);
|
|
237
|
+
} else {
|
|
238
|
+
const apiRoutes = config.buildApiRoutes?.({ controller: base.controller });
|
|
239
|
+
const server = {
|
|
240
|
+
...config.buildServerConfig?.({ controller: base.controller }),
|
|
241
|
+
...apiRoutes?.length ? { apiRoutes } : {}
|
|
242
|
+
};
|
|
243
|
+
mastra = new Mastra({
|
|
244
|
+
agentControllers: { [controllerId]: base.controller },
|
|
245
|
+
storage: config.storage,
|
|
246
|
+
...config.pubsub ? { pubsub: config.pubsub } : {},
|
|
247
|
+
...Object.keys(server).length ? { server } : {}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
await base.controller.init();
|
|
251
|
+
await mastra.startWorkers();
|
|
252
|
+
return {
|
|
253
|
+
...base,
|
|
254
|
+
mastra
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
export { createRestrictedMastraCodeAgentController, mountRestrictedAgentControllerOnMastra };
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { OMModel } from '@mastra/core/agent-controller';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
import type { PendingModelFallback } from './model-fallback.js';
|
|
3
4
|
import type { ThinkingLevelSetting } from './thinking.js';
|
|
5
|
+
export type {
|
|
6
|
+
/** @deprecated Import from `@mastra/code-sdk/model-fallback`. */
|
|
7
|
+
PendingModelFallback, } from './model-fallback.js';
|
|
4
8
|
export type PermissionPolicy = 'allow' | 'ask' | 'deny';
|
|
5
9
|
export type MastraCodeSessionState = {
|
|
6
10
|
currentModelId: string;
|
|
@@ -11,20 +15,13 @@ export interface ModelRouteEntry {
|
|
|
11
15
|
id: string;
|
|
12
16
|
label: string;
|
|
13
17
|
modelId: string;
|
|
18
|
+
thinkingLevel?: ThinkingLevelSetting;
|
|
14
19
|
accountId?: string;
|
|
15
20
|
memoryModelId?: string;
|
|
16
21
|
}
|
|
17
22
|
export interface ModelRoute {
|
|
18
23
|
entries: ModelRouteEntry[];
|
|
19
24
|
}
|
|
20
|
-
export interface PendingModelFallback {
|
|
21
|
-
fromEntryId: string;
|
|
22
|
-
toEntryId: string;
|
|
23
|
-
toModelId: string;
|
|
24
|
-
threadId?: string;
|
|
25
|
-
reason: 'pool-exhausted' | 'persistent-outage';
|
|
26
|
-
at: string;
|
|
27
|
-
}
|
|
28
25
|
export interface MastraCodeState {
|
|
29
26
|
[key: string]: unknown;
|
|
30
27
|
[key: `subagentModelId_${string}`]: string | undefined;
|
package/dist/schema.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DEFAULT_CONFIG_DIR } from "./constants.js";
|
|
2
|
+
import { pendingModelFallbackSchema } from "./model-fallback.js";
|
|
2
3
|
import { THINKING_LEVEL_VALUES } from "./thinking.js";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
// src/schema.ts
|
|
@@ -77,14 +78,7 @@ const stateSchema = z.object({
|
|
|
77
78
|
activeForm: z.string()
|
|
78
79
|
})).default([]),
|
|
79
80
|
sandboxAllowedPaths: z.array(z.string()).default([]),
|
|
80
|
-
mastracodePendingModelFallback:
|
|
81
|
-
fromEntryId: z.string(),
|
|
82
|
-
toEntryId: z.string(),
|
|
83
|
-
toModelId: z.string(),
|
|
84
|
-
threadId: z.string().optional(),
|
|
85
|
-
reason: z.enum(["pool-exhausted", "persistent-outage"]),
|
|
86
|
-
at: z.string()
|
|
87
|
-
}).nullish(),
|
|
81
|
+
mastracodePendingModelFallback: pendingModelFallbackSchema.nullish(),
|
|
88
82
|
pluginSkillPaths: z.array(z.string()).default([]),
|
|
89
83
|
pluginCommandPaths: z.array(z.string()).default([]),
|
|
90
84
|
pluginInstructions: z.array(z.string()).default([]),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.22.0-alpha.0",
|
|
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,19 +65,19 @@
|
|
|
65
65
|
"yaml": "^2.9.1",
|
|
66
66
|
"zod": "^4.6.7",
|
|
67
67
|
"@mastra/agent-browser": "0.7.0",
|
|
68
|
-
"@mastra/client-js": "1.62.0",
|
|
68
|
+
"@mastra/client-js": "1.62.1-alpha.0",
|
|
69
69
|
"@mastra/duckdb": "1.19.2",
|
|
70
|
-
"@mastra/fastembed": "1.4.0",
|
|
71
70
|
"@mastra/github-signals": "0.5.4",
|
|
72
|
-
"@mastra/
|
|
71
|
+
"@mastra/fastembed": "1.4.0",
|
|
72
|
+
"@mastra/libsql": "1.33.0-alpha.0",
|
|
73
73
|
"@mastra/mcp": "2.11.0",
|
|
74
|
-
"@mastra/
|
|
75
|
-
"@mastra/observability": "1.24.3",
|
|
74
|
+
"@mastra/observability": "1.24.4-alpha.0",
|
|
76
75
|
"@mastra/parallel": "0.1.6",
|
|
77
|
-
"@mastra/
|
|
76
|
+
"@mastra/memory": "1.41.3",
|
|
77
|
+
"@mastra/pg": "1.39.0-alpha.0",
|
|
78
78
|
"@mastra/schema-compat": "1.4.1",
|
|
79
|
-
"@mastra/stagehand": "0.4.1",
|
|
80
79
|
"@mastra/tavily": "1.1.4",
|
|
80
|
+
"@mastra/stagehand": "0.4.1",
|
|
81
81
|
"@mastra/voice-deepgram": "0.13.5",
|
|
82
82
|
"@mastra/voice-mistral": "0.1.4",
|
|
83
83
|
"@mastra/voice-openai": "0.13.5"
|
|
@@ -94,8 +94,8 @@
|
|
|
94
94
|
"vitest": "5.1.0",
|
|
95
95
|
"@internal/lint": "0.0.152",
|
|
96
96
|
"@internal/types-builder": "0.0.127",
|
|
97
|
-
"@
|
|
98
|
-
"@
|
|
97
|
+
"@mastra/core": "1.87.0-alpha.0",
|
|
98
|
+
"@internal/workspace-test-utils": "0.0.96"
|
|
99
99
|
},
|
|
100
100
|
"peerDependencies": {
|
|
101
101
|
"@mastra/core": ">=1.86.0-0 <2.0.0-0"
|