@mastra/code-sdk 1.21.0 → 1.22.0-alpha.1
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/custom-provider-check.d.ts +98 -0
- package/dist/agents/custom-provider-check.js +700 -0
- package/dist/agents/mastracode-gateway.d.ts +9 -0
- package/dist/agents/mastracode-gateway.js +18 -15
- 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/onboarding/custom-provider-headers.d.ts +50 -0
- package/dist/onboarding/custom-provider-headers.js +112 -0
- package/dist/onboarding/custom-providers.js +11 -0
- package/dist/onboarding/settings.d.ts +13 -0
- package/dist/onboarding/settings.js +27 -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 +6 -6
|
@@ -16,11 +16,23 @@ export interface CustomPack {
|
|
|
16
16
|
models: Record<string, string>;
|
|
17
17
|
createdAt: string;
|
|
18
18
|
}
|
|
19
|
+
/** How a custom provider sends its API key: `Authorization: Bearer <key>` or `x-api-key: <key>`. */
|
|
20
|
+
export type CustomProviderAuthScheme = 'bearer' | 'x-api-key';
|
|
21
|
+
/** An extra header a custom provider sends on every call. */
|
|
22
|
+
export interface CustomProviderHeader {
|
|
23
|
+
name: string;
|
|
24
|
+
value: string;
|
|
25
|
+
/** Hidden in UIs and never returned by the Factory API. */
|
|
26
|
+
secret?: boolean;
|
|
27
|
+
}
|
|
19
28
|
/** A saved custom provider for OpenAI-compatible endpoints. */
|
|
20
29
|
export interface CustomProviderSetting {
|
|
21
30
|
name: string;
|
|
22
31
|
url: string;
|
|
23
32
|
apiKey?: string;
|
|
33
|
+
/** Absent means `bearer`. */
|
|
34
|
+
authScheme?: CustomProviderAuthScheme;
|
|
35
|
+
headers?: CustomProviderHeader[];
|
|
24
36
|
models: string[];
|
|
25
37
|
}
|
|
26
38
|
/** Storage backend type. */
|
|
@@ -389,6 +401,7 @@ export declare function toCustomProviderModelId(providerName: string, modelName:
|
|
|
389
401
|
* legitimate `mastracode/...` gateway-routed ids are left untouched.
|
|
390
402
|
*/
|
|
391
403
|
export declare function stripMastraCodeCustomProviderPrefix(modelId: string, customProviders: Array<Pick<CustomProviderSetting, 'name'>>): string;
|
|
404
|
+
/** Read and sanitize the `customProviders` list of settings.json. */
|
|
392
405
|
export declare function parseCustomProviders(rawProviders: unknown): CustomProviderSetting[];
|
|
393
406
|
/**
|
|
394
407
|
* Resolve the effective LSP config. LSP is opt-in: `false` and an absent
|
|
@@ -4,6 +4,7 @@ import { buildCodexStagehandFetch, createCodexMiddleware } from "../providers/op
|
|
|
4
4
|
import { THINKING_LEVEL_VALUES, isThinkingLevelSetting, resolveDefaultThinkingLevel as resolveDefaultThinkingLevel$1 } from "../thinking.js";
|
|
5
5
|
import { getAppDataDir } from "../utils/project.js";
|
|
6
6
|
import { DEFAULT_STT_PROVIDER, resolveSTTModel } from "../voice/stt-registry.js";
|
|
7
|
+
import { customProviderHeaderProblem, isCustomProviderAuthScheme } from "./custom-provider-headers.js";
|
|
7
8
|
import { pruneUnknownModePackFallbacks, pruneUnknownPackAccountPreferences } from "./packs.js";
|
|
8
9
|
import { dirname, join } from "path";
|
|
9
10
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
|
|
@@ -371,6 +372,28 @@ function stripMastraCodeCustomProviderPrefix(modelId, customProviders) {
|
|
|
371
372
|
if (!providerId || modelParts.length === 0 || modelParts.some((part) => part.length === 0)) return modelId;
|
|
372
373
|
return customProviders.some((provider) => getCustomProviderId(provider.name) === providerId) ? rest : modelId;
|
|
373
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* Read the custom headers of a saved provider. An entry that breaks the header
|
|
377
|
+
* rules is dropped on its own, so one bad hand-edited header does not discard
|
|
378
|
+
* the provider or its other headers.
|
|
379
|
+
*/
|
|
380
|
+
function parseCustomProviderHeaders(rawHeaders, authScheme) {
|
|
381
|
+
if (!Array.isArray(rawHeaders)) return [];
|
|
382
|
+
const headers = [];
|
|
383
|
+
for (const rawHeader of rawHeaders) {
|
|
384
|
+
if (!rawHeader || typeof rawHeader !== "object") continue;
|
|
385
|
+
const candidate = rawHeader;
|
|
386
|
+
if (typeof candidate.name !== "string" || typeof candidate.value !== "string") continue;
|
|
387
|
+
const header = {
|
|
388
|
+
name: candidate.name.trim(),
|
|
389
|
+
value: candidate.value.trim(),
|
|
390
|
+
...typeof candidate.secret === "boolean" ? { secret: candidate.secret } : {}
|
|
391
|
+
};
|
|
392
|
+
if (customProviderHeaderProblem([...headers, header], authScheme) === void 0) headers.push(header);
|
|
393
|
+
}
|
|
394
|
+
return headers;
|
|
395
|
+
}
|
|
396
|
+
/** Read and sanitize the `customProviders` list of settings.json. */
|
|
374
397
|
function parseCustomProviders(rawProviders) {
|
|
375
398
|
if (!Array.isArray(rawProviders)) return [];
|
|
376
399
|
const parsedProviders = [];
|
|
@@ -387,10 +410,14 @@ function parseCustomProviders(rawProviders) {
|
|
|
387
410
|
return model;
|
|
388
411
|
}))].filter((model) => model.length > 0) : [];
|
|
389
412
|
const apiKey = typeof candidate.apiKey === "string" && candidate.apiKey.trim().length > 0 ? candidate.apiKey.trim() : void 0;
|
|
413
|
+
const authScheme = isCustomProviderAuthScheme(candidate.authScheme) ? candidate.authScheme : void 0;
|
|
414
|
+
const headers = parseCustomProviderHeaders(candidate.headers, authScheme);
|
|
390
415
|
parsedProviders.push({
|
|
391
416
|
name,
|
|
392
417
|
url,
|
|
393
418
|
...apiKey ? { apiKey } : {},
|
|
419
|
+
...authScheme ? { authScheme } : {},
|
|
420
|
+
...headers.length > 0 ? { headers } : {},
|
|
394
421
|
models
|
|
395
422
|
});
|
|
396
423
|
}
|
|
@@ -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.1",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -65,16 +65,16 @@
|
|
|
65
65
|
"yaml": "^2.9.1",
|
|
66
66
|
"zod": "^4.6.7",
|
|
67
67
|
"@mastra/agent-browser": "0.7.0",
|
|
68
|
-
"@mastra/client-js": "1.62.
|
|
68
|
+
"@mastra/client-js": "1.62.1-alpha.1",
|
|
69
69
|
"@mastra/duckdb": "1.19.2",
|
|
70
70
|
"@mastra/fastembed": "1.4.0",
|
|
71
71
|
"@mastra/github-signals": "0.5.4",
|
|
72
|
-
"@mastra/libsql": "1.
|
|
72
|
+
"@mastra/libsql": "1.33.0-alpha.0",
|
|
73
73
|
"@mastra/mcp": "2.11.0",
|
|
74
74
|
"@mastra/memory": "1.41.3",
|
|
75
|
-
"@mastra/observability": "1.24.
|
|
75
|
+
"@mastra/observability": "1.24.4-alpha.0",
|
|
76
76
|
"@mastra/parallel": "0.1.6",
|
|
77
|
-
"@mastra/pg": "1.
|
|
77
|
+
"@mastra/pg": "1.39.0-alpha.0",
|
|
78
78
|
"@mastra/schema-compat": "1.4.1",
|
|
79
79
|
"@mastra/stagehand": "0.4.1",
|
|
80
80
|
"@mastra/tavily": "1.1.4",
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
"@internal/lint": "0.0.152",
|
|
96
96
|
"@internal/types-builder": "0.0.127",
|
|
97
97
|
"@internal/workspace-test-utils": "0.0.96",
|
|
98
|
-
"@mastra/core": "1.
|
|
98
|
+
"@mastra/core": "1.87.0-alpha.1"
|
|
99
99
|
},
|
|
100
100
|
"peerDependencies": {
|
|
101
101
|
"@mastra/core": ">=1.86.0-0 <2.0.0-0"
|