@mastra/code-sdk 1.21.0-alpha.9 → 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 +22 -22
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([]),
|