@mastra/code-sdk 1.2.0-alpha.13 → 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 CHANGED
@@ -1,5 +1,11 @@
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
+
3
9
  ## 1.2.0-alpha.13
4
10
 
5
11
  ### Patch Changes
@@ -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 \`.mastracode/plans/\` using \`write_file\`, \`view\`, and \`string_replace_lsp\`. You may not write anywhere else.
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 under \`.mastracode/plans/\` (e.g. \`.mastracode/plans/add-dark-mode.md\`) using \`write_file\`, then call \`submit_plan({ path })\` with the path to that file (never the plan body).
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 \\`.mastracode/plans/\\` 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 under \\`.mastracode/plans/\\` (e.g. \\`.mastracode/plans/add-dark-mode.md\\`) 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
+ {"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;AAUpF,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,CAqE1D"}
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, { hasWebSearch, deniedTools });\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":";;;;;;;;;;AA0BA,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,eAAe,kBAAkB,IAAI,QAAQ;EAAE;EAAc;CAAY,CAAC;CAgBhF,MAAM,OAAO,gBAAgB;EAZ3B,aAAa,IAAI;EACjB,aAAa,IAAI,eAAe;EAChC,WAAW,IAAI;EACf,UAAU,QAAQ;EAClB,gBAAgB,IAAI;EACpB,MAAM,IAAI;EACV,MAAM,IAAI;EACV,SAAS,IAAI;EACb,YAAY,IAAI,OAAO;EACvB;CAGiC,CAAC;CACpC,MAAM,QAAQ,YAAY,IAAI,WAAW,YAAY;CACrD,MAAM,gBAAgB,OAAO,UAAU,aAAa,MAAM,GAAG,IAAI,UAAU;CAC3E,MAAM,gBAAgB,IAAI,UACrB,qBAAqB,IAAI,YAAiD,KAC3E;CAgBJ,MAAM,YAAY,IAAI,OAAO;CAC7B,MAAM,oBAAoB,IAAI,OAAO,sBAAsB;CAC3D,MAAM,yBAAyB,IAAI,OAAO,2BAA2B;CACrE,MAAM,UAAU,OAAO,IAAI,OAAO,YAAY,WAAW,IAAI,MAAM,UAAU,KAAA;CAC7E,MAAM,gBAAgB,oBAClB,UACE,8BAA8B,IAAI,YAAY,OAAO,IACrD;EAAE,cAAc;EAAO,YAAY;CAAG,IACxC,KAAA;CAQJ,OAFiB;EAAC;EAFU,wBAHD,sBAAsB,IAAI,YAAY,WAAW,eAAe,EACzF,YAAY,uBACd,CACqE,CAE3B,CAAC,CAAC,KAAK;EAAG,cAAc,KAAK;EAAG,aAAa,KAAK;CAAC,CAAC,CAAC,OAAO,OAExF,CAAC,CAAC,KAAK,MAAM;AAC7B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport { 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,GACz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ptContext): string;
4
+ export declare function planModePrompt(ctx: PlanPromptContext): string;
5
5
  export {};
6
6
  //# sourceMappingURL=plan.d.ts.map
@@ -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,IAAI,EAAE,iBAAiB,GAAG,MAAM,CAsG9D"}
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(_ctx) {
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(_ctx: PlanPromptContext): string {\n const plansDir = getLocalPlansRelativeDir();\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,MAAiC;CAC9D,MAAM,WAAW,yBAAyB;CAC1C,MAAM,cAAc,GAAG,SAAS;CAEhC,OAAO;;;;;;;;;;;;;mFAa0E,SAAS,cAAc,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mDA8CnE,SAAS,cAAc,YAAY;;6DAEzB,SAAS;;;;;;;;;gCAStC,SAAS;;;;;;;WAO9B,YAAY;;;;;;;;;;;;;;;;;;;;;AAqBvB"}
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;CAC3B;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,MAAM,CA+N3F"}
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 \`.mastracode/plans/\`). Do NOT pass the plan body — it lives in the file.`);
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 \`.mastracode/plans/\` (e.g. \`add-dark-mode-toggle.md\`)
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;IACf,SAAS,gBAAgB;;8CAEiB,SAAS,KAAK,kBAAkB,SAAS,eAAe,GAAG,SAAS,WAAW,mBAAmB,SAAS,mBAAmB,GAAG,SAAS,WAAW;;;;4CAIvJ,SAAS,KAAK,eAAe;CAGvE,IAAI,CAAC,OAAO,IAAI,SAAS,WAAW,GAClC,UAAU,KAAK;IACf,SAAS,YAAY;;;;;;UAMf,SAAS,KAAK;UACd,SAAS,eAAe,UAAU,SAAS,WAAW,qDAAqD;CAGnH,IAAI,CAAC,OAAO,IAAI,SAAS,kBAAk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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,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;IACf,SAAS,gBAAgB;;8CAEiB,SAAS,KAAK,kBAAkB,SAAS,eAAe,GAAG,SAAS,WAAW,mBAAmB,SAA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,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;;;;;2EAKyD,SAAS,wDAAwD;CAG1I,IAAI,WAAW,QACb,SAAS,KAAK;oEACkD,SAAS;;;;wFAIW;CAKtF,IAAI,CAAC,OAAO,IAAI,UAAU,GACxB,SAAS,KAAK;;;4EAG0D;CAG1E,OAAO,SAAS,KAAK,IAAI;AAC3B"}
@@ -1 +1 @@
1
- {"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;AAyD7F,wBAAgB,2BAA2B,CAAC,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,wBAAwB;;;cAuB1G;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"}
1
+ {"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 ${PLAN_DIR_HINT}.`
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 ${PLAN_DIR_HINT}. Refusing to edit ${inputPath}.`
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\nconst PLAN_DIR_HINT = `${getLocalPlansRelativeDir()}/`;\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 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 ${PLAN_DIR_HINT}.`,\n };\n }\n\n // Plan mode may write any `.md` file directly inside `.mastracode/plans/`, but\n // nothing else in the project.\n if (isPlanFilePath(projectPath, inputPath)) return;\n\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${PLAN_DIR_HINT}. 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 `.mastracode/plans/` while the session is 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,uBAAuB,gBAAyB,KAAsB;CAC7E,IAAI,CAAC,gBAAgB,OAAO,KAAA;CAC5B,IAAI,OAAQ,eAAqC,QAAQ,YACvD,OAAQ,eAAqD,IAAI,GAAG;CAEtE,OAAQ,eAA2C;AACrD;AAcA,SAAS,kBAAkB,SAAoD;CAC7E,MAAM,iBAAkB,SAAsD;CAC9E,MAAM,UAAU,uBAAuB,gBAAgB,SAAS;CAChE,OAAO,WAAW,OAAO,YAAY,WAAY,UAAmC,KAAA;AACtF;AAEA,SAAS,gBAAgB,SAAgF;CACvG,MAAM,QAAQ,SAAS,SAAS,OAAO,MAAM;CAC7C,OAAO,SAAS,OAAO,UAAU,WAAY,QAAoC,KAAA;AACnF;AAEA,SAAS,iBAAiB,SAA+D;CACvF,MAAM,SAAS,SAAS,SAAS,UAAU,gBAAgB,OAAO,CAAC,EAAE;CACrE,OAAO,OAAO,WAAW,WAAW,SAAS,KAAA;AAC/C;AAEA,SAAS,sBAAsB,SAA+D;CAC5F,MAAM,cAAc,gBAAgB,OAAO,CAAC,EAAE;CAC9C,OAAO,OAAO,gBAAgB,WAAW,cAAc,KAAA;AACzD;AAEA,SAAS,iBAAiB,OAAoC;CAC5D,MAAM,WAAY,OAA0C;CAC5D,OAAO,OAAO,aAAa,WAAW,WAAW,KAAA;AACnD;AAEA,MAAM,gBAAgB,GAAG,yBAAyB,EAAE;AAEpD,SAAgB,4BAA4B,EAAE,mBAAmB,OAAO,WAAqC;CAC3G,IAAI,CAAC,2BAA2B,IAAI,iBAAiB,GAAG;CAExD,MAAM,UAAU,kBAAkB,OAAO;CACzC,IAAI,iBAAiB,OAAO,MAAM,QAAQ;CAE1C,MAAM,cAAc,sBAAsB,OAAO;CACjD,MAAM,YAAY,iBAAiB,KAAK;CACxC,IAAI,CAAC,eAAe,CAAC,WACnB,OAAO;EACL,SAAS;EACT,QAAQ,8CAA8C,cAAc;CACtE;CAKF,IAAI,eAAe,aAAa,SAAS,GAAG;CAE5C,OAAO;EACL,SAAS;EACT,QAAQ,8CAA8C,cAAc,qBAAqB,UAAU;CACrG;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"}
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,uBAAuB,gBAAyB,KAAsB;CAC7E,IAAI,CAAC,gBAAgB,OAAO,KAAA;CAC5B,IAAI,OAAQ,eAAqC,QAAQ,YACvD,OAAQ,eAAqD,IAAI,GAAG;CAEtE,OAAQ,eAA2C;AACrD;AAcA,SAAS,kBAAkB,SAAoD;CAC7E,MAAM,iBAAkB,SAAsD;CAC9E,MAAM,UAAU,uBAAuB,gBAAgB,SAAS;CAChE,OAAO,WAAW,OAAO,YAAY,WAAY,UAAmC,KAAA;AACtF;AAEA,SAAS,gBAAgB,SAAgF;CACvG,MAAM,QAAQ,SAAS,SAAS,OAAO,MAAM;CAC7C,OAAO,SAAS,OAAO,UAAU,WAAY,QAAoC,KAAA;AACnF;AAEA,SAAS,iBAAiB,SAA+D;CACvF,MAAM,SAAS,SAAS,SAAS,UAAU,gBAAgB,OAAO,CAAC,EAAE;CACrE,OAAO,OAAO,WAAW,WAAW,SAAS,KAAA;AAC/C;AAEA,SAAS,sBAAsB,SAA+D;CAC5F,MAAM,cAAc,gBAAgB,OAAO,CAAC,EAAE;CAC9C,OAAO,OAAO,gBAAgB,WAAW,cAAc,KAAA;AACzD;AAEA,SAAS,2BAA2B,SAA+D;CACjG,MAAM,mBAAmB,gBAAgB,OAAO,CAAC,EAAE;CACnD,OAAO,OAAO,qBAAqB,WAAW,mBAAmB,KAAA;AACnE;AAEA,SAAS,iBAAiB,OAAoC;CAC5D,MAAM,WAAY,OAA0C;CAC5D,OAAO,OAAO,aAAa,WAAW,WAAW,KAAA;AACnD;AAEA,SAAgB,4BAA4B,EAAE,mBAAmB,OAAO,WAAqC;CAC3G,IAAI,CAAC,2BAA2B,IAAI,iBAAiB,GAAG;CAExD,MAAM,UAAU,kBAAkB,OAAO;CACzC,IAAI,iBAAiB,OAAO,MAAM,QAAQ;CAG1C,MAAM,cAAc,EAAE,kBADG,2BAA2B,OACf,EAAE;CACvC,MAAM,cAAc,GAAG,yBAAyB,WAAW,EAAE;CAC7D,MAAM,cAAc,sBAAsB,OAAO;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"}
@@ -1,16 +1,19 @@
1
1
  /** Global plans directory for approved-plan archives. */
