@mastra/code-sdk 1.4.1-alpha.2 → 1.5.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/dist/agents/context-audit.d.ts +84 -0
  3. package/dist/agents/context-audit.d.ts.map +1 -0
  4. package/dist/agents/context-audit.js +118 -0
  5. package/dist/agents/context-audit.js.map +1 -0
  6. package/dist/agents/instructions.d.ts +12 -1
  7. package/dist/agents/instructions.d.ts.map +1 -1
  8. package/dist/agents/instructions.js +23 -5
  9. package/dist/agents/instructions.js.map +1 -1
  10. package/dist/agents/memory.d.ts.map +1 -1
  11. package/dist/agents/memory.js +35 -32
  12. package/dist/agents/memory.js.map +1 -1
  13. package/dist/agents/model.d.ts +11 -4
  14. package/dist/agents/model.d.ts.map +1 -1
  15. package/dist/agents/model.js +2 -1
  16. package/dist/agents/model.js.map +1 -1
  17. package/dist/agents/prompts/agent-instructions.d.ts +9 -0
  18. package/dist/agents/prompts/agent-instructions.d.ts.map +1 -1
  19. package/dist/agents/prompts/agent-instructions.js +14 -4
  20. package/dist/agents/prompts/agent-instructions.js.map +1 -1
  21. package/dist/agents/prompts/index.d.ts +28 -0
  22. package/dist/agents/prompts/index.d.ts.map +1 -1
  23. package/dist/agents/prompts/index.js +51 -9
  24. package/dist/agents/prompts/index.js.map +1 -1
  25. package/dist/agents/tools.d.ts +2 -1
  26. package/dist/agents/tools.d.ts.map +1 -1
  27. package/dist/agents/tools.js +4 -5
  28. package/dist/agents/tools.js.map +1 -1
  29. package/dist/agents/workspace.d.ts.map +1 -1
  30. package/dist/agents/workspace.js +12 -9
  31. package/dist/agents/workspace.js.map +1 -1
  32. package/dist/onboarding/settings.d.ts +18 -7
  33. package/dist/onboarding/settings.d.ts.map +1 -1
  34. package/dist/onboarding/settings.js +38 -26
  35. package/dist/onboarding/settings.js.map +1 -1
  36. package/dist/providers/openai-codex.d.ts +3 -4
  37. package/dist/providers/openai-codex.d.ts.map +1 -1
  38. package/dist/providers/openai-codex.js +1 -9
  39. package/dist/providers/openai-codex.js.map +1 -1
  40. package/dist/schema.d.ts +4 -3
  41. package/dist/schema.d.ts.map +1 -1
  42. package/dist/schema.js +2 -8
  43. package/dist/schema.js.map +1 -1
  44. package/dist/thinking.d.ts +33 -0
  45. package/dist/thinking.d.ts.map +1 -0
  46. package/dist/thinking.js +58 -0
  47. package/dist/thinking.js.map +1 -0
  48. package/dist/tools/index.d.ts +1 -1
  49. package/dist/tools/index.d.ts.map +1 -1
  50. package/dist/tools/index.js +2 -2
  51. package/dist/tools/web-search.d.ts +81 -2
  52. package/dist/tools/web-search.d.ts.map +1 -1
  53. package/dist/tools/web-search.js +98 -4
  54. package/dist/tools/web-search.js.map +1 -1
  55. package/dist/workflows/register-primitives.d.ts +4 -4
  56. package/dist/workflows/register-primitives.d.ts.map +1 -1
  57. package/dist/workflows/register-primitives.js +5 -4
  58. package/dist/workflows/register-primitives.js.map +1 -1
  59. package/package.json +10 -9
@@ -1,7 +1,6 @@
1
- import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';
2
1
  import type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';
3
2
  import type { RequestContext } from '@mastra/core/request-context';
4
- import type { ThinkingLevel } from '../providers/openai-codex.js';
3
+ import type { ThinkingLevelSetting } from '../thinking.js';
5
4
  import { MastraCodeGateway } from './mastracode-gateway.js';
6
5
  import type { MastraCodeGatewayOptions } from './mastracode-gateway.js';
7
6
  export { getAnthropicApiKey, getOpenAIApiKey, MASTRACODE_GATEWAY_ID, MastraCodeGateway, remapOpenAIModelForCodexOAuth, resolveAuth, } from './mastracode-gateway.js';
@@ -29,10 +28,18 @@ export declare function resolveModelId(modelId: string): string;
29
28
  * - For all other providers: Uses Mastra's model router (models.dev gateway)
30
29
  */
31
30
  export declare function resolveModel(modelId: string, options?: {
32
- thinkingLevel?: ThinkingLevel;
31
+ thinkingLevel?: ThinkingLevelSetting;
33
32
  remapForCodexOAuth?: boolean;
34
33
  requestContext?: RequestContext;
35
34
  }): GatewayLanguageModel;
35
+ export interface ThinkingRequestContext {
36
+ state?: {
37
+ thinkingLevel?: unknown;
38
+ };
39
+ session?: {
40
+ modeId?: string;
41
+ };
42
+ }
36
43
  /**
37
44
  * Resolve the effective thinking level for the current request.
38
45
  *
@@ -46,7 +53,7 @@ export declare function resolveModel(modelId: string, options?: {
46
53
  * apply to the next request of every session — including automated
47
54
  * (rule-driven) Factory runs that nobody ever opens interactively.
48
55
  */
49
- export declare function resolveRequestThinkingLevel(agentControllerContext: AgentControllerRequestContext<any> | undefined, settingsPath?: string): ThinkingLevel;
56
+ export declare function resolveRequestThinkingLevel(agentControllerContext: ThinkingRequestContext | undefined, settingsPath?: string): ThinkingLevelSetting;
50
57
  /**
51
58
  * Dynamic model function that reads the current model from controller state.
52
59
  * This allows runtime model switching via the /models picker.
@@ -1 +1 @@
1
- {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/agents/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAOnE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAGlE,OAAO,EAGL,iBAAiB,EAGlB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAExE,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EACjB,6BAA6B,EAC7B,WAAW,GACZ,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAClG,OAAO,EACL,0BAA0B,E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;IAAC,cAAc,CAAC,EAAE,cAAc,CAAA;CAAE,GAChH,oBAAoB,CA+EtB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;IACpC,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC/B;AACD;;;;;;;;;;;;GAYG;AAEH,wBAAgB,2BAA2B,CACzC,sBAAsB,EAAE,sBAAsB,GAAG,SAAS,EAC1D,YAAY,CAAC,EAAE,MAAM,GACpB,oBAAoB,CAKtB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,CAoBf;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
@@ -1,3 +1,4 @@
1
+ import { isThinkingLevelSetting } from "../thinking.js";
1
2
  import { loadSettings, resolveDefaultThinkingLevel, stripMastraCodeCustomProviderPrefix } from "../onboarding/settings.js";
2
3
  import { hasCredentialStoreProvider, resolveCredentialStore, resolveTenantFromRequestContext, setCredentialStoreProvider } from "./credential-resolver.js";
3
4
  import { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from "../providers/amazon-bedrock-gateway.js";
@@ -104,7 +105,7 @@ function resolveModel(modelId, options) {
104
105
  */
