@mastra/code-sdk 1.2.0-alpha.10 → 1.2.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +4 -1
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/modes/plan.js +2 -2
- package/dist/agents/modes/plan.js.map +1 -1
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +4 -1
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/prompts/plan.d.ts +1 -1
- package/dist/agents/prompts/plan.d.ts.map +1 -1
- package/dist/agents/prompts/plan.js +2 -2
- package/dist/agents/prompts/plan.js.map +1 -1
- package/dist/agents/prompts/tool-guidance.d.ts +2 -0
- package/dist/agents/prompts/tool-guidance.d.ts.map +1 -1
- package/dist/agents/prompts/tool-guidance.js +3 -2
- package/dist/agents/prompts/tool-guidance.js.map +1 -1
- package/dist/agents/tool-availability.d.ts.map +1 -1
- package/dist/agents/tool-availability.js +9 -4
- package/dist/agents/tool-availability.js.map +1 -1
- package/dist/agents/tools.js +1 -1
- package/dist/headless/cli.d.ts.map +1 -1
- package/dist/headless/cli.js +3 -0
- package/dist/headless/cli.js.map +1 -1
- package/dist/index.d.ts +68 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +173 -61
- package/dist/index.js.map +1 -1
- package/dist/plugin.d.ts +64 -1
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js +3 -1
- package/dist/plugin.js.map +1 -1
- package/dist/plugins/loader.d.ts +7 -3
- package/dist/plugins/loader.d.ts.map +1 -1
- package/dist/plugins/loader.js +53 -1
- package/dist/plugins/loader.js.map +1 -1
- package/dist/plugins/manager.d.ts +36 -2
- package/dist/plugins/manager.d.ts.map +1 -1
- package/dist/plugins/manager.js +74 -2
- package/dist/plugins/manager.js.map +1 -1
- package/dist/plugins/signal-lane.d.ts +58 -0
- package/dist/plugins/signal-lane.d.ts.map +1 -0
- package/dist/plugins/signal-lane.js +166 -0
- package/dist/plugins/signal-lane.js.map +1 -0
- package/dist/plugins/types.d.ts +36 -0
- package/dist/plugins/types.d.ts.map +1 -1
- package/dist/utils/plans.d.ts +9 -6
- package/dist/utils/plans.d.ts.map +1 -1
- package/dist/utils/plans.js +11 -11
- package/dist/utils/plans.js.map +1 -1
- package/package.json +11 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,59 @@
|
|
|
1
1
|
# @mastra/code-sdk
|
|
2
2
|
|
|
3
|
+
## 1.2.0-alpha.14
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed Factory interactive plans so they are stored as browsable artifacts. ([#21173](https://github.com/mastra-ai/mastra/pull/21173))
|
|
8
|
+
|
|
9
|
+
## 1.2.0-alpha.13
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- Fixed woken notifications running against the controller-level workspace, which is `undefined` for dynamic workspace factories. They now use the workspace of the session that owns the target thread. ([#21144](https://github.com/mastra-ai/mastra/pull/21144))
|
|
14
|
+
|
|
15
|
+
- Updated dependencies [[`2e4624e`](https://github.com/mastra-ai/mastra/commit/2e4624edb6917e61249cb60ee377735e7af7e4a9), [`e6534fa`](https://github.com/mastra-ai/mastra/commit/e6534fab031216f6cb48c4c9907cbfdce9d60bc6), [`7fdcaa6`](https://github.com/mastra-ai/mastra/commit/7fdcaa66105d64290f9b14432a12ec99f39c4d3a), [`65b1183`](https://github.com/mastra-ai/mastra/commit/65b11832834f87a9bc8719391deb27559de5138a), [`5dba2a4`](https://github.com/mastra-ai/mastra/commit/5dba2a41600385751f5aace79878904e1972609d), [`cfd0d9e`](https://github.com/mastra-ai/mastra/commit/cfd0d9ec77ec3c69dd96f79cdb579e03d79f22ce), [`d9d93b2`](https://github.com/mastra-ai/mastra/commit/d9d93b25e4a65ad5fa153fa35be7ed149c8d587f)]:
|
|
16
|
+
- @mastra/core@1.58.0-alpha.12
|
|
17
|
+
- @mastra/observability@1.16.6-alpha.3
|
|
18
|
+
- @mastra/schema-compat@1.3.6-alpha.3
|
|
19
|
+
- @mastra/mcp@1.16.0-alpha.2
|
|
20
|
+
- @mastra/memory@1.26.1-alpha.6
|
|
21
|
+
|
|
22
|
+
## 1.2.0-alpha.12
|
|
23
|
+
|
|
24
|
+
### Minor Changes
|
|
25
|
+
|
|
26
|
+
- Added `processors` and `signalProviders` to the Mastra Code plugin contract, so a plugin can contribute more than tools. ([#20848](https://github.com/mastra-ai/mastra/pull/20848))
|
|
27
|
+
|
|
28
|
+
**Processors**
|
|
29
|
+
|
|
30
|
+
A plugin can now extend the agent pipeline directly, passing a bare array for input processors or an object for both lanes. Plugin processors run after the processors Mastra Code configures and before the channel and memory layers the Agent appends. The slot isn't configurable, and the processors are resolved before every LLM call. Enabling, disabling, or updating a plugin applies on the next request instead of requiring a restart.
|
|
31
|
+
|
|
32
|
+
**Signal providers**
|
|
33
|
+
|
|
34
|
+
A plugin can also ship a signal provider, which monitors an external source and pushes notifications into a thread. Providers are long-lived, so the SDK owns their lifecycle instead of handing them to the agent: it registers Mastra on them, connects them to the coding agent, starts them polling, and stops them when the plugin is updated, disabled, or uninstalled. That makes a provider installed from a GitHub repository survive a mid-session update of that repository. Only one provider with a given id runs at a time, and a provider that fails to start is isolated from the rest of its plugin.
|
|
35
|
+
|
|
36
|
+
Field resolvers also receive `getController()` and `getActiveSession()` on the plugin context, so a plugin can read the running session lazily at the moment it needs it.
|
|
37
|
+
|
|
38
|
+
For embedders that inject their own `pluginManager` into `createMastraCode`: the `PluginManager` contract now also requires `onReload`, `getPluginSignalProviders`, and `setRuntime`, so hand-built manager implementations must add these methods.
|
|
39
|
+
|
|
40
|
+
### Patch Changes
|
|
41
|
+
|
|
42
|
+
- Fixed deferred notification deliveries failing with "No model selected" when the woken thread had no request context. The notification dispatch workflow re-sends deferred and summarized notifications long after the originating send, so any stream options attached to the original signal are gone; waking an idle thread then had no way to resolve a model. The notification delivery policy now drives the fix: `NotificationDeliveryDecision` accepts `streamOptions`, and the dispatcher re-runs the agent's delivery policy at delivery time (via the new `agent.resolveNotificationDeliveryDecision()`) to attach freshly resolved stream options to both individual and summary deliveries. Only `streamOptions` is honored at dispatch time; the record's persisted schedule still governs when and how it is delivered. Receipt-time sends also honor the policy's `streamOptions` now: an immediate deliver or summarize-now wake attaches them too, with caller-supplied stream options taking precedence. Mastra Code wires its session-based stream options resolver through the Code Agent's `deliveryPolicy.decide`, layered on the default decision logic. This fix applies to threads whose session is live in the current process; deliveries with no resolvable session fall back to a bare wake, and the "No model selected" error now distinguishes the case where a run started without any controller session context. This re-lands the capability removed by the #18637 revert in the policy-driven shape that revert called for, and the `@mastra/github-signals` bump only widens its `getNotificationStreamOptions` callback return type to allow `undefined`. ([#21113](https://github.com/mastra-ai/mastra/pull/21113))
|
|
43
|
+
|
|
44
|
+
- Updated dependencies [[`b8ce7ec`](https://github.com/mastra-ai/mastra/commit/b8ce7ec96e39343c6c2f36d12d68a9ad816c09f7), [`a3a3624`](https://github.com/mastra-ai/mastra/commit/a3a3624f646b98e409424d8defccbd334da9e8b8), [`6246914`](https://github.com/mastra-ai/mastra/commit/62469146636911f3cbbe0880bd011c6a897a59a7), [`1315d8f`](https://github.com/mastra-ai/mastra/commit/1315d8f17e8e7acb61cca46b72a1d42f6d00d289), [`3f73c07`](https://github.com/mastra-ai/mastra/commit/3f73c076727e8c36b4fff7a1b40290fb68957fa8), [`7c1ebb1`](https://github.com/mastra-ai/mastra/commit/7c1ebb15690c4b3f0eabb19077cf8af573311e57), [`32980a3`](https://github.com/mastra-ai/mastra/commit/32980a3e2413d0274ac244d32c37d910edc13f00), [`261edb9`](https://github.com/mastra-ai/mastra/commit/261edb9bc0cfbed2b77090b87562307a360f1a04), [`4bcdfaf`](https://github.com/mastra-ai/mastra/commit/4bcdfaf0eac3199d7cb171b0a19a92c9c341eea4), [`1b1dd7b`](https://github.com/mastra-ai/mastra/commit/1b1dd7bc0e59b7a8bfabd09a3eec1ccd95b4c2f3), [`af4636a`](https://github.com/mastra-ai/mastra/commit/af4636a74463275d71c1d13a38f7d2b738f128bf), [`a463cdf`](https://github.com/mastra-ai/mastra/commit/a463cdf1c95c3059e70f0bff27959e8558bb899d), [`0ea6b80`](https://github.com/mastra-ai/mastra/commit/0ea6b8001408ce02b56e8be0536b0fd8cbaf8ad2)]:
|
|
45
|
+
- @mastra/core@1.58.0-alpha.11
|
|
46
|
+
- @mastra/github-signals@0.2.5-alpha.1
|
|
47
|
+
- @mastra/memory@1.26.1-alpha.5
|
|
48
|
+
- @mastra/mcp@1.16.0-alpha.2
|
|
49
|
+
|
|
50
|
+
## 1.2.0-alpha.11
|
|
51
|
+
|
|
52
|
+
### Patch Changes
|
|
53
|
+
|
|
54
|
+
- Updated dependencies [[`66bbfb5`](https://github.com/mastra-ai/mastra/commit/66bbfb5f05b473d39f88c0e4a481ccac41634f3a)]:
|
|
55
|
+
- @mastra/core@1.58.0-alpha.10
|
|
56
|
+
|
|
3
57
|
## 1.2.0-alpha.10
|
|
4
58
|
|
|
5
59
|
### Patch Changes
|
|
@@ -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,qBAAq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CAAC;IAAC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,cAAc,CAAA;CAAE,GACzG,oBAAoB,CA+EtB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,2BAA2B,CACzC,sBAAsB,EAAE,6BAA6B,CAAC,GAAG,CAAC,GAAG,SAAS,EACtE,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,CAKf;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"}
|
package/dist/agents/model.js
CHANGED
|
@@ -115,7 +115,10 @@ function resolveRequestThinkingLevel(agentControllerContext, settingsPath) {
|
|
|
115
115
|
function getDynamicModel({ requestContext }, settingsPath) {
|
|
116
116
|
const agentControllerContext = requestContext.get("controller");
|
|
117
117
|
const modelId = agentControllerContext?.session?.modelId;
|
|
118
|
-
if (!modelId)
|
|
118
|
+
if (!modelId) {
|
|
119
|
+
if (!agentControllerContext) throw new Error("No model available: this run started without a controller session context, so no model selection could be resolved.");
|
|
120
|
+
throw new Error("No model selected. Use /models to select a model first.");
|
|
121
|
+
}
|
|
119
122
|
return resolveModel(modelId, {
|
|
120
123
|
thinkingLevel: resolveRequestThinkingLevel(agentControllerContext, settingsPath),
|
|
121
124
|
remapForCodexOAuth: true,
|
package/dist/agents/model.js.map
CHANGED
|
@@ -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 ?? mgApiKey ?? '',\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 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,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,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D,MAAM,UAAU,wBAAwB,SAAS;CACjD,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,yDAAyD;CAK3E,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 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 ?? mgApiKey ?? '',\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,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SAAS,cAAc;CACtE,MAAM,UAAU,wBAAwB;EACtC,sBAAsB,eAAe,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,SAAS,EAAE;EAC5E,qBAAqB;EACrB,2BAA2B,QAAQ,YAAY,oBAAoB;EACnE,eAAe,SAAS;EACxB;EACA;CACF,CAAC;CAED,MAAM,OAAO,QAAQ,YAAY;EAC/B,WAAW;EACX;EACA,SAAS;EACT;CACF,CAAC;CAED,OAAO,QAAQ,qBAAqB;EAClC;EACA,SAAS;EACT,QAAQ,MAAM,UAAU,YAAY;EACpC;CACF,CAAC;AACH;;;;;;;;;;;;;;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"}
|
|
@@ -10,7 +10,7 @@ const planMode = {
|
|
|
10
10
|
|
|
11
11
|
## Rules
|
|
12
12
|
- You have READ-ONLY access to the project. You cannot modify project files or run commands.
|
|
13
|
-
- The one exception is plan files: you can create and edit markdown files inside
|
|
13
|
+
- The one exception is plan files: you can create and edit markdown files inside the session-specific plan directory identified in your system prompt using \`write_file\`, \`view\`, and \`string_replace_lsp\`. You may not write anywhere else.
|
|
14
14
|
- First, explore the codebase to understand existing patterns, architecture, and conventions.
|
|
15
15
|
- Produce a concrete, actionable plan — not vague suggestions.
|
|
16
16
|
|
|
@@ -21,7 +21,7 @@ const planMode = {
|
|
|
21
21
|
- **Parallelize**: Make multiple independent tool calls when exploring different areas
|
|
22
22
|
|
|
23
23
|
## Plan Delivery
|
|
24
|
-
- Write your plan to a markdown file
|
|
24
|
+
- Write your plan to a markdown file in the session-specific plan directory identified in your system prompt using \`write_file\`, then call \`submit_plan({ path })\` with the path to that file (never the plan body).
|
|
25
25
|
- Start the file with a \`# Title\` heading describing the plan.
|
|
26
26
|
- Reuse the same file while iterating on the same plan; only create a new file for a genuinely different plan so each plan stays available to review.
|
|
27
27
|
- Do NOT output the plan as text — it MUST live in the plan file.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/modes/plan.ts"],"sourcesContent":["/**\n * Plan mode — read-only analysis and planning.\n */\nimport type { AgentControllerMode } from '@mastra/core/agent-controller';\nimport { PLAN_MODE_AVAILABLE_TOOLS } from '../tool-availability.js';\n\nexport const planMode: AgentControllerMode = {\n id: 'plan',\n name: 'Plan',\n transitionsTo: 'build',\n defaultModelId: 'openai/gpt-5.5',\n description:\n \"Read-only analysis and planning. Use for 'create an implementation plan for X', 'analyze the architecture of Y'.\",\n instructions: `You are an expert software architect and planner. Your job is to analyze a codebase and produce a detailed implementation plan for a given task.\n\n## Rules\n- You have READ-ONLY access to the project. You cannot modify project files or run commands.\n- The one exception is plan files: you can create and edit markdown files inside
|
|
1
|
+
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/modes/plan.ts"],"sourcesContent":["/**\n * Plan mode — read-only analysis and planning.\n */\nimport type { AgentControllerMode } from '@mastra/core/agent-controller';\nimport { PLAN_MODE_AVAILABLE_TOOLS } from '../tool-availability.js';\n\nexport const planMode: AgentControllerMode = {\n id: 'plan',\n name: 'Plan',\n transitionsTo: 'build',\n defaultModelId: 'openai/gpt-5.5',\n description:\n \"Read-only analysis and planning. Use for 'create an implementation plan for X', 'analyze the architecture of Y'.\",\n instructions: `You are an expert software architect and planner. Your job is to analyze a codebase and produce a detailed implementation plan for a given task.\n\n## Rules\n- You have READ-ONLY access to the project. You cannot modify project files or run commands.\n- The one exception is plan files: you can create and edit markdown files inside the session-specific plan directory identified in your system prompt using \\`write_file\\`, \\`view\\`, and \\`string_replace_lsp\\`. You may not write anywhere else.\n- First, explore the codebase to understand existing patterns, architecture, and conventions.\n- Produce a concrete, actionable plan — not vague suggestions.\n\n## Tool Strategy\n- **Discover structure**: Use find_files (glob) to understand project layout and find relevant files\n- **Find patterns**: Use search_content (grep) to locate existing implementations, imports, and conventions\n- **Understand deeply**: Use view with view_range to read specific sections of key files\n- **Parallelize**: Make multiple independent tool calls when exploring different areas\n\n## Plan Delivery\n- Write your plan to a markdown file in the session-specific plan directory identified in your system prompt using \\`write_file\\`, then call \\`submit_plan({ path })\\` with the path to that file (never the plan body).\n- Start the file with a \\`# Title\\` heading describing the plan.\n- Reuse the same file while iterating on the same plan; only create a new file for a genuinely different plan so each plan stays available to review.\n- Do NOT output the plan as text — it MUST live in the plan file.\n- Be concise: reference files by path and line number, don't include raw contents.\n- Focus on actionable details, not general observations.\n- To revise after \"Request changes\", edit the same file in place with \\`string_replace_lsp\\`, and call \\`submit_plan\\` again with the same path.`,\n\n metadata: {\n default: false,\n },\n\n availableTools: [...PLAN_MODE_AVAILABLE_TOOLS],\n};\n"],"mappings":";;AAMA,MAAa,WAAgC;CAC3C,IAAI;CACJ,MAAM;CACN,eAAe;CACf,gBAAgB;CAChB,aACE;CACF,cAAc;;;;;;;;;;;;;;;;;;;;;;CAuBd,UAAU,EACR,SAAS,MACX;CAEA,gBAAgB,CAAC,GAAG,yBAAyB;AAC/C"}
|
|
@@ -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;
|
|
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,WAAW,aAAc,SAAQ,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAQD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CA0E1D"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { buildModePrompt, buildModePromptFn } from "./build.js";
|
|
2
|
+
import { getLocalPlansRelativeDir } from "../../utils/plans.js";
|
|
2
3
|
import { planModePrompt } from "./plan.js";
|
|
3
4
|
import { fastModePrompt } from "./fast.js";
|
|
4
5
|
import { hasTavilyKey } from "../../tools/web-search.js";
|
|
@@ -25,9 +26,11 @@ function buildFullPrompt(ctx) {
|
|
|
25
26
|
if (permRules?.tools) {
|
|
26
27
|
for (const [name, policy] of Object.entries(permRules.tools)) if (policy === "deny") deniedTools.add(name);
|
|
27
28
|
}
|
|
29
|
+
const factoryProjectId = typeof ctx.state?.factoryProjectId === "string" ? ctx.state.factoryProjectId : void 0;
|
|
28
30
|
const toolGuidance = buildToolGuidance(ctx.modeId, {
|
|
29
31
|
hasWebSearch,
|
|
30
|
-
deniedTools
|
|
32
|
+
deniedTools,
|
|
33
|
+
plansDir: getLocalPlansRelativeDir({ factoryProjectId })
|
|
31
34
|
});
|
|
32
35
|
const base = buildBasePrompt({
|
|
33
36
|
projectPath: ctx.workingDir,
|
|
@@ -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 { 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 toolGuidance = buildToolGuidance(ctx.modeId, {
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/plan.ts"],"names":[],"mappings":"AAKA,UAAU,iBAAiB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,wBAAgB,cAAc,CAAC,
|
|
1
|
+
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/plan.ts"],"names":[],"mappings":"AAKA,UAAU,iBAAiB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAuG7D"}
|
|
@@ -3,8 +3,8 @@ import { getLocalPlansRelativeDir } from "../../utils/plans.js";
|
|
|
3
3
|
/**
|
|
4
4
|
* Plan mode prompt — read-only exploration and planning.
|
|
5
5
|
*/
|
|
6
|
-
function planModePrompt(
|
|
7
|
-
const plansDir = getLocalPlansRelativeDir();
|
|
6
|
+
function planModePrompt(ctx) {
|
|
7
|
+
const plansDir = getLocalPlansRelativeDir({ factoryProjectId: typeof ctx.state?.factoryProjectId === "string" ? ctx.state.factoryProjectId : void 0 });
|
|
8
8
|
const examplePath = `${plansDir}/add-dark-mode.md`;
|
|
9
9
|
return `
|
|
10
10
|
# Plan Mode — READ-ONLY (except plan files)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/prompts/plan.ts"],"sourcesContent":["/**\n * Plan mode prompt — read-only exploration and planning.\n */\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\n\ninterface PlanPromptContext {\n state?: Record<string, unknown>;\n}\n\nexport function planModePrompt(
|
|
1
|
+
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/prompts/plan.ts"],"sourcesContent":["/**\n * Plan mode prompt — read-only exploration and planning.\n */\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\n\ninterface PlanPromptContext {\n state?: Record<string, unknown>;\n}\n\nexport function planModePrompt(ctx: PlanPromptContext): string {\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const plansDir = getLocalPlansRelativeDir({ factoryProjectId });\n const examplePath = `${plansDir}/add-dark-mode.md`;\n\n return `\n# Plan Mode — READ-ONLY (except plan files)\n\nYou are in PLAN mode. Your job is to explore the codebase and design an implementation plan — NOT to make changes to the project.\n\n## CRITICAL: Read-Only Mode (project files)\n\nThis mode is **read-only for project files**. You must NOT modify the project.\n\n- Do NOT modify, create, or delete project files\n- Do NOT run commands that change state (no git commit, no npm install, no file creation)\n- Do NOT run build commands, tests, or scripts that have side effects\n\nThe ONE exception is plan files: you CAN create and edit markdown files inside \\`${plansDir}/\\` (e.g. \\`${examplePath}\\`). You may NOT write anywhere else.\n\nIf the user asks you to make changes while in Plan mode, explain that you're in read-only mode and they should switch to Build mode (\\`/mode build\\`) first.\n\n## Exploration Strategy\n\nBefore writing any plan, build a mental model of the codebase:\n1. Start with the directory structure (\\`view\\` on the project root or relevant subdirectory).\n2. Find the relevant entry points and core files using \\`search_content\\` and \\`find_files\\`.\n3. Read the actual code — don't assume based on file names alone.\n4. Trace data flow: where does input come from, how is it transformed, where does it go?\n5. Identify existing patterns the codebase uses (naming, structure, error handling, testing).\n\n## Goal-Ready Plans\n\nThe submit_plan approval UI can let the user approve the plan normally or start it as a persistent goal. Write plans so they can be carried out as a goal if the user chooses that option:\n- Make the desired outcome explicit and verifiable.\n- Break work into ordered, actionable steps that can be executed autonomously.\n- Include constraints, risks, blockers, and decision points that may require user input.\n- Include concrete verification criteria so the goal judge can tell when the work is done.\n\n## Your Plan Output\n\nProduce a clear, step-by-step plan with this structure:\n\n### Overview\nOne paragraph: what the change does and why.\n\n### Complexity Estimate\n- **Size**: Small (1-2 files) / Medium (3-5 files) / Large (6+ files)\n- **Risk**: Low (additive, no breaking changes) / Medium (modifies existing behavior) / High (architectural, affects many consumers)\n- **Dependencies**: List any new packages, external services, or migration steps needed.\n\n### Steps\nFor each step:\n1. **File**: path to create or modify\n2. **Change**: what to add/modify/remove, with enough specificity to implement directly\n3. **Why**: brief rationale connecting this step to the overall goal\n\n### Verification\n- What tests to run\n- What to check manually\n- What could go wrong\n\n## Plan File Workflow\n\nWrite each plan to its own markdown file under \\`${plansDir}/\\` (e.g. \\`${examplePath}\\`). Start the file with a \\`# Title\\` heading describing the plan.\n\n1. **First submission**: Write your plan to a file under \\`${plansDir}/\\` using \\`write_file\\`, then call \\`submit_plan\\` with the \\`path\\` to that file.\n2. **Reading**: Use \\`view\\` to read a plan file.\n3. **Editing**: Use \\`string_replace_lsp\\` for targeted edits to specific sections.\n\n**Reuse the same file while you keep iterating on the same plan.** Only create a NEW file when you're starting a genuinely different plan — that keeps each plan available to look back at and keeps revision diffs meaningful.\n\n## IMMEDIATE ACTION: Write plan file, then call submit_plan\n\nAs soon as your plan is complete:\n1. Write it to a file under \\`${plansDir}/\\` using \\`write_file\\`\n2. Call \\`submit_plan\\` with the \\`path\\` to that file\n\n**CRITICAL:** Do NOT generate a long text response describing your plan. The plan content belongs in the plan file, not in your text output or the \\`submit_plan\\` arguments.\n\n\\`\\`\\`javascript\nsubmit_plan({\n path: \"${examplePath}\"\n})\n\\`\\`\\`\n\nThe user will see the plan rendered inline and can:\n- **Approve** — automatically switches to Build mode for implementation\n- **Start as goal** — approves the plan and enters goal mode so the agent keeps working toward the plan until judged complete, paused, or waiting for user input\n- **Request changes** — rejects the plan; the agent stops immediately and the user provides revision feedback in their next chat message\n\n## Revision Workflow\n\nIf the user requests changes, you will be stopped immediately. Wait for their next message — it will contain their revision feedback. When you receive it:\n1. Use \\`view\\` to read the SAME plan file\n2. Use \\`string_replace_lsp\\` to make targeted edits based on feedback\n3. Use \\`view\\` to re-read the updated file\n4. Call \\`submit_plan\\` again with the same \\`path\\` — editing the file alone does NOT resubmit it\n\nThe user will see a diff of what changed between the previous and revised plan. Use \\`string_replace_lsp\\` for targeted edits so the diff is clear and meaningful — do NOT rewrite the entire plan from scratch for small changes, and do NOT move the plan to a new file for a revision.\n\nDo NOT start implementing until the plan is approved.\n`;\n}\n"],"mappings":";;;;;AASA,SAAgB,eAAe,KAAgC;CAE7D,MAAM,WAAW,yBAAyB,EAAE,kBADnB,OAAO,IAAI,OAAO,qBAAqB,WAAW,IAAI,MAAM,mBAAmB,KAAA,EAC3C,CAAC;CAC9D,MAAM,cAAc,GAAG,SAAS;CAEhC,OAAO;;;;;;;;;;;;;mFAa0E,SAAS,cAAc,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mDA8CnE,SAAS,cAAc,YAAY;;6DAEzB,SAAS;;;;;;;;;gCAStC,SAAS;;;;;;;WAO9B,YAAY;;;;;;;;;;;;;;;;;;;;;AAqBvB"}
|
|
@@ -7,6 +7,8 @@ interface ToolGuidanceOptions {
|
|
|
7
7
|
hasWebSearch?: boolean;
|
|
8
8
|
/** Tool names that have been denied — omit their guidance sections. */
|
|
9
9
|
deniedTools?: Set<string>;
|
|
10
|
+
/** Workspace-relative directory where plan mode can write plans. */
|
|
11
|
+
plansDir?: string;
|
|
10
12
|
}
|
|
11
13
|
export declare function buildToolGuidance(modeId: string, options?: ToolGuidanceOptions): string;
|
|
12
14
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,UAAU,mBAAmB;IAC3B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uEAAuE;IACvE,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,UAAU,mBAAmB;IAC3B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uEAAuE;IACvE,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,MAAM,CAgO3F"}
|
|
@@ -7,6 +7,7 @@ import { MC_TOOLS } from "../../tool-names.js";
|
|
|
7
7
|
*/
|
|
8
8
|
function buildToolGuidance(modeId, options = {}) {
|
|
9
9
|
const denied = options.deniedTools ?? /* @__PURE__ */ new Set();
|
|
10
|
+
const plansDir = options.plansDir ?? ".mastracode/plans";
|
|
10
11
|
const sections = [];
|
|
11
12
|
sections.push(`# Tool Usage Rules
|
|
12
13
|
|
|
@@ -130,9 +131,9 @@ ${patchToolGuidance}
|
|
|
130
131
|
- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.
|
|
131
132
|
- The plan will be rendered as markdown and the user can approve, reject, or request changes.
|
|
132
133
|
- On approval, the system automatically switches to the default mode so you can implement.
|
|
133
|
-
- Takes one argument: \`path\` (the plan markdown file you wrote under
|
|
134
|
+
- Takes one argument: \`path\` (the plan markdown file you wrote under \`${plansDir}/\`). Do NOT pass the plan body — it lives in the file.`);
|
|
134
135
|
if (modeId === "plan") sections.push(`
|
|
135
|
-
**Plan file access** — Your plan lives in a markdown file under
|
|
136
|
+
**Plan file access** — Your plan lives in a markdown file under \`${plansDir}/\` (e.g. \`add-dark-mode-toggle.md\`)
|
|
136
137
|
- Use \`write_file\` to create the plan file, \`view\` to read it, and \`string_replace_lsp\` for targeted edits.
|
|
137
138
|
- On first submission: write the plan to the file, then call \`submit_plan\` with its \`path\`.
|
|
138
139
|
- On revision: read the existing file, edit specific sections, re-read, then call \`submit_plan\` with the same \`path\`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-guidance.js","names":[],"sources":["../../../src/agents/prompts/tool-guidance.ts"],"sourcesContent":["/**\n * Mode-specific tool behavioral guidance.\n * Generates tool usage instructions that match the actual registered tool names\n * and are scoped to what's available in the current mode.\n */\n\nimport { MC_TOOLS } from '../../tool-names.js';\n\ninterface ToolGuidanceOptions {\n hasWebSearch?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read files before editing them. NEVER propose changes to code you haven't read.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- You MUST read a file with \\`${MC_TOOLS.VIEW}\\` before editing it.\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- If overwriting an existing file, you MUST have read it first with \\`${MC_TOOLS.VIEW}\\`.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (!denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n sections.push(`\n${webTools.join(' / ')} — Search the web / extract page content\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Task management tools (all modes) ---\n\n const taskTools: string[] = [];\n const canUpdateTask = !denied.has('task_update');\n const canCompleteTask = !denied.has('task_complete');\n const canCheckTasks = !denied.has('task_check');\n const canWriteTasks = !denied.has('task_write');\n const patchToolGuidance =\n canUpdateTask && canCompleteTask\n ? '- Prefer task_update or task_complete when changing one existing task.'\n : canUpdateTask\n ? '- Prefer task_update when changing one existing task.'\n : canCompleteTask\n ? '- Prefer task_complete when marking one existing task completed.'\n : '- Use task_write with the full task list when changing existing tasks.';\n\n if (canWriteTasks) {\n taskTools.push(`\n**task_write** — Track tasks for complex multi-step work\n- Use when a task requires 3 or more distinct steps or actions.\n- Use task_write to create the initial task list or replace the whole list after replanning.\n- Each task has: id (stable identifier), content (imperative form), status (pending, in_progress, or completed), activeForm (present continuous form shown during execution).\n- Keep task IDs stable across updates. If you omit IDs, the tool result returns generated IDs.\n${patchToolGuidance}\n- Mark tasks \\`in_progress\\` BEFORE starting work. Only ONE task should be \\`in_progress\\` at a time.\n- Mark tasks \\`completed\\` IMMEDIATELY after finishing each task. Do not batch completions.`);\n }\n\n if (canUpdateTask) {\n taskTools.push(`\n**task_update** — Patch one tracked task by ID\n- Use this for targeted changes to one existing task.\n- Provide the task ID and only the fields that changed: content, status, or activeForm.`);\n }\n\n if (canCompleteTask) {\n const idSource = canCheckTasks\n ? 'Use task_check if you need the current IDs before completing a task.'\n : canWriteTasks\n ? 'Use IDs returned by task_write.'\n : 'Use only task IDs already visible in the current task list.';\n taskTools.push(`\n**task_complete** — Mark one tracked task completed by ID\n- Use this immediately after finishing a tracked task.\n- ${idSource}`);\n }\n\n if (canCheckTasks) {\n taskTools.push(`\n**task_check** — Check completion status of tasks\n- Use this BEFORE finishing tracked work to verify all tasks are completed.\n- Returns a readable status summary plus structured fields: tasks, summary, incompleteTasks, and isError.\n- summary includes total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted.\n- Use summary.allCompleted to decide whether tracked work is complete; if summary.hasTasks is false, no task list is currently tracked.\n- If any tasks remain incomplete, continue working on them.\n- IMPORTANT: Always check task completion before ending work on a complex task.`);\n }\n\n if (!denied.has('ask_user')) {\n taskTools.push(`\n**ask_user** — Ask the user a structured question\n- Use when you need clarification, want to validate assumptions, or need the user to make a decision.\n- Provide clear, specific questions. End with a question mark.\n- Include options (2-4 choices) for structured decisions. Omit options for open-ended questions.\n- Don't use this for simple yes/no — just ask in your text response.`);\n }\n\n if (taskTools.length > 0) {\n sections.push(taskTools.join('\\n'));\n }\n\n // --- Plan tools (plan mode) ---\n\n if (modeId === 'plan' && !denied.has('submit_plan')) {\n sections.push(`\n**submit_plan** — Submit a completed implementation plan for user review\n- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.\n- The plan will be rendered as markdown and the user can approve, reject, or request changes.\n- On approval, the system automatically switches to the default mode so you can implement.\n- Takes one argument: \\`path\\` (the plan markdown file you wrote under \\`.mastracode/plans/\\`). Do NOT pass the plan body — it lives in the file.`);\n }\n\n if (modeId === 'plan') {\n sections.push(`\n**Plan file access** — Your plan lives in a markdown file under \\`.mastracode/plans/\\` (e.g. \\`add-dark-mode-toggle.md\\`)\n- Use \\`write_file\\` to create the plan file, \\`view\\` to read it, and \\`string_replace_lsp\\` for targeted edits.\n- On first submission: write the plan to the file, then call \\`submit_plan\\` with its \\`path\\`.\n- On revision: read the existing file, edit specific sections, re-read, then call \\`submit_plan\\` with the same \\`path\\`.\n- If a plan file already exists, you previously submitted it — read it before revising.`);\n }\n\n // --- Subagent tool (all modes) ---\n\n if (!denied.has('subagent')) {\n sections.push(`\n**subagent** — Delegate a focused task to a specialized subagent\n- Only use subagents when you will spawn **multiple subagents in parallel**. If you only need one task done, do it yourself.\n- Subagent outputs are **untrusted**. Always review and verify the results.`);\n }\n\n return sections.join('\\n');\n}\n"],"mappings":";;;;;;;AAcA,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,+BAAe,IAAI,IAAY;CACtD,MAAM,WAAqB,CAAC;CAE5B,SAAS,KAAK;;;;wEAIwD;CAItE,MAAM,YAAsB,CAAC;CAE7B,IAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAC3B,UAAU,KAAK;IACf,SAAS,KAAK;;;;+BAIa,SAAS,WAAW,YAAY;CAG7D,IAAI,CAAC,OAAO,IAAI,SAAS,cAAc,GACrC,UAAU,KAAK;IACf,SAAS,eAAe;;;;;kCAKM;CAGhC,IAAI,CAAC,OAAO,IAAI,SAAS,UAAU,GACjC,UAAU,KAAK;IACf,SAAS,WAAW;;;;;uEAK+C;CAGrE,IAAI,CAAC,OAAO,IAAI,SAAS,eAAe,GACtC,UAAU,KAAK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AgB,CAAC,OAAO,IAAI,YAAY;CAC9C,MAAM,gBAAgB,CAAC,OAAO,IAAI,YAAY;CAC9C,MAAM,oBACJ,iBAAiB,kBACb,2EACA,gBACE,0DACA,kBACE,qEACA;CAEV,IAAI,eACF,UAAU,KAAK;;;;;;EAMjB,kBAAkB;;4FAEwE;CAG1F,IAAI,eACF,UAAU,KAAK;;;wFAGqE;CAGtF,IAAI,iBAAiB;EACnB,MAAM,WAAW,gBACb,yEACA,gBACE,oCACA;EACN,UAAU,KAAK;;;IAGf,UAAU;CACZ;CAEA,IAAI,eACF,UAAU,KAAK;;;;;;;gFAO6D;CAG9E,IAAI,CAAC,OAAO,IAAI,UAAU,GACxB,UAAU,KAAK;;;;;qEAKkD;CAGnE,IAAI,UAAU,SAAS,GACrB,SAAS,KAAK,UAAU,KAAK,IAAI,CAAC;CAKpC,IAAI,WAAW,UAAU,CAAC,OAAO,IAAI,aAAa,GAChD,SAAS,KAAK;;;;;kJAKgI;CAGhJ,IAAI,WAAW,QACb,SAAS,KAAK;;;;;wFAKsE;CAKtF,IAAI,CAAC,OAAO,IAAI,UAAU,GACxB,SAAS,KAAK;;;4EAG0D;CAG1E,OAAO,SAAS,KAAK,IAAI;AAC3B"}
|
|
1
|
+
{"version":3,"file":"tool-guidance.js","names":[],"sources":["../../../src/agents/prompts/tool-guidance.ts"],"sourcesContent":["/**\n * Mode-specific tool behavioral guidance.\n * Generates tool usage instructions that match the actual registered tool names\n * and are scoped to what's available in the current mode.\n */\n\nimport { MC_TOOLS } from '../../tool-names.js';\n\ninterface ToolGuidanceOptions {\n hasWebSearch?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const plansDir = options.plansDir ?? '.mastracode/plans';\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read files before editing them. NEVER propose changes to code you haven't read.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- You MUST read a file with \\`${MC_TOOLS.VIEW}\\` before editing it.\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- If overwriting an existing file, you MUST have read it first with \\`${MC_TOOLS.VIEW}\\`.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (!denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n sections.push(`\n${webTools.join(' / ')} — Search the web / extract page content\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Task management tools (all modes) ---\n\n const taskTools: string[] = [];\n const canUpdateTask = !denied.has('task_update');\n const canCompleteTask = !denied.has('task_complete');\n const canCheckTasks = !denied.has('task_check');\n const canWriteTasks = !denied.has('task_write');\n const patchToolGuidance =\n canUpdateTask && canCompleteTask\n ? '- Prefer task_update or task_complete when changing one existing task.'\n : canUpdateTask\n ? '- Prefer task_update when changing one existing task.'\n : canCompleteTask\n ? '- Prefer task_complete when marking one existing task completed.'\n : '- Use task_write with the full task list when changing existing tasks.';\n\n if (canWriteTasks) {\n taskTools.push(`\n**task_write** — Track tasks for complex multi-step work\n- Use when a task requires 3 or more distinct steps or actions.\n- Use task_write to create the initial task list or replace the whole list after replanning.\n- Each task has: id (stable identifier), content (imperative form), status (pending, in_progress, or completed), activeForm (present continuous form shown during execution).\n- Keep task IDs stable across updates. If you omit IDs, the tool result returns generated IDs.\n${patchToolGuidance}\n- Mark tasks \\`in_progress\\` BEFORE starting work. Only ONE task should be \\`in_progress\\` at a time.\n- Mark tasks \\`completed\\` IMMEDIATELY after finishing each task. Do not batch completions.`);\n }\n\n if (canUpdateTask) {\n taskTools.push(`\n**task_update** — Patch one tracked task by ID\n- Use this for targeted changes to one existing task.\n- Provide the task ID and only the fields that changed: content, status, or activeForm.`);\n }\n\n if (canCompleteTask) {\n const idSource = canCheckTasks\n ? 'Use task_check if you need the current IDs before completing a task.'\n : canWriteTasks\n ? 'Use IDs returned by task_write.'\n : 'Use only task IDs already visible in the current task list.';\n taskTools.push(`\n**task_complete** — Mark one tracked task completed by ID\n- Use this immediately after finishing a tracked task.\n- ${idSource}`);\n }\n\n if (canCheckTasks) {\n taskTools.push(`\n**task_check** — Check completion status of tasks\n- Use this BEFORE finishing tracked work to verify all tasks are completed.\n- Returns a readable status summary plus structured fields: tasks, summary, incompleteTasks, and isError.\n- summary includes total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted.\n- Use summary.allCompleted to decide whether tracked work is complete; if summary.hasTasks is false, no task list is currently tracked.\n- If any tasks remain incomplete, continue working on them.\n- IMPORTANT: Always check task completion before ending work on a complex task.`);\n }\n\n if (!denied.has('ask_user')) {\n taskTools.push(`\n**ask_user** — Ask the user a structured question\n- Use when you need clarification, want to validate assumptions, or need the user to make a decision.\n- Provide clear, specific questions. End with a question mark.\n- Include options (2-4 choices) for structured decisions. Omit options for open-ended questions.\n- Don't use this for simple yes/no — just ask in your text response.`);\n }\n\n if (taskTools.length > 0) {\n sections.push(taskTools.join('\\n'));\n }\n\n // --- Plan tools (plan mode) ---\n\n if (modeId === 'plan' && !denied.has('submit_plan')) {\n sections.push(`\n**submit_plan** — Submit a completed implementation plan for user review\n- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.\n- The plan will be rendered as markdown and the user can approve, reject, or request changes.\n- On approval, the system automatically switches to the default mode so you can implement.\n- Takes one argument: \\`path\\` (the plan markdown file you wrote under \\`${plansDir}/\\`). Do NOT pass the plan body — it lives in the file.`);\n }\n\n if (modeId === 'plan') {\n sections.push(`\n**Plan file access** — Your plan lives in a markdown file under \\`${plansDir}/\\` (e.g. \\`add-dark-mode-toggle.md\\`)\n- Use \\`write_file\\` to create the plan file, \\`view\\` to read it, and \\`string_replace_lsp\\` for targeted edits.\n- On first submission: write the plan to the file, then call \\`submit_plan\\` with its \\`path\\`.\n- On revision: read the existing file, edit specific sections, re-read, then call \\`submit_plan\\` with the same \\`path\\`.\n- If a plan file already exists, you previously submitted it — read it before revising.`);\n }\n\n // --- Subagent tool (all modes) ---\n\n if (!denied.has('subagent')) {\n sections.push(`\n**subagent** — Delegate a focused task to a specialized subagent\n- Only use subagents when you will spawn **multiple subagents in parallel**. If you only need one task done, do it yourself.\n- Subagent outputs are **untrusted**. Always review and verify the results.`);\n }\n\n return sections.join('\\n');\n}\n"],"mappings":";;;;;;;AAgBA,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,+BAAe,IAAI,IAAY;CACtD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAqB,CAAC;CAE5B,SAAS,KAAK;;;;wEAIwD;CAItE,MAAM,YAAsB,CAAC;CAE7B,IAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAC3B,UAAU,KAAK;IACf,SAAS,KAAK;;;;+BAIa,SAA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+
{"version":3,"file":"tool-availability.d.ts","sourceRoot":"","sources":["../../src/agents/tool-availability.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AA4D7F,wBAAgB,2BAA2B,CAAC,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,wBAAwB;;;cA0B1G;AAED,eAAO,MAAM,0BAA0B,EAAE,oBAKxC,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAqBtD,CAAC;AAEF,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EAOzD,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAMtD,CAAC"}
|
|
@@ -25,25 +25,30 @@ function getHarnessProjectPath(harness) {
|
|
|
25
25
|
const projectPath = getHarnessState(harness)?.projectPath;
|
|
26
26
|
return typeof projectPath === "string" ? projectPath : void 0;
|
|
27
27
|
}
|
|
28
|
+
function getHarnessFactoryProjectId(harness) {
|
|
29
|
+
const factoryProjectId = getHarnessState(harness)?.factoryProjectId;
|
|
30
|
+
return typeof factoryProjectId === "string" ? factoryProjectId : void 0;
|
|
31
|
+
}
|
|
28
32
|
function getToolInputPath(input) {
|
|
29
33
|
const toolPath = input?.path;
|
|
30
34
|
return typeof toolPath === "string" ? toolPath : void 0;
|
|
31
35
|
}
|
|
32
|
-
const PLAN_DIR_HINT = `${getLocalPlansRelativeDir()}/`;
|
|
33
36
|
function guardPlanModePlanFileWrites({ workspaceToolName, input, context }) {
|
|
34
37
|
if (!PLAN_MODE_WRITE_TOOL_NAMES.has(workspaceToolName)) return;
|
|
35
38
|
const harness = getHarnessContext(context);
|
|
36
39
|
if (getHarnessModeId(harness) !== "plan") return;
|
|
40
|
+
const planOptions = { factoryProjectId: getHarnessFactoryProjectId(harness) };
|
|
41
|
+
const planDirHint = `${getLocalPlansRelativeDir(planOptions)}/`;
|
|
37
42
|
const projectPath = getHarnessProjectPath(harness);
|
|
38
43
|
const inputPath = getToolInputPath(input);
|
|
39
44
|
if (!projectPath || !inputPath) return {
|
|
40
45
|
proceed: false,
|
|
41
|
-
output: `Plan mode can only write plan files inside ${
|
|
46
|
+
output: `Plan mode can only write plan files inside ${planDirHint}.`
|
|
42
47
|
};
|
|
43
|
-
if (isPlanFilePath(projectPath, inputPath)) return;
|
|
48
|
+
if (isPlanFilePath(projectPath, inputPath, planOptions)) return;
|
|
44
49
|
return {
|
|
45
50
|
proceed: false,
|
|
46
|
-
output: `Plan mode can only write plan files inside ${
|
|
51
|
+
output: `Plan mode can only write plan files inside ${planDirHint}. Refusing to edit ${inputPath}.`
|
|
47
52
|
};
|
|
48
53
|
}
|
|
49
54
|
const MASTRACODE_WORKSPACE_TOOLS = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-availability.js","names":[],"sources":["../../src/agents/tool-availability.ts"],"sourcesContent":["import { WORKSPACE_TOOLS } from '@mastra/core/workspace';\nimport type { WorkspaceToolHookContext, WorkspaceToolsConfig } from '@mastra/core/workspace';\nimport { MC_TOOLS, TOOL_NAME_OVERRIDES } from '../tool-names.js';\nimport { getLocalPlansRelativeDir, isPlanFilePath } from '../utils/plans.js';\n\nconst PLAN_MODE_WRITE_TOOL_NAMES = new Set<string>([\n WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,\n WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,\n]);\n\nfunction getRequestContextValue(requestContext: unknown, key: string): unknown {\n if (!requestContext) return undefined;\n if (typeof (requestContext as { get?: unknown }).get === 'function') {\n return (requestContext as { get: (key: string) => unknown }).get(key);\n }\n return (requestContext as Record<string, unknown>)[key];\n}\n\n/**\n * Subset of the real `HarnessRequestContext` shape (see\n * packages/core/src/harness/types.ts). The mode is a string property\n * (`session.modeId`) and live state is read via `session.state.get()`.\n */\ninterface PlanModeGuardHarness {\n session?: {\n modeId?: unknown;\n state?: { get?: () => unknown };\n };\n}\n\nfunction getHarnessContext(context: unknown): PlanModeGuardHarness | undefined {\n const requestContext = (context as { requestContext?: unknown } | undefined)?.requestContext;\n const harness = getRequestContextValue(requestContext, 'harness');\n return harness && typeof harness === 'object' ? (harness as PlanModeGuardHarness) : undefined;\n}\n\nfunction getHarnessState(harness: PlanModeGuardHarness | undefined): Record<string, unknown> | undefined {\n const state = harness?.session?.state?.get?.();\n return state && typeof state === 'object' ? (state as Record<string, unknown>) : undefined;\n}\n\nfunction getHarnessModeId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const modeId = harness?.session?.modeId ?? getHarnessState(harness)?.modeId;\n return typeof modeId === 'string' ? modeId : undefined;\n}\n\nfunction getHarnessProjectPath(harness: PlanModeGuardHarness | undefined): string | undefined {\n const projectPath = getHarnessState(harness)?.projectPath;\n return typeof projectPath === 'string' ? projectPath : undefined;\n}\n\nfunction getToolInputPath(input: unknown): string | undefined {\n const toolPath = (input as { path?: unknown } | undefined)?.path;\n return typeof toolPath === 'string' ? toolPath : undefined;\n}\n\
|
|
1
|
+
{"version":3,"file":"tool-availability.js","names":[],"sources":["../../src/agents/tool-availability.ts"],"sourcesContent":["import { WORKSPACE_TOOLS } from '@mastra/core/workspace';\nimport type { WorkspaceToolHookContext, WorkspaceToolsConfig } from '@mastra/core/workspace';\nimport { MC_TOOLS, TOOL_NAME_OVERRIDES } from '../tool-names.js';\nimport { getLocalPlansRelativeDir, isPlanFilePath } from '../utils/plans.js';\n\nconst PLAN_MODE_WRITE_TOOL_NAMES = new Set<string>([\n WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,\n WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,\n]);\n\nfunction getRequestContextValue(requestContext: unknown, key: string): unknown {\n if (!requestContext) return undefined;\n if (typeof (requestContext as { get?: unknown }).get === 'function') {\n return (requestContext as { get: (key: string) => unknown }).get(key);\n }\n return (requestContext as Record<string, unknown>)[key];\n}\n\n/**\n * Subset of the real `HarnessRequestContext` shape (see\n * packages/core/src/harness/types.ts). The mode is a string property\n * (`session.modeId`) and live state is read via `session.state.get()`.\n */\ninterface PlanModeGuardHarness {\n session?: {\n modeId?: unknown;\n state?: { get?: () => unknown };\n };\n}\n\nfunction getHarnessContext(context: unknown): PlanModeGuardHarness | undefined {\n const requestContext = (context as { requestContext?: unknown } | undefined)?.requestContext;\n const harness = getRequestContextValue(requestContext, 'harness');\n return harness && typeof harness === 'object' ? (harness as PlanModeGuardHarness) : undefined;\n}\n\nfunction getHarnessState(harness: PlanModeGuardHarness | undefined): Record<string, unknown> | undefined {\n const state = harness?.session?.state?.get?.();\n return state && typeof state === 'object' ? (state as Record<string, unknown>) : undefined;\n}\n\nfunction getHarnessModeId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const modeId = harness?.session?.modeId ?? getHarnessState(harness)?.modeId;\n return typeof modeId === 'string' ? modeId : undefined;\n}\n\nfunction getHarnessProjectPath(harness: PlanModeGuardHarness | undefined): string | undefined {\n const projectPath = getHarnessState(harness)?.projectPath;\n return typeof projectPath === 'string' ? projectPath : undefined;\n}\n\nfunction getHarnessFactoryProjectId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const factoryProjectId = getHarnessState(harness)?.factoryProjectId;\n return typeof factoryProjectId === 'string' ? factoryProjectId : undefined;\n}\n\nfunction getToolInputPath(input: unknown): string | undefined {\n const toolPath = (input as { path?: unknown } | undefined)?.path;\n return typeof toolPath === 'string' ? toolPath : undefined;\n}\n\nexport function guardPlanModePlanFileWrites({ workspaceToolName, input, context }: WorkspaceToolHookContext) {\n if (!PLAN_MODE_WRITE_TOOL_NAMES.has(workspaceToolName)) return;\n\n const harness = getHarnessContext(context);\n if (getHarnessModeId(harness) !== 'plan') return;\n\n const factoryProjectId = getHarnessFactoryProjectId(harness);\n const planOptions = { factoryProjectId };\n const planDirHint = `${getLocalPlansRelativeDir(planOptions)}/`;\n const projectPath = getHarnessProjectPath(harness);\n const inputPath = getToolInputPath(input);\n if (!projectPath || !inputPath) {\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}.`,\n };\n }\n\n // Plan mode may write any `.md` file directly inside the configured plan directory,\n // but nothing else in the project.\n if (isPlanFilePath(projectPath, inputPath, planOptions)) return;\n\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}. Refusing to edit ${inputPath}.`,\n };\n}\n\nexport const MASTRACODE_WORKSPACE_TOOLS: WorkspaceToolsConfig = {\n ...TOOL_NAME_OVERRIDES,\n hooks: {\n beforeToolCall: guardPlanModePlanFileWrites,\n },\n};\n\nexport const PLAN_MODE_AVAILABLE_TOOLS: readonly string[] = [\n // Read-only exploration tools\n MC_TOOLS.VIEW,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n // Plan file writing. Tool hooks enforce that these can only write `.md`\n // files inside the session's configured plan directory while in plan mode.\n MC_TOOLS.WRITE_FILE,\n MC_TOOLS.STRING_REPLACE_LSP,\n // Plan delivery tools\n 'ask_user',\n 'submit_plan',\n // Task tools for plan-stage tracking\n 'task_write',\n 'task_update',\n 'task_complete',\n 'task_check',\n // Notification access\n MC_TOOLS.NOTIFICATION_INBOX,\n];\n\nexport const EXPLORE_MODE_AVAILABLE_TOOLS: readonly string[] = [\n MC_TOOLS.VIEW,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n 'ask_user',\n];\n\nexport const GOAL_JUDGE_READONLY_TOOLS: readonly string[] = [\n MC_TOOLS.VIEW,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n];\n"],"mappings":";;;;AAKA,MAAM,6CAA6B,IAAI,IAAY,CACjD,gBAAgB,WAAW,YAC3B,gBAAgB,WAAW,SAC7B,CAAC;AAED,SAAS,uB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CACjD,MAAM,YAAY,iBAAiB,KAAK;CACxC,IAAI,CAAC,eAAe,CAAC,WACnB,OAAO;EACL,SAAS;EACT,QAAQ,8CAA8C,YAAY;CACpE;CAKF,IAAI,eAAe,aAAa,WAAW,WAAW,GAAG;CAEzD,OAAO;EACL,SAAS;EACT,QAAQ,8CAA8C,YAAY,qBAAqB,UAAU;CACnG;AACF;AAEA,MAAa,6BAAmD;CAC9D,GAAG;CACH,OAAO,EACL,gBAAgB,4BAClB;AACF;AAEA,MAAa,4BAA+C;CAE1D,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CAGT,SAAS;CACT,SAAS;CAET;CACA;CAEA;CACA;CACA;CACA;CAEA,SAAS;AACX;AAEA,MAAa,+BAAkD;CAC7D,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT;AACF;AAEA,MAAa,4BAA+C;CAC1D,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;AACX"}
|
package/dist/agents/tools.js
CHANGED
|
@@ -3,8 +3,8 @@ import { MC_TOOLS } from "../tool-names.js";
|
|
|
3
3
|
import { requestSandboxAccessTool } from "../tools/request-sandbox-access.js";
|
|
4
4
|
import "../tools/index.js";
|
|
5
5
|
import { createOpenAI } from "@ai-sdk/openai";
|
|
6
|
-
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
7
6
|
import { NotificationsStorage, createNotificationInboxTool } from "@mastra/core/notifications";
|
|
7
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
8
8
|
//#region src/agents/tools.ts
|
|
9
9
|
var LazyNotificationsStorage = class extends NotificationsStorage {
|
|
10
10
|
storage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/headless/cli.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEzE,k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AM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,UAAU,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAID;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAcvD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,YAAY,CAsC9D;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CA+BzC;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,CAuH9E"}
|
package/dist/headless/cli.js
CHANGED
|
@@ -179,6 +179,9 @@ async function runMCCli(predrainedInput) {
|
|
|
179
179
|
exitCode = 1;
|
|
180
180
|
} finally {
|
|
181
181
|
releaseAllThreadLocks();
|
|
182
|
+
try {
|
|
183
|
+
boot.stopPluginSignalProviders();
|
|
184
|
+
} catch {}
|
|
182
185
|
const closeSignalsPubSub = boot.signalsPubSub?.close;
|
|
183
186
|
await Promise.allSettled([
|
|
184
187
|
mcpManager?.disconnect(),
|