2
2
  export declare function getPlansDir(): string;
3
- /** Local (project-scoped) plans directory where the agent writes named plan files. */
4
- export declare function getLocalPlansDir(projectPath: string): string;
3
+ export interface LocalPlansOptions {
4
+ factoryProjectId?: string | null;
5
+ }
5
6
  /** Workspace-relative directory the agent writes plan files into. */
6
- export declare function getLocalPlansRelativeDir(): string;
7
+ export declare function getLocalPlansRelativeDir(options?: LocalPlansOptions): string;
8
+ /** Local (project-scoped) plans directory where the agent writes named plan files. */
9
+ export declare function getLocalPlansDir(projectPath: string, options?: LocalPlansOptions): string;
7
10
  /** Derive a plan filename from a title (e.g. `add-dark-mode.md`). */
8
11
  export declare function getPlanFilename(title: string): string;
9
12
  /**
10
13
  * Suggested workspace-relative path for a new plan file, shown in plan-mode prompts.
11
14
  * Without a title we fall back to a generic name the agent can rename later.
12
15
  */
13
- export declare function getSuggestedPlanRelativePath(title?: string): string;
16
+ export declare function getSuggestedPlanRelativePath(title?: string, options?: LocalPlansOptions): string;
14
17
  /**
15
18
  * Resolve a plan path submitted by the agent (absolute or project-relative) to an
16
19
  * absolute path. Returns `undefined` when no usable path was provided.
@@ -18,11 +21,11 @@ export declare function getSuggestedPlanRelativePath(title?: string): string;
18
21
  export declare function resolvePlanPath(projectPath: string, submittedPath: string): string | undefined;
19
22
  /**
20
23
  * Whether `targetPath` (absolute or project-relative) is a valid plan file: a `.md`
21
- * file located directly inside the project's `.mastracode/plans/` directory. Used by the
24
+ * file located directly inside the project's configured plan directory. Used by the
22
25
  * plan-mode write guard so the agent can write any named plan file there, but nothing
23
26
  * outside that directory.
24
27
  */