105
106
  function resolveRequestThinkingLevel(agentControllerContext, settingsPath) {
106
107
  const override = agentControllerContext?.state?.thinkingLevel;
107
- if (override !== void 0) return override;
108
+ if (isThinkingLevelSetting(override)) return override;
108
109
  const modeId = agentControllerContext?.session?.modeId;
109
110
  return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;
110
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevel; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\nexport function resolveRequestThinkingLevel(\n agentControllerContext: AgentControllerRequestContext<any> | undefined,\n settingsPath?: string,\n): ThinkingLevel {\n const override = agentControllerContext?.state?.thinkingLevel as ThinkingLevel | undefined;\n if (override !== undefined) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;AA8CA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAgB,wBAAwB,SAAsD;CAC5F,OAAO,IAAI,kBAAkB,OAAO;AACtC;AAEA,SAAgB,qCAAqC,SAAsC;CACzF,OAAO,mBAAmB,oBACtB,QAAQ,2BAA2B,IACnC,kBAAkB,2BAA2B,OAAO;AAC1D;;;;;;AAOA,SAAgB,eAAe,SAAyB;CACtD,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,aACd,SACA,SACsB;CACtB,kBAAkB;CAClB,MAAM,UAAU,0BAA0B,SAAS,cAAc;CACjE,MAAM,WAAW,aAAa;CAK9B,MAAM,sBAAsB,GAAG,sBAAs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H;;;;;;;;;;;;;;AAeA,SAAgB,4BACd,wBACA,cACe;CACf,MAAM,WAAW,wBAAwB,OAAO;CAChD,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,SAAS,wBAAwB,SAAS;CAChD,OAAO,4BAA4B,aAAa,YAAY,GAAG,MAAM,CAAC,CAAC;AACzE;;;;;AAMA,SAAgB,gBACd,EAAE,kBACF,cACe;CACf,MAAM,yBAAyB,eAAe,IAAI,YAAY;CAE9D,MAAM,UAAU,wBAAwB,SAAS;CACjD,IAAI,CAAC,SAAS;EAKZ,IAAI,CAAC,wBACH,MAAM,IAAI,MACR,qHACF;EAEF,MAAM,IAAI,MAAM,yDAAyD;CAC3E;CAIA,OAAO,aAAa,SAAS;EAAE,eAFT,4BAA4B,wBAAwB,YAE/B;EAAG,oBAAoB;EAAM;CAAe,CAAC;AAC1F;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
1
+ {"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { GatewayLanguageModel, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport {\n loadSettings,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport { resolveCredentialStore } from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: { thinkingLevel?: ThinkingLevelSetting; remapForCodexOAuth?: boolean; requestContext?: RequestContext },\n): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Bedrock was previously cataloged under the MastraCode gateway namespace\n // (`mastracode/amazon-bedrock/<model>`). Normalize any legacy saved ids to the\n // standalone `amazon-bedrock/<model>` form so they resolve through the\n // dedicated Bedrock gateway.\n const bedrockLegacyPrefix = `${MASTRACODE_GATEWAY_ID}/amazon-bedrock/`;\n const bedrockNormalizedInput = modelId.startsWith(bedrockLegacyPrefix)\n ? modelId.slice(MASTRACODE_GATEWAY_ID.length + 1)\n : modelId;\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(bedrockNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = MastraCodeGateway.getMastraGatewayApiKey();\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n // Deployed web registers a per-tenant credential store provider; when the\n // request carries an authenticated tenant, resolve credentials through the\n // caller's own store (user > org > env). Undefined = global AuthStorage.\n const credentialStore = resolveCredentialStore(options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. Per-mode default from settings (`models.modeThinkingDefaults[mode]`).\n * 3. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\n\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model from controller state.\n * This allows runtime model switching via the /models picker.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel {\n const agentControllerContext = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n\n const modelId = agentControllerContext?.session?.modelId;\n if (!modelId) {\n // A missing controller context means the run was started without session\n // request context at all (e.g. a signal delivered to an idle thread) —\n // \"use /models\" would mislead there, the user's selection was never the\n // problem.\n if (!agentControllerContext) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(agentControllerContext, settingsPath);\n\n return resolveModel(modelId, { thinkingLevel, remapForCodexOAuth: true, requestContext });\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;AA+CA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAgB,wBAAwB,SAAsD;CAC5F,OAAO,IAAI,kBAAkB,OAAO;AACtC;AAEA,SAAgB,qCAAqC,SAAsC;CACzF,OAAO,mBAAmB,oBACtB,QAAQ,2BAA2B,IACnC,kBAAkB,2BAA2B,OAAO;AAC1D;;;;;;AAOA,SAAgB,eAAe,SAAyB;CACtD,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,aACd,SACA,SACsB;CACtB,kBAAkB;CAClB,MAAM,UAAU,0BAA0B,SAAS,cAAc;CACjE,MAAM,WAAW,aAAa;CAK9B,MAAM,sBAAsB,GAAG,sBAAsB;CACrD,MAAM,yBAAyB,QAAQ,WAAW,mBAAmB,IACjE,QAAQ,MAAM,sBAAsB,SAAS,CAAC,IAC9C;CAIJ,MAAM,kBAAkB,uBAAuB,SAAS,cAAc,KAAK,SAAS;CAOpF,MAAM,kBAAkB,oCAAoC,wBAAwB,eAAe;CACnG,MAAM,uBAAuB,gBAAgB,WAAW,qBAAqB;CAC7E,MAAM,oBAAoB,yBAAyB,eAAe;CAClE,MAAM,CAAC,YAAY,GAAG,cAAc,kBAAkB,MAAM,GAAG;CAC/D,MAAM,cAAc,WAAW,KAAK,GAAG;CACvC,IAAI,CAAC,cAAc,CAAC,aAClB,MAAM,IAAI,MAAM,qBAAqB,SAAS;CAGhD,I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E;CAIA,OAAO,aAAa,SAAS;EAAE,eAFT,4BAA4B,wBAAwB,YAE/B;EAAG,oBAAoB;EAAM;CAAe,CAAC;AAC1F;;;;;;;;;;;;;;;AAgBA,SAAgB,kBACd,EAAE,kBACF,cAC2B;CAC3B,MAAM,eAAe,aAAa,YAAY,CAAC,CAAC,OAAO;CACvD,IAAI,CAAC,cAAc,OAAO,KAAA;CAC1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
@@ -54,6 +54,15 @@ export declare function loadAgentInstructions(projectPath: string, configDirName
54
54
  skipGlobal?: boolean;
55
55
  }): InstructionSource[];
56
56
  export declare function getStaticallyLoadedInstructionPaths(projectPath: string, configDirName?: string, projectReader?: InstructionFileReader): string[];
57
+ /** Heading the agent-instructions block is introduced by in the system prompt. */
58
+ export declare const AGENT_INSTRUCTIONS_HEADING = "# Agent Instructions";
59
+ /**
60
+ * Format a single instruction source as it appears in the system prompt.
61
+ *
62
+ * Exported so callers that attribute prompt cost per source (the `/context`
63
+ * audit) measure the exact block that is sent rather than reconstructing it.
64
+ */
65
+ export declare function formatInstructionSource(source: InstructionSource): string;
57
66
  /**
58
67
  * Format loaded instructions into a string for the system prompt.
59
68
  */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-instructions.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/agent-instructions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAoBH,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC5B,6EAA6E;IAC7E,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,MAAM,WAAW,qBAAqB;IACpC,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAC9B,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAOD;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,qBAAqB,CA+BrG;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,MAAM,GACV;IACD,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACtC,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACvC,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;CACpC,CA4CA;AAgBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,GAAE,qBAA2C,EAC1D,EAAE,UAAkB,EAAE,GAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACpD,iBAAiB,EAAE,CAwDrB;AAED,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,CAAC,EAAE,qBAAqB,GACpC,MAAM,EAAE,CAEV;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,iBAAiB,EAAE,GAAG,MAAM,CAU5E"}
1
+ {"version":3,"file":"agent-instructions.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/agent-instructions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAoBH,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC5B,6EAA6E;IAC7E,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,MAAM,WAAW,qBAAqB;IACpC,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAC9B,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAOD;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,qBAAqB,CA+BrG;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,MAAM,GACV;IACD,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACtC,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACvC,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;CACpC,CA4CA;AAgBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,GAAE,qBAA2C,EAC1D,EAAE,UAAkB,EAAE,GAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACpD,iBAAiB,EAAE,CAwDrB;AAED,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,CAAC,EAAE,qBAAqB,GACpC,MAAM,EAAE,CAEV;AAED,kFAAkF;AAClF,eAAO,MAAM,0BAA0B,yBAAyB,CAAC;AAEjE;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAIzE;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,iBAAiB,EAAE,GAAG,MAAM,CAM5E"}
@@ -186,16 +186,26 @@ function loadAgentInstructions(projectPath, configDirName = DEFAULT_CONFIG_DIR,
186
186
  function getStaticallyLoadedInstructionPaths(projectPath, configDirName = DEFAULT_CONFIG_DIR, projectReader) {
187
187
  return loadAgentInstructions(projectPath, configDirName, projectReader).map((source) => normalize(source.path));
188
188
  }
189
+ /** Heading the agent-instructions block is introduced by in the system prompt. */
190
+ const AGENT_INSTRUCTIONS_HEADING = "# Agent Instructions";
191
+ /**
192
+ * Format a single instruction source as it appears in the system prompt.
193
+ *
194
+ * Exported so callers that attribute prompt cost per source (the `/context`
195
+ * audit) measure the exact block that is sent rather than reconstructing it.
196
+ */
197
+ function formatInstructionSource(source) {
198
+ return `<!-- ${source.scope === "global" ? "Global" : "Project"} instructions from ${source.ref ? `${source.path} (at ref ${source.ref})` : source.path} -->\n${source.content}`;
199
+ }
189
200
  /**
190
201
  * Format loaded instructions into a string for the system prompt.
191
202
  */
192
203
  function formatAgentInstructions(sources) {
193
204
  if (sources.length === 0) return "";
194
- return `\n# Agent Instructions\n\n${sources.map((source) => {
195
- return `<!-- ${source.scope === "global" ? "Global" : "Project"} instructions from ${source.ref ? `${source.path} (at ref ${source.ref})` : source.path} -->\n${source.content}`;
196
- }).join("\n\n")}\n`;
205
+ const sections = sources.map(formatInstructionSource);
206
+ return `\n${AGENT_INSTRUCTIONS_HEADING}\n\n${sections.join("\n\n")}\n`;
197
207
  }
198
208
  //#endregion
199
- export { createGitRefInstructionReader, createGitRefReminderReader, formatAgentInstructions, getStaticallyLoadedInstructionPaths, loadAgentInstructions };
209
+ export { AGENT_INSTRUCTIONS_HEADING, createGitRefInstructionReader, createGitRefReminderReader, formatAgentInstructions, formatInstructionSource, getStaticallyLoadedInstructionPaths, loadAgentInstructions };
200
210
 
201
211
  //# sourceMappingURL=agent-instructions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, normalize, relative, sep } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n /** Git ref the content was read from, when not read off the working tree. */\n ref?: string;\n}\n\n/**\n * Reads project-scope instruction files. The default implementation reads the\n * working tree via `fs`; alternative readers can serve content from another\n * source (e.g. a trusted git ref) while keeping working-tree paths as the\n * addressing scheme.\n */\nexport interface InstructionFileReader {\n exists(path: string): boolean;\n read(path: string): string;\n /** Git ref backing this reader, recorded on the loaded sources. */\n ref?: string;\n}\n\nconst fsInstructionReader: InstructionFileReader = {\n exists: path => existsSync(path),\n read: path => readFileSync(path, 'utf-8'),\n};\n\n/**\n * Create a reader that serves instruction files from a git ref instead of the\n * working tree. Paths are still addressed as working-tree paths under\n * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted\n * checkout (e.g. a PR branch under review) cannot influence what is loaded.\n * Tries `origin/<ref>` first (remote truth), then the local ref. Any git\n * failure (missing ref, missing file, no repo) reports the file as absent.\n */\nexport function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader {\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, path);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (rel === null) return null;\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'show', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n } catch {\n // Ref or file missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n ref,\n exists: path => show(path) !== null,\n read: path => {\n const content = show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\n/**\n * Reader for the reactive reminder channel (AgentsMDInjector) that serves\n * paths under `projectPath` from a trusted git ref. Paths outside the project\n * fall back to the operator machine's filesystem (those are trusted); paths\n * inside the project are only ever resolved against the ref, never the\n * working tree, so an untrusted checkout cannot feed content in.\n */\nexport function createGitRefReminderReader(\n projectPath: string,\n ref: string,\n): {\n pathExists: (path: string) => boolean;\n isDirectory: (path: string) => boolean;\n readFile: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, normalize(path));\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'cat-file', '-t', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n } catch {\n // Ref or object missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n pathExists: path => {\n const rel = toRelative(path);\n if (rel === null) return existsSync(path);\n return objectType(rel) !== null;\n },\n isDirectory: path => {\n const rel = toRelative(path);\n if (rel === null) {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n }\n return objectType(rel) === 'tree';\n },\n readFile: path => {\n const rel = toRelative(path);\n if (rel === null) return readFileSync(path, 'utf-8');\n return gitReader.read(path);\n },\n };\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string, reader: InstructionFileReader = fsInstructionReader): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (reader.exists(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n *\n * `projectReader` controls where project-scope content comes from (defaults to\n * the working tree). Global instructions read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath, projectReader);\n if (filePath) {\n try {\n const content = projectReader.read(filePath).trim();\n if (content) {\n sources.push({\n path: filePath,\n content,\n scope: 'project',\n ...(projectReader.ref ? { ref: projectReader.ref } : {}),\n });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader?: InstructionFileReader,\n): string[] {\n return loadAgentInstructions(projectPath, configDirName, projectReader).map(source => normalize(source.path));\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(source => {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n const origin = source.ref ? `${source.path} (at ref ${source.ref})` : source.path;\n return `<!-- ${label} instructions from ${origin} -->\\n${source.content}`;\n });\n\n return `\\n# Agent Instructions\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;AACF;AAEA,MAAM,mBAAmB;CAAC;CAAW;CAAe;CAAkB;AAAoB;AAuB1F,MAAM,sBAA6C;CACjD,SAAQ,SAAQ,WAAW,IAAI;CAC/B,OAAM,SAAQ,aAAa,MAAM,OAAO;AAC1C;;;;;;;;;AAUA,SAAgB,8BAA8B,aAAqB,KAAoC;CACrG,MAAM,cAAc,SAAgC;EAClD,MAAM,MAAM,SAAS,aAAa,IAAI;EACtC,IAAI,CAAC,OAAO,IAAI,WAAW,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;EAC5D,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;CAChC;CACA,MAAM,QAAQ,SAAgC;EAC5C,MAAM,MAAM,WAAW,IAAI;EAC3B,IAAI,QAAQ,MAAM,OAAO;EACzB,KAAK,MAAM,aAAa,CAAC,UAAU,OAAO,GAAG,GAC3C,IAAI;GACF,OAAO,aAAa,OAAO;IAAC;IAAM;IAAa;IAAQ,GAAG,UAAU,GAAG;GAAK,GAAG;IAC7E,UAAU;IACV,OAAO;KAAC;KAAU;KAAQ;IAAQ;IAClC,WAAW,OAAO;GACpB,CAAC;EACH,QAAQ,CAER;EAEF,OAAO;CACT;CACA,OAAO;EACL;EACA,SAAQ,SAAQ,KAAK,IAAI,MAAM;EAC/B,OAAM,SAAQ;GAC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AC,KAAI,WAAU,UAAU,OAAO,IAAI,CAAC;AAC9G;;;;AAKA,SAAgB,wBAAwB,SAAsC;CAC5E,IAAI,QAAQ,WAAW,GAAG,OAAO;CAQjC,OAAO,6BANU,QAAQ,KAAI,WAAU;EAGrC,OAAO,QAFO,OAAO,UAAU,WAAW,WAAW,UAEhC,qBADN,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO,KAC5B,QAAQ,OAAO;CAClE,CAE2C,CAAC,CAAC,KAAK,MAAM,EAAE;AAC5D"}
1
+ {"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, normalize, relative, sep } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n /** Git ref the content was read from, when not read off the working tree. */\n ref?: string;\n}\n\n/**\n * Reads project-scope instruction files. The default implementation reads the\n * working tree via `fs`; alternative readers can serve content from another\n * source (e.g. a trusted git ref) while keeping working-tree paths as the\n * addressing scheme.\n */\nexport interface InstructionFileReader {\n exists(path: string): boolean;\n read(path: string): string;\n /** Git ref backing this reader, recorded on the loaded sources. */\n ref?: string;\n}\n\nconst fsInstructionReader: InstructionFileReader = {\n exists: path => existsSync(path),\n read: path => readFileSync(path, 'utf-8'),\n};\n\n/**\n * Create a reader that serves instruction files from a git ref instead of the\n * working tree. Paths are still addressed as working-tree paths under\n * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted\n * checkout (e.g. a PR branch under review) cannot influence what is loaded.\n * Tries `origin/<ref>` first (remote truth), then the local ref. Any git\n * failure (missing ref, missing file, no repo) reports the file as absent.\n */\nexport function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader {\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, path);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (rel === null) return null;\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'show', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n } catch {\n // Ref or file missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n ref,\n exists: path => show(path) !== null,\n read: path => {\n const content = show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\n/**\n * Reader for the reactive reminder channel (AgentsMDInjector) that serves\n * paths under `projectPath` from a trusted git ref. Paths outside the project\n * fall back to the operator machine's filesystem (those are trusted); paths\n * inside the project are only ever resolved against the ref, never the\n * working tree, so an untrusted checkout cannot feed content in.\n */\nexport function createGitRefReminderReader(\n projectPath: string,\n ref: string,\n): {\n pathExists: (path: string) => boolean;\n isDirectory: (path: string) => boolean;\n readFile: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, normalize(path));\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'cat-file', '-t', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n } catch {\n // Ref or object missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n pathExists: path => {\n const rel = toRelative(path);\n if (rel === null) return existsSync(path);\n return objectType(rel) !== null;\n },\n isDirectory: path => {\n const rel = toRelative(path);\n if (rel === null) {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n }\n return objectType(rel) === 'tree';\n },\n readFile: path => {\n const rel = toRelative(path);\n if (rel === null) return readFileSync(path, 'utf-8');\n return gitReader.read(path);\n },\n };\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string, reader: InstructionFileReader = fsInstructionReader): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (reader.exists(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n *\n * `projectReader` controls where project-scope content comes from (defaults to\n * the working tree). Global instructions read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath, projectReader);\n if (filePath) {\n try {\n const content = projectReader.read(filePath).trim();\n if (content) {\n sources.push({\n path: filePath,\n content,\n scope: 'project',\n ...(projectReader.ref ? { ref: projectReader.ref } : {}),\n });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader?: InstructionFileReader,\n): string[] {\n return loadAgentInstructions(projectPath, configDirName, projectReader).map(source => normalize(source.path));\n}\n\n/** Heading the agent-instructions block is introduced by in the system prompt. */\nexport const AGENT_INSTRUCTIONS_HEADING = '# Agent Instructions';\n\n/**\n * Format a single instruction source as it appears in the system prompt.\n *\n * Exported so callers that attribute prompt cost per source (the `/context`\n * audit) measure the exact block that is sent rather than reconstructing it.\n */\nexport function formatInstructionSource(source: InstructionSource): string {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n const origin = source.ref ? `${source.path} (at ref ${source.ref})` : source.path;\n return `<!-- ${label} instructions from ${origin} -->\\n${source.content}`;\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(formatInstructionSource);\n\n return `\\n${AGENT_INSTRUCTIONS_HEADING}\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;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EAAE;AACrE"}
@@ -11,9 +11,37 @@ export interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {
11
11
  currentDate: string;
12
12
  workingDir: string;
13
13
  }
14
+ /**
15
+ * One labeled piece of the assembled system prompt.
16
+ *
17
+ * The system prompt is a single string by the time it reaches the model, which
18
+ * makes it impossible to say which configuration source is responsible for
19
+ * which share of the context window. Building it as labeled sections and
20
+ * joining them at the end keeps that attribution available to the `/context`
21
+ * audit while guaranteeing the audit measures the exact text that is sent —
22
+ * a parallel "describe the prompt" path would drift and report numbers for a
23
+ * prompt that is no longer assembled this way.
24
+ */
25
+ export interface PromptSection {
26
+ /** Stable identifier, unique within a single build. */
27
+ id: string;
28
+ /** Human-readable label for display. */
29
+ label: string;
30
+ /** Optional provenance (e.g. the instruction file path). */
31
+ detail?: string;
32
+ /** The exact text contributed to the prompt. */
33
+ content: string;
34
+ }
35
+ /** Join prompt sections into the final system prompt string. */
36
+ export declare function joinPromptSections(sections: PromptSection[]): string;
14
37
  /**
15
38
  * Build the full system prompt for a given mode and context.
16
39
  * Combines the base prompt with mode-specific instructions.
17
40
  */
18
41
  export declare function buildFullPrompt(ctx: PromptContext): string;
42
+ /**
43
+ * Build the system prompt as labeled sections. `buildFullPrompt` is the join of
44
+ * these, so the two can never disagree about what the model receives.
45
+ */
46
+ export declare function buildFullPromptSections(ctx: PromptContext): PromptSection[];
19
47
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAWpF,MAAM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AAC,GAAG,EAAE,aAAa,GAAG,aAAa,EAAE,CAsG3E"}
@@ -1,10 +1,12 @@
1
+ import { loadSettings, resolveLspSetting } from "../../onboarding/settings.js";
1
2
  import { buildModePrompt, buildModePromptFn } from "./build.js";
2
3
  import { getLocalPlansRelativeDir } from "../../utils/plans.js";
3
4
  import { planModePrompt } from "./plan.js";
4
5
  import { fastModePrompt } from "./fast.js";
5
- import { hasTavilyKey } from "../../tools/web-search.js";
6
+ import { MC_TOOLS } from "../../tool-names.js";
7
+ import { hasParallelKey, hasTavilyKey } from "../../tools/web-search.js";
6
8
  import "../../tools/index.js";
7
- import { createGitRefInstructionReader, formatAgentInstructions, loadAgentInstructions } from "./agent-instructions.js";
9
+ import { AGENT_INSTRUCTIONS_HEADING, createGitRefInstructionReader, formatInstructionSource, loadAgentInstructions } from "./agent-instructions.js";
8
10
  import { modelSpecificPrompts } from "./model.js";
9
11
  import { buildToolGuidance } from "./tool-guidance.js";
10
12
  import { buildBasePrompt } from "@mastra/core/coding-agent";
@@ -14,18 +16,30 @@ const modePrompts = {
14
16
  plan: planModePrompt,
15
17
  fast: fastModePrompt
16
18
  };
19
+ /** Join prompt sections into the final system prompt string. */
20
+ function joinPromptSections(sections) {
21
+ return sections.map((section) => section.content).filter(Boolean).join("\n\n");
22
+ }
17
23
  /**
18
24
  * Build the full system prompt for a given mode and context.
19
25
  * Combines the base prompt with mode-specific instructions.
20
26
  */
21
27
  function buildFullPrompt(ctx) {
28
+ return joinPromptSections(buildFullPromptSections(ctx));
29
+ }
30
+ /**
31
+ * Build the system prompt as labeled sections. `buildFullPrompt` is the join of
32
+ * these, so the two can never disagree about what the model receives.
33
+ */
34
+ function buildFullPromptSections(ctx) {
22
35
  const modelId = ctx.modelId;
23
- const hasWebSearch = hasTavilyKey() || !!modelId && modelId.startsWith("anthropic/");
36
+ const hasWebSearch = hasParallelKey() || hasTavilyKey() || !!modelId && (modelId.startsWith("anthropic/") || modelId.startsWith("openai/"));
24
37
  const deniedTools = /* @__PURE__ */ new Set();
25
38
  const permRules = ctx.state?.permissionRules;
26
39
  if (permRules?.tools) {
27
40
  for (const [name, policy] of Object.entries(permRules.tools)) if (policy === "deny") deniedTools.add(name);
28
41
  }
42
+ if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);
29
43
  const factoryProjectId = typeof ctx.state?.factoryProjectId === "string" ? ctx.state.factoryProjectId : void 0;
30
44
  const toolGuidance = buildToolGuidance(ctx.modeId, {
31
45
  hasWebSearch,
@@ -55,14 +69,42 @@ function buildFullPrompt(ctx) {
55
69
  exists: () => false,
56
70
  read: () => ""
57
71
  } : void 0;
72
+ const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader, { skipGlobal: skipGlobalInstructions });
73
+ const instructionSections = instructionSources.map((source, index) => {
74
+ const isFirst = index === 0;
75
+ const isLast = index === instructionSources.length - 1;
76
+ let content = formatInstructionSource(source);
77
+ if (isFirst) content = `${AGENT_INSTRUCTIONS_HEADING}\n\n${content}`;
78
+ if (isLast) content = content.trimEnd();
79
+ return {
80
+ id: `agent-instructions:${source.path}:${index}`,
81
+ label: `${source.scope === "global" ? "Global" : "Project"} instructions`,
82
+ detail: source.ref ? `${source.path} (at ref ${source.ref})` : source.path,
83
+ content
84
+ };
85
+ });
58
86
  return [
59
- base,
60
- formatAgentInstructions(loadAgentInstructions(ctx.workingDir, configDir, projectReader, { skipGlobal: skipGlobalInstructions })).trim(),
61
- modelSpecific.trim(),
62
- modeSpecific.trim()
63
- ].filter(Boolean).join("\n\n");
87
+ {
88
+ id: "base-prompt",
89
+ label: "Base system prompt",
90
+ content: base
91
+ },
92
+ ...instructionSections,
93
+ {
94
+ id: "model-prompt",
95
+ label: "Model-specific prompt",
96
+ detail: ctx.modelId,
97
+ content: modelSpecific.trim()
98
+ },
99
+ {
100
+ id: "mode-prompt",
101
+ label: "Mode prompt",
102
+ detail: ctx.modeId,
103
+ content: modeSpecific.trim()
104
+ }
105
+ ].filter((section) => Boolean(section.content));
64
106
  }
65
107
  //#endregion
66
- export { buildFullPrompt, buildModePrompt, buildModePromptFn, fastModePrompt, planModePrompt };
108
+ export { buildFullPrompt, buildFullPromptSections, buildModePrompt, buildModePromptFn, fastModePrompt, joinPromptSections, planModePrompt };
67
109
 
68
110
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport { hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport { loadAgentInstructions, formatAgentInstructions, createGitRefInstructionReader } from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n // Determine whether web search tools are available\n const modelId = ctx.modelId;\n const hasWebSearch = hasTavilyKey() || (!!modelId && modelId.startsWith('anthropic/'));\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // Build mode-aware tool guidance\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const toolGuidance = buildToolGuidance(ctx.modeId, {\n hasWebSearch,\n deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir,\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n activePlan: ctx.state?.activePlan,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific = (typeof entry === 'function' ? entry(ctx) : entry) ?? '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files.\n // Untrusted checkouts (e.g. a PR branch under review) never read\n // project-scope files off the working tree: their AGENTS.md is\n // attacker-writable and would otherwise land in the system prompt as\n // trusted configuration. When the session carries a trusted base ref, the\n // project instructions are served from that ref instead (`git show`);\n // without one, project-scope files are skipped entirely. Home-directory\n // (global) instructions belong to whoever owns the machine, so hosts that\n // run sessions for someone else opt out of them entirely.\n const configDir = ctx.state?.configDir as string | undefined;\n const untrustedCheckout = ctx.state?.untrustedCheckout === true;\n const skipGlobalInstructions = ctx.state?.skipGlobalInstructions === true;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const projectReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(ctx.workingDir, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader, {\n skipGlobal: skipGlobalInstructions,\n });\n const instructionsSection = formatAgentInstructions(instructionSources);\n\n const sections = [base, instructionsSection.trim(), modelSpecific.trim(), modeSpecific.trim()].filter(Boolean);\n\n return sections.join('\\n\\n');\n}\n"],"mappings":";;;;;;;;;;;AA2BA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;;;;AAMA,SAAgB,gBAAgB,KAA4B;CAE1D,MAAM,UAAU,IAAI;CACpB,MAAM,eAAe,aAAa,KAAM,CAAC,CAAC,WAAW,QAAQ,WAAW,YAAY;CAGpF,MAAM,8BAAc,IAAI,IAAY;CACpC,MAAM,YAAY,IAAI,OAAO;CAC7B,IAAI,WAAW,OACR;OAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,KAAK,GACzD,IAAI,WAAW,QAAQ,YAAY,IAAI,IAAI;CAAA;CAK/C,MAAM,mBAAmB,OAAO,IAAI,OAAO,qBAAqB,WAAW,IAAI,MAAM,mBAAmB,KAAA;CACxG,MAAM,eAAe,kBAAkB,IAAI,QAAQ;EACjD;EACA;EACA,UAAU,yBAAyB,EAAE,iBAAiB,CAAC;CACzD,CAAC;CAgBD,MAAM,OAAO,gBAAgB;EAZ3B,aAAa,IAAI;EACjB,aAAa,IAAI,eAAe;EAChC,WAAW,IAAI;EACf,UAAU,QAAQ;EAClB,gBAAgB,IAAI;EACpB,MAAM,IAAI;EACV,MAAM,IAAI;EACV,SAAS,IAAI;EACb,YAAY,IAAI,OAAO;EACvB;CAGiC,CAAC;CACpC,MAAM,QAAQ,YAAY,IAAI,WAAW,YAAY;CACrD,MAAM,gBAAgB,OAAO,UAAU,aAAa,MAAM,GAAG,IAAI,UAAU;CAC3E,MAAM,gBAAgB,IAAI,UACrB,qBAAqB,IAAI,YAAiD,KAC3E;CAgBJ,MAAM,YAAY,IAAI,OAAO;CAC7B,MAAM,oBAAoB,IAAI,OAAO,sBAAsB;CAC3D,MAAM,yBAAyB,IAAI,OAAO,2BAA2B;CACrE,MAAM,UAAU,OAAO,IAAI,OAAO,YAAY,WAAW,IAAI,MAAM,UAAU,KAAA;CAC7E,MAAM,gBAAgB,oBAClB,UACE,8BAA8B,IAAI,YAAY,OAAO,IACrD;EAAE,cAAc;EAAO,YAAY;CAAG,IACxC,KAAA;CAQJ,OAFiB;EAAC;EAFU,wBAHD,sBAAsB,IAAI,YAAY,WAAW,eAAe,EACzF,YAAY,uBACd,CACqE,CAE3B,CAAC,CAAC,KAAK;EAAG,cAAc,KAAK;EAAG,aAAa,KAAK;CAAC,CAAC,CAAC,OAAO,OAExF,CAAC,CAAC,KAAK,MAAM;AAC7B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport { loadSettings, resolveLspSetting } from '../../onboarding/settings.js';\nimport { MC_TOOLS } from '../../tool-names.js';\nimport { hasParallelKey, hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport {\n loadAgentInstructions,\n formatInstructionSource,\n createGitRefInstructionReader,\n AGENT_INSTRUCTIONS_HEADING,\n} from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * One labeled piece of the assembled system prompt.\n *\n * The system prompt is a single string by the time it reaches the model, which\n * makes it impossible to say which configuration source is responsible for\n * which share of the context window. Building it as labeled sections and\n * joining them at the end keeps that attribution available to the `/context`\n * audit while guaranteeing the audit measures the exact text that is sent —\n * a parallel \"describe the prompt\" path would drift and report numbers for a\n * prompt that is no longer assembled this way.\n */\nexport interface PromptSection {\n /** Stable identifier, unique within a single build. */\n id: string;\n /** Human-readable label for display. */\n label: string;\n /** Optional provenance (e.g. the instruction file path). */\n detail?: string;\n /** The exact text contributed to the prompt. */\n content: string;\n}\n\n/** Join prompt sections into the final system prompt string. */\nexport function joinPromptSections(sections: PromptSection[]): string {\n return sections\n .map(section => section.content)\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n return joinPromptSections(buildFullPromptSections(ctx));\n}\n\n/**\n * Build the system prompt as labeled sections. `buildFullPrompt` is the join of\n * these, so the two can never disagree about what the model receives.\n */\nexport function buildFullPromptSections(ctx: PromptContext): PromptSection[] {\n // Determine whether web search tools are available\n const modelId = ctx.modelId;\n const hasWebSearch =\n hasParallelKey() ||\n hasTavilyKey() ||\n (!!modelId && (modelId.startsWith('anthropic/') || modelId.startsWith('openai/')));\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // LSP is opt-in — when it is off the tool is never registered, so its\n // guidance must not be advertised either.\n if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);\n\n // Build mode-aware tool guidance\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const toolGuidance = buildToolGuidance(ctx.modeId, {\n hasWebSearch,\n deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir,\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n activePlan: ctx.state?.activePlan,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific = (typeof entry === 'function' ? entry(ctx) : entry) ?? '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files.\n // Untrusted checkouts (e.g. a PR branch under review) never read\n // project-scope files off the working tree: their AGENTS.md is\n // attacker-writable and would otherwise land in the system prompt as\n // trusted configuration. When the session carries a trusted base ref, the\n // project instructions are served from that ref instead (`git show`);\n // without one, project-scope files are skipped entirely. Home-directory\n // (global) instructions belong to whoever owns the machine, so hosts that\n // run sessions for someone else opt out of them entirely.\n const configDir = ctx.state?.configDir as string | undefined;\n const untrustedCheckout = ctx.state?.untrustedCheckout === true;\n const skipGlobalInstructions = ctx.state?.skipGlobalInstructions === true;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const projectReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(ctx.workingDir, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader, {\n skipGlobal: skipGlobalInstructions,\n });\n // Emitted per source so each AGENTS.md/CLAUDE.md can be costed individually.\n // The heading rides on the first source's section, which is exactly how\n // `formatAgentInstructions` lays the block out, so joining the sections\n // reproduces its output byte for byte.\n const instructionSections: PromptSection[] = instructionSources.map((source, index) => {\n const isFirst = index === 0;\n const isLast = index === instructionSources.length - 1;\n let content = formatInstructionSource(source);\n if (isFirst) content = `${AGENT_INSTRUCTIONS_HEADING}\\n\\n${content}`;\n // The block as a whole used to be trimmed, which only ever affected the\n // trailing whitespace of the final source's content.\n if (isLast) content = content.trimEnd();\n return {\n id: `agent-instructions:${source.path}:${index}`,\n label: `${source.scope === 'global' ? 'Global' : 'Project'} instructions`,\n detail: source.ref ? `${source.path} (at ref ${source.ref})` : source.path,\n content,\n };\n });\n\n return [\n { id: 'base-prompt', label: 'Base system prompt', content: base },\n ...instructionSections,\n { id: 'model-prompt', label: 'Model-specific prompt', detail: ctx.modelId, content: modelSpecific.trim() },\n { id: 'mode-prompt', label: 'Mode prompt', detail: ctx.modeId, content: modeSpecific.trim() },\n ].filter(section => Boolean(section.content));\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;AAyBA,SAAgB,mBAAmB,UAAmC;CACpE,OAAO,SACJ,KAAI,YAAW,QAAQ,OAAO,CAAC,CAC/B,OAAO,OAAO,CAAC,CACf,KAAK,MAAM;AAChB;;;;;AAMA,SAAgB,gBAAgB,KAA4B;CAC1D,OAAO,mBAAmB,wBAAwB,GAAG,CAAC;AACxD;;;;;AAMA,SAAgB,wBAAwB,KAAqC;CAE3E,MAAM,UAAU,IAAI;CACpB,MAAM,eACJ,eAAe,KACf,aAAa,KACZ,CAAC,CAAC,YAAY,QAAQ,WAAW,YAAY,KAAK,QAAQ,WAAW,SAAS;CAGjF,MAAM,8BAAc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AAK,QAAQ,UAAU;EACrF,MAAM,UAAU,UAAU;EAC1B,MAAM,SAAS,UAAU,mBAAmB,SAAS;EACrD,IAAI,UAAU,wBAAwB,MAAM;EAC5C,IAAI,SAAS,UAAU,GAAG,2BAA2B,MAAM;EAG3D,IAAI,QAAQ,UAAU,QAAQ,QAAQ;EACtC,OAAO;GACL,IAAI,sBAAsB,OAAO,KAAK,GAAG;GACzC,OAAO,GAAG,OAAO,UAAU,WAAW,WAAW,UAAU;GAC3D,QAAQ,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO;GACtE;EACF;CACF,CAAC;CAED,OAAO;EACL;GAAE,IAAI;GAAe,OAAO;GAAsB,SAAS;EAAK;EAChE,GAAG;EACH;GAAE,IAAI;GAAgB,OAAO;GAAyB,QAAQ,IAAI;GAAS,SAAS,cAAc,KAAK;EAAE;EACzG;GAAE,IAAI;GAAe,OAAO;GAAe,QAAQ,IAAI;GAAQ,SAAS,aAAa,KAAK;EAAE;CAC9F,CAAC,CAAC,QAAO,YAAW,QAAQ,QAAQ,OAAO,CAAC;AAC9C"}
@@ -1,3 +1,4 @@
1
+ import type { ToolsInput } from '@mastra/core/agent';
1
2
  import { NotificationsStorage } from '@mastra/core/notifications';
2
3
  import type { CreateNotificationInput, ListDueNotificationsInput, ListNotificationsInput, UpdateNotificationInput } from '@mastra/core/notifications';
3
4
  import type { RequestContext } from '@mastra/core/request-context';
@@ -30,6 +31,6 @@ type DynamicToolProvider = Record<string, ToolLike | undefined> | ((ctx: {
30
31
  }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);
31
32
  export declare function createDynamicTools(mcpManager?: McpManager, extraTools?: DynamicToolProvider, disabledTools?: string[], storage?: MastraCompositeStore, pluginTools?: Record<string, ToolLike>): ({ requestContext, }: {
32
33
  requestContext: RequestContext;
33
- }) => Record<string, ToolLike> | Promise<Record<string, ToolLike>>;
34
+ }) => ToolsInput | Promise<ToolsInput>;
34
35
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,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AAEhG,wBAAgB,kBAAkB,CAChC,UAAU,CAAC,EAAE,UAAU,EACvB,UAAU,CAAC,EAAE,mBAAmB,EAChC,aAAa,CAAC,EAAE,MAAM,EAAE,EACxB,OAAO,CAAC,EAAE,oBAAoB,EAC9B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAEN,qBAE7B;IACD,cAAc,EAAE,cAAc,CAAC;CAChC,KAAG,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CA6FrC"}
@@ -1,5 +1,5 @@
1
- import { createWebExtractTool, createWebSearchTool, hasTavilyKey } from "../tools/web-search.js";
2
1
  import { MC_TOOLS } from "../tool-names.js";
2
+ import { createConfiguredWebTools } from "../tools/web-search.js";
3
3
  import { requestSandboxAccessTool } from "../tools/request-sandbox-access.js";
4
4
  import "../tools/index.js";
5
5
  import { createWorkflowTool } from "../tools/workflows/create-workflow.js";
@@ -81,10 +81,9 @@ function createDynamicTools(mcpManager, extraTools, disabledTools, storage, plug
81
81
  [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool
82
82
  };
83
83
  if (storage) tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({ storage: new LazyNotificationsStorage(storage) });
84
- if (hasTavilyKey()) {
85
- tools.web_search = createWebSearchTool();
86
- tools.web_extract = createWebExtractTool();
87
- } else if (isAnthropicModel) tools.web_search = createAnthropic({}).tools.webSearch_20250305();
84
+ const configuredWebTools = createConfiguredWebTools();
85
+ if (configuredWebTools) Object.assign(tools, configuredWebTools);
86
+ else if (isAnthropicModel) tools.web_search = createAnthropic({}).tools.webSearch_20250305();
88
87
  else if (isOpenAIModel) tools.web_search = createOpenAI({}).tools.webSearch();
89
88
  if (mcpManager) {
90
89
  const mcpTools = mcpManager.getTools();
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../src/agents/tools.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createWebSearchTool, createWebExtractTool, hasTavilyKey, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): Record<string, ToolLike> | Promise<Record<string, ToolLike>> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n const modelId = ctx?.session?.modelId;\n const isAnthropicModel = modelId?.startsWith('anthropic/');\n const isOpenAIModel = modelId?.startsWith('openai/');\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n if (hasTavilyKey()) {\n tools.web_search = createWebSearchTool();\n tools.web_extract = createWebExtractTool();\n } else if (isAnthropicModel) {\n const anthropic = createAnthropic({});\n tools.web_search = anthropic.tools.webSearch_20250305();\n } else if (isOpenAIModel) {\n const openai = createOpenAI({});\n tools.web_search = openai.tools.webSearch();\n }\n\n if (mcpManager) {\n const mcpTools = mcpManager.getTools();\n Object.assign(tools, mcpTools);\n }\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools;\n };\n\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.resolve(resolved).then(finish);\n }\n return finish(resolved as Record<string, ToolLike | undefined>);\n }\n\n return finish(extraTools);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,IAAa,2BAAb,cAA8C,qBAAqB;CACpC;CAA7B,YAAY,SAAgD;EAC1D,MAAM;EADqB,KAAA,UAAA;CAE7B;CAEA,MAAc,0BAAyD;EACrE,MAAM,gBAAgB,MAAM,KAAK,QAAQ,SAAS,eAAe;EACjE,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,4DAA4D;EAE9E,OAAO;CACT;CAEA,MAAM,mBAAmB,OAAgC;EACvD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,mBAAmB,KAAK;CACxE;CAEA,MAAM,kBAAkB,OAA+B;EACrD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,kBAAkB,KAAK;CACvE;CAEA,MAAM,qBAAqB,OAAkC;EAC3D,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,qBAAqB,KAAK;CAC1E;CAEA,MAAM,gBAAgB,OAAyC;EAC7D,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,gBAAgB,KAAK;CACrE;CAEA,MAAM,mBAAmB,OAAgC;EACvD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,mBAAmB,KAAK;CACxE;CAEA,MAAM,sBAAsB;EAC1B,QAAQ,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{ createOpenAI } from '@ai-sdk/openai';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createConfiguredWebTools, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): ToolsInput | Promise<ToolsInput> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n const modelId = ctx?.session?.modelId;\n const isAnthropicModel = modelId?.startsWith('anthropic/');\n const isOpenAIModel = modelId?.startsWith('openai/');\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n const configuredWebTools = createConfiguredWebTools();\n if (configuredWebTools) {\n Object.assign(tools, configuredWebTools);\n } else if (isAnthropicModel) {\n const anthropic = createAnthropic({});\n tools.web_search = anthropic.tools.webSearch_20250305();\n } else if (isOpenAIModel) {\n const openai = createOpenAI({});\n tools.web_search = openai.tools.webSearch();\n }\n\n if (mcpManager) {\n const mcpTools = mcpManager.getTools();\n Object.assign(tools, mcpTools);\n }\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools as ToolsInput;\n };\n\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.resolve(resolved).then(finish);\n }\n return finish(resolved as Record<string, ToolLike | undefined>);\n }\n\n return finish(extraTools);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BA,IAAa,2BAAb,cAA8C,qBAAqB;CACpC;CAA7B,YAAY,SAAgD;EAC1D,MAAM;EADqB,KAAA,UAAA;CAE7B;CAEA,MAAc,0BAAyD;EACrE,MAAM,gBAAgB,MAAM,KAAK,QAAQ,SAAS,eAAe;EACjE,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,4DAA4D;EAE9E,OAAO;CACT;CAEA,MAAM,mBAAmB,OAAgC;EACvD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,mBAAmB,KAAK;CACxE;CAEA,MAAM,kBAAkB,OAA+B;EACrD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,kBAAkB,KAAK;CACvE;CAEA,MAAM,qBAAqB,OAAkC;EAC3D,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,qBAAqB,KAAK;CAC1E;CAEA,MAAM,gBAAgB,OAAyC;EAC7D,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,gBAAgB,KAAK;CACrE;CAEA,MAAM,mBAAmB,OAAgC;EACvD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,mBAAmB,KAAK;CACxE;CAEA,MAAM,sBAAsB;EAC1B,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,oBAAoB;CACpE;AACF;AAIA,SAAgB,gBAAgB,aAA2B,kBAA4D;CACrH,I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AS,EAAE,eAAe,EAAE,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AACxG,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,wBAAwB,CAAC;AA0GrE,wBAAgB,eAAe,CAC7B,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,SAAe,EACtB,gBAAgB,GAAE,MAAM,EAAO,GAC9B,MAAM,EAAE,CA0BV;AAED,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AA4FD,wBAAsB,mBAAmB,CAAC,EACxC,cAAc,EACd,MAAM,EACN,cAAc,GACf,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,uBAAuB,CAAC;CAC1C,wNA8FA;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
@@ -1,5 +1,5 @@
1
1
  import "../constants.js";
