@mastra/code-sdk 1.18.0 → 1.19.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.js +2 -2
- package/dist/acp/runtime.js +2 -2
- package/dist/agent-connections/state-processor.js +3 -3
- package/dist/agent-connections/tools.js +2 -2
- package/dist/agents/instructions.d.ts +5 -2
- package/dist/agents/instructions.d.ts.map +1 -1
- package/dist/agents/instructions.js +5 -3
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/mastracode-gateway.d.ts +1 -0
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +12 -8
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/memory.js +2 -2
- package/dist/agents/model.js +5 -5
- package/dist/agents/prompts/index.d.ts +2 -0
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +8 -5
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/prompts/plan.d.ts +1 -0
- package/dist/agents/prompts/plan.d.ts.map +1 -1
- package/dist/agents/prompts/plan.js +4 -1
- package/dist/agents/prompts/plan.js.map +1 -1
- package/dist/agents/prompts/tool-guidance.d.ts.map +1 -1
- package/dist/agents/prompts/tool-guidance.js +9 -1
- package/dist/agents/prompts/tool-guidance.js.map +1 -1
- package/dist/agents/tool-availability.d.ts +7 -2
- package/dist/agents/tool-availability.d.ts.map +1 -1
- package/dist/agents/tool-availability.js +15 -7
- package/dist/agents/tool-availability.js.map +1 -1
- package/dist/agents/tools.js +2 -2
- package/dist/agents/workflow-builder-agent.js +2 -2
- package/dist/agents/workspace.d.ts +3 -1
- package/dist/agents/workspace.d.ts.map +1 -1
- package/dist/agents/workspace.js +3 -3
- package/dist/agents/workspace.js.map +1 -1
- package/dist/auth/account-rotation-processor.js +4 -4
- package/dist/auth/index.js +3 -3
- package/dist/evals/index.js +1 -1
- package/dist/factory/client.d.ts +4 -1
- package/dist/factory/client.d.ts.map +1 -1
- package/dist/factory/client.js +22 -7
- package/dist/factory/client.js.map +1 -1
- package/dist/headless/cli.js +7 -7
- package/dist/headless/index.js +2 -2
- package/dist/headless/run-mc.js +2 -2
- package/dist/hooks/index.js +2 -2
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +36 -33
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/onboarding/settings.js +2 -2
- package/dist/plugins/install.js +2 -2
- package/dist/plugins/manager.js +3 -3
- package/dist/providers/claude-max.js +5 -5
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/github-copilot.js +2 -2
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/google-thinking.js +1 -1
- package/dist/providers/google-thinking.js.map +1 -1
- package/dist/providers/kimi-coding.js +1 -1
- package/dist/providers/openai-codex.js +5 -5
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/provider-thinking.d.ts +1 -1
- package/dist/providers/provider-thinking.d.ts.map +1 -1
- package/dist/providers/provider-thinking.js +2 -2
- package/dist/providers/provider-thinking.js.map +1 -1
- package/dist/providers/xai.js +1 -1
- package/dist/schedules/tools.js +1 -1
- package/dist/tools/utils.js +1 -1
- package/dist/tools/workflows/list-available-tools.js +1 -1
- package/dist/utils/plans.d.ts +2 -0
- package/dist/utils/plans.d.ts.map +1 -1
- package/dist/utils/plans.js +6 -0
- package/dist/utils/plans.js.map +1 -1
- package/dist/utils/prune-cli.js +2 -2
- package/dist/voice/stt-registry.d.ts +6 -3
- package/dist/voice/stt-registry.d.ts.map +1 -1
- package/dist/voice/stt-registry.js +13 -10
- package/dist/voice/stt-registry.js.map +1 -1
- package/dist/voice/transcribe.d.ts +10 -0
- package/dist/voice/transcribe.d.ts.map +1 -0
- package/dist/voice/transcribe.js +77 -0
- package/dist/voice/transcribe.js.map +1 -0
- package/dist/workflows/register-primitives.js +2 -2
- package/package.json +19 -15
|
@@ -5,7 +5,10 @@ import { getLocalPlansRelativeDir } from "../../utils/plans.js";
|
|
|
5
5
|
*/
|
|
6
6
|
function planModePrompt(ctx) {
|
|
7
7
|
const factoryProjectId = typeof ctx.state?.factoryProjectId === "string" ? ctx.state.factoryProjectId : void 0;
|
|
8
|
-
const plansDir = getLocalPlansRelativeDir({
|
|
8
|
+
const plansDir = getLocalPlansRelativeDir({
|
|
9
|
+
factoryProjectId,
|
|
10
|
+
plansDir: ctx.plansDir
|
|
11
|
+
});
|
|
9
12
|
const examplePath = `${plansDir}/add-dark-mode.md`;
|
|
10
13
|
const submitPlanAvailable = ctx.submitPlanAvailable !== false;
|
|
11
14
|
return `
|
|
@@ -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 /** False when the host disabled or denied `submit_plan`; defaults to available. */\n submitPlanAvailable?: boolean;\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 const submitPlanAvailable = ctx.submitPlanAvailable !== false;\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${submitPlanAvailable ? GOAL_READY_SECTION : ''}## 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. **${submitPlanAvailable ? 'First submission' : 'Writing'}**: Write your plan to a file under \\`${plansDir}/\\` using \\`write_file\\`${submitPlanAvailable ? ', 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${submitPlanAvailable ? submitPlanSection(plansDir, examplePath) : planFileOnlySection(plansDir)}Do NOT start implementing until the plan is approved.\n`;\n}\n\nconst GOAL_READY_SECTION = `## 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`;\n\nfunction submitPlanSection(plansDir: string, examplePath: string): string {\n return `## 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\n`;\n}\n\nfunction planFileOnlySection(plansDir: string): string {\n return `## When the plan is complete\n\nPlan approval is not available in this session — there is no \\`submit_plan\\` tool. As soon as your plan is complete:\n1. Write it to a file under \\`${plansDir}/\\` using \\`write_file\\`\n2. Follow any host or session instructions for handing the plan off; otherwise reply with a brief summary and the plan file path\n\n**CRITICAL:** Do NOT generate a long text response describing your plan. The plan content belongs in the plan file.\n\nWhen you receive revision feedback, edit the SAME plan file with \\`string_replace_lsp\\` rather than rewriting it or moving it to a new file.\n\n`;\n}\n"],"mappings":";;;;;
|
|
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 plansDir?: string;\n /** False when the host disabled or denied `submit_plan`; defaults to available. */\n submitPlanAvailable?: boolean;\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, plansDir: ctx.plansDir });\n const examplePath = `${plansDir}/add-dark-mode.md`;\n const submitPlanAvailable = ctx.submitPlanAvailable !== false;\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${submitPlanAvailable ? GOAL_READY_SECTION : ''}## 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. **${submitPlanAvailable ? 'First submission' : 'Writing'}**: Write your plan to a file under \\`${plansDir}/\\` using \\`write_file\\`${submitPlanAvailable ? ', 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${submitPlanAvailable ? submitPlanSection(plansDir, examplePath) : planFileOnlySection(plansDir)}Do NOT start implementing until the plan is approved.\n`;\n}\n\nconst GOAL_READY_SECTION = `## 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`;\n\nfunction submitPlanSection(plansDir: string, examplePath: string): string {\n return `## 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\n`;\n}\n\nfunction planFileOnlySection(plansDir: string): string {\n return `## When the plan is complete\n\nPlan approval is not available in this session — there is no \\`submit_plan\\` tool. As soon as your plan is complete:\n1. Write it to a file under \\`${plansDir}/\\` using \\`write_file\\`\n2. Follow any host or session instructions for handing the plan off; otherwise reply with a brief summary and the plan file path\n\n**CRITICAL:** Do NOT generate a long text response describing your plan. The plan content belongs in the plan file.\n\nWhen you receive revision feedback, edit the SAME plan file with \\`string_replace_lsp\\` rather than rewriting it or moving it to a new file.\n\n`;\n}\n"],"mappings":";;;;;AAYA,SAAgB,eAAe,KAAgC;CAC7D,MAAM,mBAAmB,OAAO,IAAI,OAAO,qBAAqB,WAAW,IAAI,MAAM,mBAAmB,KAAA;CACxG,MAAM,WAAW,yBAAyB;EAAE;EAAkB,UAAU,IAAI;CAAS,CAAC;CACtF,MAAM,cAAc,GAAG,SAAS;CAChC,MAAM,sBAAsB,IAAI,wBAAwB;CAExD,OAAO;;;;;;;;;;;;;mFAa0E,SAAS,cAAc,YAAY;;;;;;;;;;;;;EAapH,sBAAsB,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;mDAyBG,SAAS,cAAc,YAAY;;OAE/E,sBAAsB,qBAAqB,UAAU,wCAAwC,SAAS,0BAA0B,sBAAsB,2DAA+D,GAAG;;;;;;EAM7N,sBAAsB,kBAAkB,UAAU,WAAW,IAAI,oBAAoB,QAAQ,EAAE;;AAEjG;AAEA,MAAM,qBAAqB;;;;;;;;;AAU3B,SAAS,kBAAkB,UAAkB,aAA6B;CACxE,OAAO;;;gCAGuB,SAAS;;;;;;;WAO9B,YAAY;;;;;;;;;;;;;;;;;;;;AAoBvB;AAEA,SAAS,oBAAoB,UAA0B;CACrD,OAAO;;;gCAGuB,SAAS;;;;;;;;AAQzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAMH,UAAU,mBAAmB;IAC3B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,mGAAmG;IACnG,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,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,CAqP3F"}
|
|
@@ -5,9 +5,10 @@ import { MC_TOOLS } from "../../tool-names.js";
|
|
|
5
5
|
* Generates tool usage instructions that match the actual registered tool names
|
|
6
6
|
* and are scoped to what's available in the current mode.
|
|
7
7
|
*/
|
|
8
|
+
const DEFAULT_PLANS_DIR = ".mastracode/plans";
|
|
8
9
|
function buildToolGuidance(modeId, options = {}) {
|
|
9
10
|
const denied = options.deniedTools ?? /* @__PURE__ */ new Set();
|
|
10
|
-
const plansDir = options.plansDir ?? "
|
|
11
|
+
const plansDir = (options.plansDir ?? DEFAULT_PLANS_DIR).replaceAll("\\", "/");
|
|
11
12
|
const sections = [];
|
|
12
13
|
sections.push(`# Tool Usage Rules
|
|
13
14
|
|
|
@@ -135,6 +136,13 @@ ${patchToolGuidance}
|
|
|
135
136
|
- The plan will be rendered as markdown and the user can approve, reject, or request changes.
|
|
136
137
|
- On approval, the system automatically switches to the default mode so you can implement.
|
|
137
138
|
- Takes one argument: \`path\` (the plan markdown file you wrote under \`${plansDir}/\`). Do NOT pass the plan body — it lives in the file.`);
|
|
139
|
+
if (modeId !== "plan" && modeId !== "fast" && !denied.has("submit_plan")) {
|
|
140
|
+
const elsewhere = plansDir === DEFAULT_PLANS_DIR ? "" : `, never under \`${DEFAULT_PLANS_DIR}/\`. Plans anywhere else cannot be shown to the user`;
|
|
141
|
+
sections.push(`
|
|
142
|
+
**submit_plan** — Submit a plan for user review
|
|
143
|
+
- Write plan files under \`${plansDir}/\` (e.g. \`${plansDir}/add-dark-mode.md\`)${elsewhere}.
|
|
144
|
+
- Pass that file's \`path\` to \`submit_plan\`. Do NOT pass the plan body — it lives in the file.`);
|
|
145
|
+
}
|
|
138
146
|
if (modeId === "plan") sections.push(`
|
|
139
147
|
**Plan file access** — Your plan lives in a markdown file under \`${plansDir}/\` (e.g. \`add-dark-mode-toggle.md\`)
|
|
140
148
|
- Use \`write_file\` to create the plan file, \`view\` to read it, and \`string_replace_lsp\` for targeted edits.
|
|
@@ -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 /** `web_extract` is registered (Parallel/Tavily); provider-executed search has no extract tool. */\n hasWebExtract?: boolean;\n hasSubagents?: 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 file contents. Don't propose changes to code you haven't seen; reading with shell commands (cat, sed, rg) also works.\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- Always set \\`description\\` to a 5-10 word summary of what the command does; the user sees it instead of the raw command. Put it first in the arguments, before \\`command\\`, so the user sees it while the rest of the call streams in. Write each one as the next step in a running narrative that can lean on earlier commands (e.g. \"Searching open PRs for failing CI\", then \"Drilling into the first of 15 failures\").\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- \\`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- Overwriting replaces the whole file, so make sure you know its current contents first.\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 (options.hasWebExtract && !denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n const purpose =\n webTools.length === 2\n ? 'Search the web / extract page content'\n : webTools[0] === '**web_search**'\n ? 'Search the web'\n : 'Extract page content';\n sections.push(`\n${webTools.join(' / ')} — ${purpose}\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 (options.hasSubagents !== false && !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":";;;;;;;AAmBA,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,SAAS,mBAAmB,GAAG,SAAS,WAAW;;;;;4CAKvJ,SAAS,KAAK,eAAe;CAGvE,IAAI,CAAC,OAAO,IAAI,SAAS,WAAW,GAClC,UAAU,KAAK;IACf,SAAS,YAAY;;;;;;UAMf,SAAS,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AAkB;;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,QAAQ,iBAAiB,SAAS,CAAC,OAAO,IAAI,UAAU,GAC1D,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\nconst DEFAULT_PLANS_DIR = '.mastracode/plans';\n\ninterface ToolGuidanceOptions {\n hasWebSearch?: boolean;\n /** `web_extract` is registered (Parallel/Tavily); provider-executed search has no extract tool. */\n hasWebExtract?: boolean;\n hasSubagents?: 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 // Name the dir with `/` so the win32 default (`.mastracode\\plans`) still matches DEFAULT_PLANS_DIR.\n const plansDir = (options.plansDir ?? DEFAULT_PLANS_DIR).replaceAll('\\\\', '/');\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 file contents. Don't propose changes to code you haven't seen; reading with shell commands (cat, sed, rg) also works.\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- Always set \\`description\\` to a 5-10 word summary of what the command does; the user sees it instead of the raw command. Put it first in the arguments, before \\`command\\`, so the user sees it while the rest of the call streams in. Write each one as the next step in a running narrative that can lean on earlier commands (e.g. \"Searching open PRs for failing CI\", then \"Drilling into the first of 15 failures\").\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- \\`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- Overwriting replaces the whole file, so make sure you know its current contents first.\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 (options.hasWebExtract && !denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n const purpose =\n webTools.length === 2\n ? 'Search the web / extract page content'\n : webTools[0] === '**web_search**'\n ? 'Search the web'\n : 'Extract page content';\n sections.push(`\n${webTools.join(' / ')} — ${purpose}\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 // Outside plan mode nothing else names the plans directory (the submit_plan\n // tool example is directory-neutral), so state it here. Explore (`fast`) mode\n // is read-only and has neither submit_plan nor file writes.\n if (modeId !== 'plan' && modeId !== 'fast' && !denied.has('submit_plan')) {\n const elsewhere =\n plansDir === DEFAULT_PLANS_DIR\n ? ''\n : `, never under \\`${DEFAULT_PLANS_DIR}/\\`. Plans anywhere else cannot be shown to the user`;\n sections.push(`\n**submit_plan** — Submit a plan for user review\n- Write plan files under \\`${plansDir}/\\` (e.g. \\`${plansDir}/add-dark-mode.md\\`)${elsewhere}.\n- Pass that file's \\`path\\` to \\`submit_plan\\`. 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 (options.hasSubagents !== false && !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":";;;;;;;AAQA,MAAM,oBAAoB;AAa1B,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,+BAAe,IAAI,IAAY;CAEtD,MAAM,YAAY,QAAQ,YAAY,kBAAA,CAAmB,WAAW,MAAM,GAAG;CAC7E,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;;;;;4CAKvJ,SAAS,KAAK,eAAe;CAGvE,IAAI,CAAC,OAAO,IAAI,SAAS,WAAW,G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,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;CAM1I,IAAI,WAAW,UAAU,WAAW,UAAU,CAAC,OAAO,IAAI,aAAa,GAAG;EACxE,MAAM,YACJ,aAAa,oBACT,KACA,mBAAmB,kBAAkB;EAC3C,SAAS,KAAK;;6BAEW,SAAS,cAAc,SAAS,sBAAsB,UAAU;kGACK;CAChG;CAEA,IAAI,WAAW,QACb,SAAS,KAAK;oEACkD,SAAS;;;;wFAIW;CAKtF,IAAI,QAAQ,iBAAiB,SAAS,CAAC,OAAO,IAAI,UAAU,GAC1D,SAAS,KAAK;;;4EAG0D;CAG1E,OAAO,SAAS,KAAK,IAAI;AAC3B"}
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import type { WorkspaceToolHookContext, WorkspaceToolsConfig } from '@mastra/core/workspace';
|
|
2
|
-
|
|
2
|
+
/** Plan-mode write guard; `plansDir` is the host-configured plans directory, if any. */
|
|
3
|
+
export declare function createPlanModePlanFileWriteGuard(plansDir?: string): (hookContext: WorkspaceToolHookContext) => {
|
|
3
4
|
proceed: false;
|
|
4
5
|
output: string;
|
|
5
6
|
} | undefined;
|
|
6
|
-
export declare
|
|
7
|
+
export declare const guardPlanModePlanFileWrites: (hookContext: WorkspaceToolHookContext) => {
|
|
8
|
+
proceed: false;
|
|
9
|
+
output: string;
|
|
10
|
+
} | undefined;
|
|
11
|
+
export declare function createMastraCodeWorkspaceTools(backgroundToolsEnabled?: boolean, plansDir?: string): WorkspaceToolsConfig;
|
|
7
12
|
/** Default foreground-only configuration for consumers without Mastra Code settings. */
|
|
8
13
|
export declare const MASTRACODE_WORKSPACE_TOOLS: WorkspaceToolsConfig;
|
|
9
14
|
export declare const PLAN_MODE_AVAILABLE_TOOLS: readonly string[];
|
|
@@ -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;AA4D7F,wBAAgB,
|
|
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,wFAAwF;AACxF,wBAAgB,gCAAgC,CAAC,QAAQ,CAAC,EAAE,MAAM,iBAC3C,wBAAwB;;;cAC9C;AAED,eAAO,MAAM,2BAA2B,gBAHjB,wBAAwB;;;aAG8B,CAAC;AAgC9E,wBAAgB,8BAA8B,CAC5C,sBAAsB,UAAQ,EAC9B,QAAQ,CAAC,EAAE,MAAM,GAChB,oBAAoB,CAiCtB;AAED,wFAAwF;AACxF,eAAO,MAAM,0BAA0B,sBAAmC,CAAC;AAE3E,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAwBtD,CAAC;AAEF,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EAUzD,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAMtD,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { getLocalPlansRelativeDir, isPlanFilePath } from "../utils/plans.js";
|
|
2
1
|
import { MC_TOOLS, TOOL_NAME_OVERRIDES } from "../tool-names.js";
|
|
2
|
+
import { getLocalPlansRelativeDir, isPlanFilePath } from "../utils/plans.js";
|
|
3
3
|
import { WORKSPACE_TOOLS } from "@mastra/core/workspace";
|
|
4
4
|
// src/agents/tool-availability.ts
|
|
5
5
|
const PLAN_MODE_WRITE_TOOL_NAMES = /* @__PURE__ */ new Set([WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE, WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE]);
|
|
@@ -10,7 +10,7 @@ function getRequestContextValue(requestContext, key) {
|
|
|
10
10
|
}
|
|
11
11
|
function getHarnessContext(context) {
|
|
12
12
|
const requestContext = context?.requestContext;
|
|
13
|
-
const harness = getRequestContextValue(requestContext, "
|
|
13
|
+
const harness = getRequestContextValue(requestContext, "controller");
|
|
14
14
|
return harness && typeof harness === "object" ? harness : void 0;
|
|
15
15
|
}
|
|
16
16
|
function getHarnessState(harness) {
|
|
@@ -33,11 +33,19 @@ function getToolInputPath(input) {
|
|
|
33
33
|
const toolPath = input?.path;
|
|
34
34
|
return typeof toolPath === "string" ? toolPath : void 0;
|
|
35
35
|
}
|
|
36
|
-
|
|
36
|
+
/** Plan-mode write guard; `plansDir` is the host-configured plans directory, if any. */
|
|
37
|
+
function createPlanModePlanFileWriteGuard(plansDir) {
|
|
38
|
+
return (hookContext) => guardPlanFileWrite(hookContext, plansDir);
|
|
39
|
+
}
|
|
40
|
+
const guardPlanModePlanFileWrites = createPlanModePlanFileWriteGuard();
|
|
41
|
+
function guardPlanFileWrite({ workspaceToolName, input, context }, plansDir) {
|
|
37
42
|
if (!PLAN_MODE_WRITE_TOOL_NAMES.has(workspaceToolName)) return;
|
|
38
43
|
const harness = getHarnessContext(context);
|
|
39
44
|
if (getHarnessModeId(harness) !== "plan") return;
|
|
40
|
-
const planOptions = {
|
|
45
|
+
const planOptions = {
|
|
46
|
+
factoryProjectId: getHarnessFactoryProjectId(harness),
|
|
47
|
+
plansDir
|
|
48
|
+
};
|
|
41
49
|
const planDirHint = `${getLocalPlansRelativeDir(planOptions)}/`;
|
|
42
50
|
const projectPath = getHarnessProjectPath(harness);
|
|
43
51
|
const inputPath = getToolInputPath(input);
|
|
@@ -55,7 +63,7 @@ const BACKGROUND_TOOL_CONFIG = {
|
|
|
55
63
|
enabled: true,
|
|
56
64
|
defaultDisposition: "foreground"
|
|
57
65
|
};
|
|
58
|
-
function createMastraCodeWorkspaceTools(backgroundToolsEnabled = false) {
|
|
66
|
+
function createMastraCodeWorkspaceTools(backgroundToolsEnabled = false, plansDir) {
|
|
59
67
|
const background = backgroundToolsEnabled ? BACKGROUND_TOOL_CONFIG : void 0;
|
|
60
68
|
return {
|
|
61
69
|
...TOOL_NAME_OVERRIDES,
|
|
@@ -83,7 +91,7 @@ function createMastraCodeWorkspaceTools(backgroundToolsEnabled = false) {
|
|
|
83
91
|
...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.LSP.LSP_INSPECT],
|
|
84
92
|
...background ? { background } : {}
|
|
85
93
|
},
|
|
86
|
-
hooks: { beforeToolCall:
|
|
94
|
+
hooks: { beforeToolCall: createPlanModePlanFileWriteGuard(plansDir) }
|
|
87
95
|
};
|
|
88
96
|
}
|
|
89
97
|
/** Default foreground-only configuration for consumers without Mastra Code settings. */
|
|
@@ -123,6 +131,6 @@ const GOAL_JUDGE_READONLY_TOOLS = [
|
|
|
123
131
|
MC_TOOLS.FILE_STAT,
|
|
124
132
|
MC_TOOLS.LSP_INSPECT
|
|
125
133
|
];
|
|
126
|
-
export { EXPLORE_MODE_AVAILABLE_TOOLS, GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS, PLAN_MODE_AVAILABLE_TOOLS, createMastraCodeWorkspaceTools, guardPlanModePlanFileWrites };
|
|
134
|
+
export { EXPLORE_MODE_AVAILABLE_TOOLS, GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS, PLAN_MODE_AVAILABLE_TOOLS, createMastraCodeWorkspaceTools, createPlanModePlanFileWriteGuard, guardPlanModePlanFileWrites };
|
|
127
135
|
|
|
128
136
|
//# sourceMappingURL=tool-availability.js.map
|
|
@@ -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
|
|
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 `AgentControllerRequestContext` the controller sets under the\n * `controller` request-context key. 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, 'controller');\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\n/** Plan-mode write guard; `plansDir` is the host-configured plans directory, if any. */\nexport function createPlanModePlanFileWriteGuard(plansDir?: string) {\n return (hookContext: WorkspaceToolHookContext) => guardPlanFileWrite(hookContext, plansDir);\n}\n\nexport const guardPlanModePlanFileWrites = createPlanModePlanFileWriteGuard();\n\nfunction guardPlanFileWrite({ workspaceToolName, input, context }: WorkspaceToolHookContext, plansDir?: string) {\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, plansDir };\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\nconst BACKGROUND_TOOL_CONFIG = { enabled: true, defaultDisposition: 'foreground' } as const;\n\nexport function createMastraCodeWorkspaceTools(\n backgroundToolsEnabled = false,\n plansDir?: string,\n): WorkspaceToolsConfig {\n const background = backgroundToolsEnabled ? BACKGROUND_TOOL_CONFIG : undefined;\n return {\n ...TOOL_NAME_OVERRIDES,\n // The TUI shows this description in place of the raw command.\n [WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND],\n requireDescription: true,\n },\n [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.READ_FILE],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.FILESYSTEM.GREP]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.GREP],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.LSP.LSP_INSPECT]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.LSP.LSP_INSPECT],\n ...(background ? { background } : {}),\n },\n hooks: {\n beforeToolCall: createPlanModePlanFileWriteGuard(plansDir),\n },\n };\n}\n\n/** Default foreground-only configuration for consumers without Mastra Code settings. */\nexport const MASTRACODE_WORKSPACE_TOOLS = createMastraCodeWorkspaceTools();\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 // Read-only workflow inspection (no create/run/delete in plan mode).\n 'list-workflows',\n 'get-workflow',\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 // Read-only workflow inspection (no create/run/delete in fast mode either).\n 'list-workflows',\n 'get-workflow',\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 M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,GAAG,oBAAoB,gBAAgB,IAAI;GAC3C,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC;EACA,OAAO,EACL,gBAAgB,iCAAiC,QAAQ,EAC3D;CACF;AACF;;AAGA,MAAa,6BAA6B,+BAA+B;AAEzE,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;CAET;CACA;AACF;AAEA,MAAa,+BAAkD;CAC7D,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT;CAEA;CACA;AACF;AAEA,MAAa,4BAA+C;CAC1D,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;AACX"}
|
package/dist/agents/tools.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { prepareProviderWebSearchRoute, resolveProviderWebSearchRoute } from "./model.js";
|
|
2
1
|
import { MC_TOOLS } from "../tool-names.js";
|
|
2
|
+
import "../tools/index.js";
|
|
3
3
|
import { createConfiguredWebTools } from "../tools/web-search.js";
|
|
4
4
|
import { requestSandboxAccessTool } from "../tools/request-sandbox-access.js";
|
|
5
|
-
import "../tools/index.js";
|
|
6
5
|
import { createWorkflowTool } from "../tools/workflows/create-workflow.js";
|
|
7
6
|
import { deleteWorkflowTool } from "../tools/workflows/delete-workflow.js";
|
|
8
7
|
import { getWorkflowTool } from "../tools/workflows/get-workflow.js";
|
|
9
8
|
import { listWorkflowsTool } from "../tools/workflows/list-workflows.js";
|
|
10
9
|
import { runWorkflowTool } from "../tools/workflows/run-workflow.js";
|
|
11
10
|
import { WORKFLOW_MANAGEMENT_TOOL_IDS } from "../tools/workflows/tool-ids.js";
|
|
11
|
+
import { prepareProviderWebSearchRoute, resolveProviderWebSearchRoute } from "./model.js";
|
|
12
12
|
import { createOpenAI } from "@ai-sdk/openai";
|
|
13
13
|
import { jsonSchema } from "ai";
|
|
14
14
|
import { NotificationsStorage, createNotificationInboxTool } from "@mastra/core/notifications";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { getDynamicModel } from "./model.js";
|
|
2
|
-
import { WORKFLOW_AUTHORING_TOOL_IDS } from "../tools/workflows/tool-ids.js";
|
|
3
1
|
import { listAvailableAgentsTool } from "../tools/workflows/list-available-agents.js";
|
|
4
2
|
import { listAvailableClassifiersTool } from "../tools/workflows/list-available-classifiers.js";
|
|
5
3
|
import { listAvailableToolsTool } from "../tools/workflows/list-available-tools.js";
|
|
6
4
|
import { listAvailableWorkflowsTool } from "../tools/workflows/list-available-workflows.js";
|
|
7
5
|
import { saveWorkflowTool } from "../tools/workflows/save-workflow.js";
|
|
6
|
+
import { WORKFLOW_AUTHORING_TOOL_IDS } from "../tools/workflows/tool-ids.js";
|
|
7
|
+
import { getDynamicModel } from "./model.js";
|
|
8
8
|
import { createWorkflowBuilderAgent } from "@mastra/core/workflows/builder";
|
|
9
9
|
// src/agents/workflow-builder-agent.ts
|
|
10
10
|
/**
|
|
@@ -12,11 +12,13 @@ export interface WorkspaceSkillExtension {
|
|
|
12
12
|
/** Compose the additional roots with the workspace's normal skill source. */
|
|
13
13
|
createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;
|
|
14
14
|
}
|
|
15
|
-
export declare function getDynamicWorkspace({ requestContext, mastra, skillExtension, backgroundToolsEnabled, }: {
|
|
15
|
+
export declare function getDynamicWorkspace({ requestContext, mastra, skillExtension, backgroundToolsEnabled, plansDir, }: {
|
|
16
16
|
requestContext: RequestContext;
|
|
17
17
|
mastra?: Mastra;
|
|
18
18
|
skillExtension?: WorkspaceSkillExtension;
|
|
19
19
|
backgroundToolsEnabled?: boolean;
|
|
20
|
+
/** Host-configured plans directory the plan-mode write guard allows. */
|
|
21
|
+
plansDir?: string;
|
|
20
22
|
}): Promise<Workspace<LocalFilesystem, LocalSandbox, undefined>>;
|
|
21
23
|
/**
|
|
22
24
|
* Resolver for the agent's `goal.tools` config. Builds the request's workspace
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../../src/agents/workspace.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AACxG,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAyGrE,wBAAgB,eAAe,CAC7B,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,SAAe,EACtB,gBAAgB,GAAE,MAAM,EAAO,GAC9B,MAAM,EAAE,CA0BV;AAED,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AA2BD,wBAAsB,mBAAmB,CAAC,EACxC,cAAc,EACd,MAAM,EACN,cAAc,EACd,sBAA8B,
|
|
1
|
+
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../../src/agents/workspace.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AACxG,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAyGrE,wBAAgB,eAAe,CAC7B,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,SAAe,EACtB,gBAAgB,GAAE,MAAM,EAAO,GAC9B,MAAM,EAAE,CA0BV;AAED,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AA2BD,wBAAsB,mBAAmB,CAAC,EACxC,cAAc,EACd,MAAM,EACN,cAAc,EACd,sBAA8B,EAC9B,QAAQ,GACT,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,uBAAuB,CAAC;IACzC,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,wEAAwE;IACxE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,gEA2EA;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
|
package/dist/agents/workspace.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "../constants.js";
|
|
2
2
|
import { loadSettings, resolveLspSetting } from "../onboarding/settings.js";
|
|
3
|
-
import { getPlansDir } from "../utils/plans.js";
|
|
4
3
|
import { isPathWithinRoot } from "../utils/path-security.js";
|
|
4
|
+
import { getPlansDir } from "../utils/plans.js";
|
|
5
5
|
import { GOAL_JUDGE_READONLY_TOOLS, createMastraCodeWorkspaceTools } from "./tool-availability.js";
|
|
6
6
|
import path, { dirname, join } from "path";
|
|
7
7
|
import fs, { existsSync } from "fs";
|
|
@@ -123,7 +123,7 @@ function detectPackageRunner(projectPath) {
|
|
|
123
123
|
if (existsSync(join(projectPath, "package-lock.json"))) return "npx --yes";
|
|
124
124
|
return "npx --yes";
|
|
125
125
|
}
|
|
126
|
-
async function getDynamicWorkspace({ requestContext, mastra, skillExtension, backgroundToolsEnabled = false }) {
|
|
126
|
+
async function getDynamicWorkspace({ requestContext, mastra, skillExtension, backgroundToolsEnabled = false, plansDir }) {
|
|
127
127
|
const state = requestContext.get("controller")?.getState();
|
|
128
128
|
const rawProjectPath = state?.projectPath;
|
|
129
129
|
if (!rawProjectPath) throw new Error("Project path is required");
|
|
@@ -138,7 +138,7 @@ async function getDynamicWorkspace({ requestContext, mastra, skillExtension, bac
|
|
|
138
138
|
...DEFAULT_ALLOWED_PATHS,
|
|
139
139
|
...sandboxPaths.map((p) => path.resolve(p))
|
|
140
140
|
];
|
|
141
|
-
const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled);
|
|
141
|
+
const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled, plansDir);
|
|
142
142
|
let existing;
|
|
143
143
|
try {
|
|
144
144
|
existing = mastra?.getWorkspaceById(workspaceId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n timeout: 30_000,\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GACF,MAAM,gBAAgB,GAAG,aAAa,SAAS;GAC/C,IAAI,CAAC,iBAAiB,eAAe,eA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gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
|
|
1
|
+
{"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n plansDir,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n /** Host-configured plans directory the plan-mode write guard allows. */\n plansDir?: string;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled, plansDir);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n timeout: 30_000,\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GACF,MAAM,gBAAgB,GAAG,aAAa,SAAS;GAC/C,IAAI,CAAC,iBAAiB,eAAe,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;GACvB,KAAK,IAAI,QAAQ;GACjB,MAAM,KAAK,SAAS;EACtB;EAEA,IAAI,CAAC,iBAAiB;EAEtB,IAAI;GACF,MAAM,UAAU,GAAG,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC;GACjE,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,eAAe,GACvB,IAAI;IACF,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;IAChD,MAAM,WAAW,GAAG,aAAa,QAAQ;IACzC,IAAI,mBAAmB,CAAC,iBAAiB,UA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
|
2
|
+
import { resolveModel, resolveRequestThinkingLevel } from "../agents/model.js";
|
|
2
3
|
import { getCredentialProviderId, normalizeLegacyModelId } from "../providers/model-ids.js";
|
|
3
4
|
import { isThinkingLevelSetting } from "../thinking.js";
|
|
4
|
-
import { ProviderAuthRequiredError } from "./provider-auth-error.js";
|
|
5
|
-
import { resolveCredentialStore } from "../agents/credential-resolver.js";
|
|
6
5
|
import { getRequestAccountSelection, isRequestAccountRoutingExhausted, markRequestAccountRoutingExhausted, setRequestAccountSelection } from "./account-routing-context.js";
|
|
7
|
-
import {
|
|
6
|
+
import { ProviderAuthRequiredError } from "./provider-auth-error.js";
|
|
7
|
+
import { getOAuthProviders } from "./storage.js";
|
|
8
8
|
import { TripWire } from "@mastra/core/agent";
|
|
9
9
|
import { classifyProviderError } from "@mastra/core/error";
|
|
10
10
|
// src/auth/account-rotation-processor.ts
|
package/dist/auth/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse } from "./provider-auth-error.js";
|
|
2
|
+
import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
|
|
3
|
+
import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, modelFallbackNoticeText, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
|
|
1
4
|
import { anthropicOAuthProvider } from "./providers/anthropic.js";
|
|
2
5
|
import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
|
|
3
6
|
import { kimiCodingOAuthProvider } from "./providers/kimi-coding.js";
|
|
4
7
|
import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
|
|
5
8
|
import { xaiOAuthProvider } from "./providers/xai.js";
|
|
6
|
-
import { AuthStorage, PROVIDER_DEFAULT_MODELS, getOAuthProvider, getOAuthProviders } from "./storage.js";
|
|
7
|
-
import { PROVIDER_AUTH_REQUIRED_ERROR, ProviderAuthRequiredError, rejectUnauthorizedResponse } from "./provider-auth-error.js";
|
|
8
|
-
import { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_DISPLAY_NAMES, accountSwitchNoticeText, classifyRotationError, isAccountSwitchReason, isModelFallbackReason, modelFallbackNoticeText, providerFromError, providerFromModelId } from "./account-rotation-processor.js";
|
|
9
9
|
export { ACCOUNT_SWITCH_PART_TYPE, AccountRotationProcessor, AccountStartNoticeProcessor, AuthStorage, MODEL_FALLBACK_PART_TYPE, MODEL_FALLBACK_STATE_KEY, PROVIDER_AUTH_REQUIRED_ERROR, PROVIDER_DEFAULT_MODELS, PROVIDER_DISPLAY_NAMES, ProviderAuthRequiredError, accountSwitchNoticeText, anthropicOAuthProvider, classifyRotationError, getOAuthProvider, getOAuthProviders, githubCopilotOAuthProvider, isAccountSwitchReason, isModelFallbackReason, kimiCodingOAuthProvider, modelFallbackNoticeText, openaiCodexOAuthProvider, providerFromError, providerFromModelId, rejectUnauthorizedResponse, xaiOAuthProvider };
|
package/dist/evals/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createOutcomeScorer } from "./scorers/outcome.js";
|
|
2
2
|
import { createEfficiencyScorer } from "./scorers/efficiency.js";
|
|
3
|
-
import "./scorers/index.js";
|
|
4
3
|
import { buildEvalContext } from "./context-builder.js";
|
|
4
|
+
import "./scorers/index.js";
|
|
5
5
|
export { buildEvalContext, createEfficiencyScorer, createOutcomeScorer };
|
package/dist/factory/client.d.ts
CHANGED
|
@@ -24,7 +24,10 @@ export interface FactoryUserSession {
|
|
|
24
24
|
updatedAt: string;
|
|
25
25
|
}
|
|
26
26
|
export declare function factoryHeaders({ session }: FactoryAddress): Record<string, string>;
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* List the org's Factory projects with their linked repositories. Current servers return the repositories with the
|
|
29
|
+
* project list; an older server, which does not, is asked once per project.
|
|
30
|
+
*/
|
|
28
31
|
export declare function listFactoryProjects(address: FactoryAddress): Promise<FactoryProject[]>;
|
|
29
32
|
/**
|
|
30
33
|
* Create a Factory user session. Factory assigns the session ID and its
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/factory/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5D,2EAA2E;AAC3E,eAAO,MAAM,qBAAqB,SAAS,CAAC;AAI5C,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,eAAe,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,iBAAiB,EAAE,CAAC;CACnC;AAED,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,cAAc,CAAC,EAAE,OAAO,EAAE,EAAE,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAElF;
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","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AS,GAAE,OAAO,KAAa,GAC9B,OAAO,KAAK,CAsBd;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,YAAY,CAGzE"}
|
package/dist/factory/client.js
CHANGED
|
@@ -25,22 +25,37 @@ async function factoryFetch(address, path, init) {
|
|
|
25
25
|
}
|
|
26
26
|
return await res.json();
|
|
27
27
|
}
|
|
28
|
-
|
|
28
|
+
function toFactoryRepository(projectName, repository) {
|
|
29
|
+
return {
|
|
30
|
+
projectRepositoryId: repository.projectRepositoryId,
|
|
31
|
+
slug: repository.slug ?? projectName,
|
|
32
|
+
branch: repository.branch ?? repository.defaultBranch ?? void 0
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* List the org's Factory projects with their linked repositories. Current servers return the repositories with the
|
|
37
|
+
* project list; an older server, which does not, is asked once per project.
|
|
38
|
+
*/
|
|
29
39
|
async function listFactoryProjects(address) {
|
|
30
40
|
const { projects } = await factoryFetch(address, "/web/factory/projects");
|
|
31
41
|
return Promise.all(projects.map(async (project) => {
|
|
32
|
-
const
|
|
42
|
+
const repositories = project.repositories ?? await listProjectRepositories(address, project.id);
|
|
33
43
|
return {
|
|
34
44
|
id: project.id,
|
|
35
45
|
name: project.name,
|
|
36
|
-
repositories:
|
|
37
|
-
projectRepositoryId: link.id,
|
|
38
|
-
slug: link.repository?.slug ?? project.name,
|
|
39
|
-
branch: link.branch ?? link.repository?.defaultBranch
|
|
40
|
-
})))
|
|
46
|
+
repositories: repositories.map((repository) => toFactoryRepository(project.name, repository))
|
|
41
47
|
};
|
|
42
48
|
}));
|
|
43
49
|
}
|
|
50
|
+
async function listProjectRepositories(address, projectId) {
|
|
51
|
+
const { connections } = await factoryFetch(address, `/web/factory/projects/${encodeURIComponent(projectId)}/source-control-connections`);
|
|
52
|
+
return connections.flatMap((connection) => connection.repositories.map((link) => ({
|
|
53
|
+
projectRepositoryId: link.id,
|
|
54
|
+
slug: link.repository?.slug ?? null,
|
|
55
|
+
defaultBranch: link.repository?.defaultBranch ?? null,
|
|
56
|
+
branch: link.branch
|
|
57
|
+
})));
|
|
58
|
+
}
|
|
44
59
|
/**
|
|
45
60
|
* Create a Factory user session. Factory assigns the session ID and its
|
|
46
61
|
* `user/session-<id>` branch, cut from the repository's default branch.
|