25
- export declare function isPlanFilePath(projectPath: string, targetPath: string): boolean;
28
+ export declare function isPlanFilePath(projectPath: string, targetPath: string, options?: LocalPlansOptions): boolean;
26
29
  export declare function savePlanToDisk(opts: {
27
30
  title: string;
28
31
  plan: string;
@@ -1 +1 @@
1
- {"version":3,"file":"plans.d.ts","sourceRoot":"","sources":["../../src/utils/plans.ts"],"names":[],"mappings":"AAKA,yDAAyD;AACzD,wBAAgB,WAAW,IAAI,MAAM,CAEpC;AAED,sFAAsF;AACtF,wBAAgB,gBA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EAAE,MAAM,CAAC;CACnB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAc9B"}
@@ -7,13 +7,13 @@ import fs from "fs/promises";
7
7
  function getPlansDir() {
8
8
  return process.env.MASTRA_PLANS_DIR ?? path.join(getAppDataDir(), "plans");
9
9
  }
10
- /** Local (project-scoped) plans directory where the agent writes named plan files. */
11
- function getLocalPlansDir(projectPath) {
12
- return path.join(projectPath, DEFAULT_CONFIG_DIR, "plans");
13
- }
14
10
  /** Workspace-relative directory the agent writes plan files into. */
15
- function getLocalPlansRelativeDir() {
16
- return path.join(DEFAULT_CONFIG_DIR, "plans");
11
+ function getLocalPlansRelativeDir(options = {}) {
12
+ return options.factoryProjectId ? path.join(".artifacts", "plans") : path.join(DEFAULT_CONFIG_DIR, "plans");
13
+ }
14
+ /** Local (project-scoped) plans directory where the agent writes named plan files. */
15
+ function getLocalPlansDir(projectPath, options = {}) {
16
+ return path.join(projectPath, getLocalPlansRelativeDir(options));
17
17
  }
18
18
  function slugify(str) {
19
19
  return str.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "untitled";
@@ -26,9 +26,9 @@ function getPlanFilename(title) {
26
26
  * Suggested workspace-relative path for a new plan file, shown in plan-mode prompts.
27
27
  * Without a title we fall back to a generic name the agent can rename later.
28
28
  */
29
- function getSuggestedPlanRelativePath(title) {
29
+ function getSuggestedPlanRelativePath(title, options = {}) {
30
30
  const filename = title ? getPlanFilename(title) : "plan.md";
31
- return path.join(getLocalPlansRelativeDir(), filename);
31
+ return path.join(getLocalPlansRelativeDir(options), filename);
32
32
  }
33
33
  /**
34
34
  * Resolve a plan path submitted by the agent (absolute or project-relative) to an
@@ -40,15 +40,15 @@ function resolvePlanPath(projectPath, submittedPath) {
40
40
  }
41
41
  /**
42
42
  * Whether `targetPath` (absolute or project-relative) is a valid plan file: a `.md`
43
- * file located directly inside the project's `.mastracode/plans/` directory. Used by the
43
+ * file located directly inside the project's configured plan directory. Used by the
44
44
  * plan-mode write guard so the agent can write any named plan file there, but nothing
45
45
  * outside that directory.
46
46
  */
47
- function isPlanFilePath(projectPath, targetPath) {
47
+ function isPlanFilePath(projectPath, targetPath, options = {}) {
48
48
  const abs = resolvePlanPath(projectPath, targetPath);
49
49
  if (!abs) return false;
50
50
  if (path.extname(abs).toLowerCase() !== ".md") return false;
51
- const plansDir = path.resolve(getLocalPlansDir(projectPath));
51
+ const plansDir = path.resolve(getLocalPlansDir(projectPath, options));
52
52
  const rel = path.relative(plansDir, abs);
53
53
  if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return false;
54
54
  return !rel.includes(path.sep);
@@ -1 +1 @@
1
- {"version":3,"file":"plans.js","names":[],"sources":["../../src/utils/plans.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { getAppDataDir } from './project.js';\n\n/** Global plans directory for approved-plan archives. */\nexport function getPlansDir(): string {\n return process.env.MASTRA_PLANS_DIR ?? path.join(getAppDataDir(), 'plans');\n}\n\n/** Local (project-scoped) plans directory where the agent writes named plan files. */\nexport function getLocalPlansDir(projectPath: string): string {\n return path.join(projectPath, DEFAULT_CONFIG_DIR, 'plans');\n}\n\n/** Workspace-relative directory the agent writes plan files into. */\nexport function getLocalPlansRelativeDir(): string {\n return path.join(DEFAULT_CONFIG_DIR, 'plans');\n}\n\nfunction slugify(str: string): string {\n const slug = str\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return slug || 'untitled';\n}\n\n/** Derive a plan filename from a title (e.g. `add-dark-mode.md`). */\nexport function getPlanFilename(title: string): string {\n return `${slugify(title)}.md`;\n}\n\n/**\n * Suggested workspace-relative path for a new plan file, shown in plan-mode prompts.\n * Without a title we fall back to a generic name the agent can rename later.\n */\nexport function getSuggestedPlanRelativePath(title?: string): string {\n const filename = title ? getPlanFilename(title) : 'plan.md';\n return path.join(getLocalPlansRelativeDir(), filename);\n}\n\n/**\n * Resolve a plan path submitted by the agent (absolute or project-relative) to an\n * absolute path. Returns `undefined` when no usable path was provided.\n */\nexport function resolvePlanPath(projectPath: string, submittedPath: string): string | undefined {\n if (!submittedPath) return undefined;\n return path.isAbsolute(submittedPath) ? submittedPath : path.resolve(projectPath, submittedPath);\n}\n\n/**\n * Whether `targetPath` (absolute or project-relative) is a valid plan file: a `.md`\n * file located directly inside the project's `.mastracode/plans/` directory. Used by the\n * plan-mode write guard so the agent can write any named plan file there, but nothing\n * outside that directory.\n */\nexport function isPlanFilePath(projectPath: string, targetPath: string): boolean {\n const abs = resolvePlanPath(projectPath, targetPath);\n if (!abs) return false;\n if (path.extname(abs).toLowerCase() !== '.md') return false;\n\n const plansDir = path.resolve(getLocalPlansDir(projectPath));\n const rel = path.relative(plansDir, abs);\n // Must be directly inside the plans dir (no nested subdirectories, no escaping it).\n if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return false;\n return !rel.includes(path.sep);\n}\n\nexport async function savePlanToDisk(opts: {\n title: string;\n plan: string;\n resourceId: string;\n plansDir?: string;\n}): Promise<void> {\n const { title, plan, resourceId } = opts;\n const plansDir = opts.plansDir ?? getPlansDir();\n const baseDir = path.resolve(plansDir);\n const dir = path.resolve(baseDir, resourceId);\n const rel = path.relative(baseDir, dir);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Invalid resourceId: ${resourceId}`);\n }\n\n await fs.mkdir(dir, { recursive: true });\n\n const now = new Date();\n const timestamp = now.toISOString().replace(/:/g, '-');\n const slug = slugify(title);\n const filename = `${timestamp}-${slug}.md`;\n\n const content = `# ${title}\\n\\nApproved: ${now.toISOString()}\\n\\n${plan}\\n`;\n\n await fs.writeFile(path.join(dir, filename), content, 'utf-8');\n}\n\n/**\n * Read a plan markdown file by absolute path.\n *\n * The leading `# <title>` heading (if present) is parsed as the title and the remaining\n * content is returned as the plan body. Returns `undefined` when the file does not exist.\n */\nexport async function readPlanFile(absPath: string): Promise<{ title: string; plan: string } | undefined> {\n let raw: string;\n try {\n raw = await fs.readFile(absPath, 'utf-8');\n } catch {\n return undefined;\n }\n\n const lines = raw.split(/\\r?\\n/);\n const headingIndex = lines.findIndex(line => line.trim().length > 0);\n const heading = headingIndex >= 0 ? lines[headingIndex] : undefined;\n if (heading?.startsWith('# ')) {\n const title = heading.slice(2).trim();\n const plan = lines\n .slice(headingIndex + 1)\n .join('\\n')\n .replace(/^\\n+/, '')\n .trimEnd();\n return { title, plan };\n }\n\n return { title: '', plan: raw.trimEnd() };\n}\n\n/**\n * Approve the plan file at `planPath`: write a timestamped copy to the global plans\n * archive so approved plans are findable later. The local named plan file is left in\n * place so the user can review every plan made over time.\n *\n * Returns the local plan filename (e.g. `add-dark-mode.md`), or `undefined` when there\n * was no plan file to approve.\n */\nexport async function approvePlanFile(opts: {\n planPath: string;\n title: string;\n resourceId: string;\n plansDir?: string;\n}): Promise<string | undefined> {\n const { planPath, title, resourceId, plansDir } = opts;\n\n const current = await readPlanFile(planPath);\n if (!current) {\n return undefined;\n }\n\n const resolvedTitle = title || current.title || 'Implementation Plan';\n\n // Global archive (timestamped, never overwritten) so approved plans are findable later.\n await savePlanToDisk({ title: resolvedTitle, plan: current.plan, resourceId, plansDir });\n\n return path.basename(planPath);\n}\n"],"mappings":";;;;;;AAMA,SAAgB,cAAsB;CACpC,OAAO,QAAQ,IAAI,oBAAoB,KAAK,KAAK,cAAc,GAAG,OAAO;AAC3E;;AAGA,SAAgB,iBAAiB,aAA6B;CAC5D,OAAO,KAAK,KAAK,aAAa,oBAAoB,OAAO;AAC3D;;AAGA,SAAgB,2BAAmC;CACjD,OAAO,KAAK,KAAK,oBAAoB,OAAO;AAC9C;AAEA,SAAS,QAAQ,KAAqB;CAKpC,OAJa,IACV,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,UAAU,EACX,KAAK;AACjB;;AAGA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,GAAG,QAA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,UAAU,KAAK,MAAM,gBAAgB,IAAI,YAAY,EAAE,MAAM,KAAK;CAExE,MAAM,GAAG,UAAU,KAAK,KAAK,KAAK,QAAQ,GAAG,SAAS,OAAO;AAC/D;;;;;;;AAQA,eAAsB,aAAa,SAAuE;CACxG,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,GAAG,SAAS,SAAS,OAAO;CAC1C,QAAQ;EACN;CACF;CAEA,MAAM,QAAQ,IAAI,MAAM,OAAO;CAC/B,MAAM,eAAe,MAAM,WAAU,SAAQ,KAAK,KAAK,CAAC,CAAC,SAAS,CAAC;CACnE,MAAM,UAAU,gBAAgB,IAAI,MAAM,gBAAgB,KAAA;CAC1D,IAAI,SAAS,WAAW,IAAI,GAO1B,OAAO;EAAE,OANK,QAAQ,MAAM,CAAC,CAAC,CAAC,KAMlB;EAAG,MALH,MACV,MAAM,eAAe,CAAC,CAAC,CACvB,KAAK,IAAI,CAAC,CACV,QAAQ,QAAQ,EAAE,CAAC,CACnB,QACgB;CAAE;CAGvB,OAAO;EAAE,OAAO;EAAI,MAAM,IAAI,QAAQ;CAAE;AAC1C;;;;;;;;;AAUA,eAAsB,gBAAgB,MAKN;CAC9B,MAAM,EAAE,UAAU,OAAO,YAAY,aAAa;CAElD,MAAM,UAAU,MAAM,aAAa,QAAQ;CAC3C,IAAI,CAAC,SACH;CAMF,MAAM,eAAe;EAAE,OAHD,SAAS,QAAQ,SAAS;EAGH,MAAM,QAAQ;EAAM;EAAY;CAAS,CAAC;CAEvF,OAAO,KAAK,SAAS,QAAQ;AAC/B"}
1
+ {"version":3,"file":"plans.js","names":[],"sources":["../../src/utils/plans.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { getAppDataDir } from './project.js';\n\n/** Global plans directory for approved-plan archives. */\nexport function getPlansDir(): string {\n return process.env.MASTRA_PLANS_DIR ?? path.join(getAppDataDir(), 'plans');\n}\n\nexport interface LocalPlansOptions {\n factoryProjectId?: string | null;\n}\n\n/** Workspace-relative directory the agent writes plan files into. */\nexport function getLocalPlansRelativeDir(options: LocalPlansOptions = {}): string {\n return options.factoryProjectId ? path.join('.artifacts', 'plans') : path.join(DEFAULT_CONFIG_DIR, 'plans');\n}\n\n/** Local (project-scoped) plans directory where the agent writes named plan files. */\nexport function getLocalPlansDir(projectPath: string, options: LocalPlansOptions = {}): string {\n return path.join(projectPath, getLocalPlansRelativeDir(options));\n}\n\nfunction slugify(str: string): string {\n const slug = str\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return slug || 'untitled';\n}\n\n/** Derive a plan filename from a title (e.g. `add-dark-mode.md`). */\nexport function getPlanFilename(title: string): string {\n return `${slugify(title)}.md`;\n}\n\n/**\n * Suggested workspace-relative path for a new plan file, shown in plan-mode prompts.\n * Without a title we fall back to a generic name the agent can rename later.\n */\nexport function getSuggestedPlanRelativePath(title?: string, options: LocalPlansOptions = {}): string {\n const filename = title ? getPlanFilename(title) : 'plan.md';\n return path.join(getLocalPlansRelativeDir(options), filename);\n}\n\n/**\n * Resolve a plan path submitted by the agent (absolute or project-relative) to an\n * absolute path. Returns `undefined` when no usable path was provided.\n */\nexport function resolvePlanPath(projectPath: string, submittedPath: string): string | undefined {\n if (!submittedPath) return undefined;\n return path.isAbsolute(submittedPath) ? submittedPath : path.resolve(projectPath, submittedPath);\n}\n\n/**\n * Whether `targetPath` (absolute or project-relative) is a valid plan file: a `.md`\n * file located directly inside the project's configured plan directory. Used by the\n * plan-mode write guard so the agent can write any named plan file there, but nothing\n * outside that directory.\n */\nexport function isPlanFilePath(projectPath: string, targetPath: string, options: LocalPlansOptions = {}): boolean {\n const abs = resolvePlanPath(projectPath, targetPath);\n if (!abs) return false;\n if (path.extname(abs).toLowerCase() !== '.md') return false;\n\n const plansDir = path.resolve(getLocalPlansDir(projectPath, options));\n const rel = path.relative(plansDir, abs);\n // Must be directly inside the plans dir (no nested subdirectories, no escaping it).\n if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return false;\n return !rel.includes(path.sep);\n}\n\nexport async function savePlanToDisk(opts: {\n title: string;\n plan: string;\n resourceId: string;\n plansDir?: string;\n}): Promise<void> {\n const { title, plan, resourceId } = opts;\n const plansDir = opts.plansDir ?? getPlansDir();\n const baseDir = path.resolve(plansDir);\n const dir = path.resolve(baseDir, resourceId);\n const rel = path.relative(baseDir, dir);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Invalid resourceId: ${resourceId}`);\n }\n\n await fs.mkdir(dir, { recursive: true });\n\n const now = new Date();\n const timestamp = now.toISOString().replace(/:/g, '-');\n const slug = slugify(title);\n const filename = `${timestamp}-${slug}.md`;\n\n const content = `# ${title}\\n\\nApproved: ${now.toISOString()}\\n\\n${plan}\\n`;\n\n await fs.writeFile(path.join(dir, filename), content, 'utf-8');\n}\n\n/**\n * Read a plan markdown file by absolute path.\n *\n * The leading `# <title>` heading (if present) is parsed as the title and the remaining\n * content is returned as the plan body. Returns `undefined` when the file does not exist.\n */\nexport async function readPlanFile(absPath: string): Promise<{ title: string; plan: string } | undefined> {\n let raw: string;\n try {\n raw = await fs.readFile(absPath, 'utf-8');\n } catch {\n return undefined;\n }\n\n const lines = raw.split(/\\r?\\n/);\n const headingIndex = lines.findIndex(line => line.trim().length > 0);\n const heading = headingIndex >= 0 ? lines[headingIndex] : undefined;\n if (heading?.startsWith('# ')) {\n const title = heading.slice(2).trim();\n const plan = lines\n .slice(headingIndex + 1)\n .join('\\n')\n .replace(/^\\n+/, '')\n .trimEnd();\n return { title, plan };\n }\n\n return { title: '', plan: raw.trimEnd() };\n}\n\n/**\n * Approve the plan file at `planPath`: write a timestamped copy to the global plans\n * archive so approved plans are findable later. The local named plan file is left in\n * place so the user can review every plan made over time.\n *\n * Returns the local plan filename (e.g. `add-dark-mode.md`), or `undefined` when there\n * was no plan file to approve.\n */\nexport async function approvePlanFile(opts: {\n planPath: string;\n title: string;\n resourceId: string;\n plansDir?: string;\n}): Promise<string | undefined> {\n const { planPath, title, resourceId, plansDir } = opts;\n\n const current = await readPlanFile(planPath);\n if (!current) {\n return undefined;\n }\n\n const resolvedTitle = title || current.title || 'Implementation Plan';\n\n // Global archive (timestamped, never overwritten) so approved plans are findable later.\n await savePlanToDisk({ title: resolvedTitle, plan: current.plan, resourceId, plansDir });\n\n return path.basename(planPath);\n}\n"],"mappings":";;;;;;AAMA,SAAgB,cAAsB;CACpC,OAAO,QAAQ,IAAI,oBAAoB,KAAK,KAAK,cAAc,GAAG,OAAO;AAC3E;;AAOA,SAAgB,yBAAyB,UAA6B,CAAC,GAAW;CAChF,OAAO,QAAQ,mBAAmB,KAAK,KAAK,cAAc,OAAO,IAAI,KAAK,KAAK,oBAAoB,OAAO;AAC5G;;AAGA,SAAgB,iBAAiB,aAAqB,UAA6B,CAAC,GAAW;CAC7F,OAAO,KAAK,KAAK,aAAa,yBAAyB,OAAO,CAAC;AACjE;AAEA,SAAS,QAAQ,KAAqB;CAKpC,OAJa,IACV,YAAY,CAAC,CACb,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,UAAU,EACX,KAAK;AACjB;;AAGA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,GAAG,QAAQ,KAAK,EAAE;AAC3B;;;;;AAMA,SAAgB,6BAA6B,OAAgB,UAA6B,CAAC,GAAW;CACpG,MAAM,WAAW,QAAQ,gBAAgB,KAAK,IAAI;CAClD,OAAO,KAAK,KAAK,yBAAyB,OAAO,GAAG,QAAQ;AAC9D;;;;;AAMA,SAAgB,gBAAgB,aAAqB,eAA2C;CAC9F,IAAI,CAAC,eAAe,OAAO,KAAA;CAC3B,OAAO,KAAK,WAAW,aAAa,IAAI,gBAAgB,KAAK,QAAQ,aAAa,aAAa;AACjG;;;;;;;AAQA,SAAgB,eAAe,aAAqB,YAAoB,UAA6B,CAAC,GAAY;CAChH,MAAM,MAAM,gBAAgB,aAAa,UAAU;CACnD,IAAI,CAAC,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M,gBAAgB,KAAA;CAC1D,IAAI,SAAS,WAAW,IAAI,GAO1B,OAAO;EAAE,OANK,QAAQ,MAAM,CAAC,CAAC,CAAC,KAMlB;EAAG,MALH,MACV,MAAM,eAAe,CAAC,CAAC,CACvB,KAAK,IAAI,CAAC,CACV,QAAQ,QAAQ,EAAE,CAAC,CACnB,QACgB;CAAE;CAGvB,OAAO;EAAE,OAAO;EAAI,MAAM,IAAI,QAAQ;CAAE;AAC1C;;;;;;;;;AAUA,eAAsB,gBAAgB,MAKN;CAC9B,MAAM,EAAE,UAAU,OAAO,YAAY,aAAa;CAElD,MAAM,UAAU,MAAM,aAAa,QAAQ;CAC3C,IAAI,CAAC,SACH;CAMF,MAAM,eAAe;EAAE,OAHD,SAAS,QAAQ,SAAS;EAGH,MAAM,QAAQ;EAAM;EAAY;CAAS,CAAC;CAEvF,OAAO,KAAK,SAAS,QAAQ;AAC/B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/code-sdk",
3
- "version": "1.2.0-alpha.13",
3
+ "version": "1.2.0-alpha.14",
4
4
  "description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -56,19 +56,19 @@
56
56
  "vscode-languageserver-protocol": "^3.17.5",
57
57
  "yaml": "^2.7.1",
58
58
  "zod": "^4.3.6",
59
- "@mastra/duckdb": "1.6.1-alpha.0",
60
59
  "@mastra/agent-browser": "0.5.1-alpha.0",
61
- "@mastra/github-signals": "0.2.5-alpha.1",
62
60
  "@mastra/core": "1.58.0-alpha.12",
63
- "@mastra/libsql": "1.20.0-alpha.2",
64
61
  "@mastra/fastembed": "1.2.0",
65
- "@mastra/memory": "1.26.1-alpha.6",
62
+ "@mastra/duckdb": "1.6.1-alpha.0",
63
+ "@mastra/github-signals": "0.2.5-alpha.1",
64
+ "@mastra/libsql": "1.20.0-alpha.2",
66
65
  "@mastra/mcp": "1.16.0-alpha.2",
67
66
  "@mastra/observability": "1.16.6-alpha.3",
67
+ "@mastra/memory": "1.26.1-alpha.6",
68
68
  "@mastra/pg": "1.20.0-alpha.3",
69
- "@mastra/schema-compat": "1.3.6-alpha.3",
69
+ "@mastra/tavily": "1.1.1",
70
70
  "@mastra/stagehand": "0.3.2-alpha.1",
71
- "@mastra/tavily": "1.1.1"
71
+ "@mastra/schema-compat": "1.3.6-alpha.3"
72
72
  },
73
73
  "devDependencies": {
74
74
  "@libsql/client": "^0.17.4",
@@ -80,8 +80,8 @@
80
80
  "typescript-eslint": "^8.57.0",
81
81
  "vitest": "4.1.10",
82
82
  "@internal/types-builder": "0.0.96",
83
- "@internal/lint": "0.0.121",
84
- "@internal/workspace-test-utils": "0.0.65"
83
+ "@internal/workspace-test-utils": "0.0.65",
84
+ "@internal/lint": "0.0.121"
85
85
  },
86
86
  "engines": {
87
87
  "node": ">=22.19.0"