2
- import { loadSettings } from "../onboarding/settings.js";
2
+ import { loadSettings, resolveLspSetting } from "../onboarding/settings.js";
3
3
  import { getPlansDir } from "../utils/plans.js";
4
4
  import { isPathWithinRoot } from "../utils/path-security.js";
5
5
  import { SandboxFilesystem } from "./sandbox-filesystem.js";
@@ -198,14 +198,17 @@ async function getDynamicWorkspace({ requestContext, mastra, skillExtension }) {
198
198
  existing.setToolsConfig(workspaceTools);
199
199
  return existing;
200
200
  }
201
- const userLsp = loadSettings().lsp ?? {};
202
- const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), "..");
203
- const lspConfig = {
204
- maxOpenClients: 4,
205
- ...userLsp,
206
- packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath),
207
- searchPaths: [mcModulePath, ...userLsp.searchPaths ?? []]
208
- };
201
+ const userLsp = resolveLspSetting(loadSettings().lsp);
202
+ let lspConfig = false;
203
+ if (userLsp !== false) {
204
+ const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), "..");
205
+ lspConfig = {
206
+ maxOpenClients: 4,
207
+ ...userLsp,
208
+ packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath),
209
+ searchPaths: [mcModulePath, ...userLsp.searchPaths ?? []]
210
+ };
211
+ }
209
212
  const filesystem = new LocalFilesystem({
210
213
  basePath: projectPath,
211
214
  allowedPaths