@mastra/code-sdk 1.8.4-alpha.0 → 1.8.4-alpha.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,UAAU,mBAAmB;IAC3B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uFAAuF;IACvF,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,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,CA+Q3F"}
1
+ {"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,UAAU,mBAAmB;IAC3B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uFAAuF;IACvF,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,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,CAgR3F"}
@@ -41,6 +41,7 @@ You have access to the following tools. Use the RIGHT tool for the job:`);
41
41
  - 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}).
42
42
  - Commands have a 30-second default timeout. Use \`timeout\` for longer commands, \`cwd\` for working directory.
43
43
  - 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.
44
+ - 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").
44
45
  - Good: Run independent commands in parallel when possible.
45
46
  - Bad: Running \`cat file.txt\` — use the ${MC_TOOLS.VIEW} tool instead.`);
46
47
  if (!denied.has(MC_TOOLS.LSP_INSPECT)) readTools.push(`
@@ -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 hasSubagents?: boolean;\n /** Subconscious knowledge tools are registered (experimental subconscious enabled). */\n hasSubconscious?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const plansDir = options.plansDir ?? '.mastracode/plans';\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read files before editing them. NEVER propose changes to code you haven't read.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- You MUST read a file with \\`${MC_TOOLS.VIEW}\\` before editing it.\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- If overwriting an existing file, you MUST have read it first with \\`${MC_TOOLS.VIEW}\\`.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (!denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n sections.push(`\n${webTools.join(' / ')} — Search the web / extract page content\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Subconscious knowledge tools (all modes, conditionally available) ---\n\n if (options.hasSubconscious) {\n const knowledgeTools = ['knowledge_search', 'knowledge_read', 'knowledge_browse'].filter(name => !denied.has(name));\n const hasAskMemory = !denied.has('ask_memory');\n if (knowledgeTools.length > 0 || hasAskMemory) {\n const lines = [\n `\n# Subconscious Memory\n\nA background memory system (the \"subconscious\") runs alongside you. After conversations, it extracts durable knowledge — decisions, preferences, people, files, repos, work items — into a knowledge graph scoped to this project, visible across your sessions here. It also delivers reminders (\\`<remembered>\\`) and pinned knowledge into your context on its own; you do not manage those directly.`,\n ];\n if (knowledgeTools.length > 0) {\n const bullets: string[] = [];\n if (knowledgeTools.includes('knowledge_search')) {\n bullets.push(\n \"- Use `knowledge_search` for a quick lexical + semantic lookup when you need a specific fact (a past decision, a person's role, what a file is for). Cheaper than re-deriving it from the codebase or asking the user.\",\n );\n }\n if (knowledgeTools.includes('knowledge_read')) {\n bullets.push('- Use `knowledge_read` to open a node by name or ID and see the records about it.');\n }\n if (knowledgeTools.includes('knowledge_browse')) {\n bullets.push(\n \"- Use `knowledge_browse` to list nodes by kind or name prefix, or to walk a node's mentions and backlinks.\",\n );\n }\n if (!denied.has('recall')) {\n bullets.push(\n '- Prefer these over `recall` when the question is about durable facts rather than what was said in a specific past conversation.',\n );\n }\n lines.push(`\n${knowledgeTools.map(name => `**${name}**`).join(' / ')} — Query the knowledge graph directly\n${bullets.join('\\n')}`);\n }\n if (hasAskMemory) {\n lines.push(`\n**ask_memory** — Ask the reminder sidekick a question about existing memory\n- Use only when the answer is not already in your context and a direct search is not enough: open-ended questions (\"what did we decide about X and why?\") or questions that need synthesis across several memories. It answers from what is already remembered; it does not store anything.\n- It is ASYNCHRONOUS. The tool returns as soon as the question is accepted; the answer arrives later as one or more \\`<remind-answer source=\"subconscious\" agent=\"remind\" replyId=\"…\" moreComing=\"true|false\">\\` messages in your context. Keep working — do not poll or wait, and do not re-ask the same question.\n- Treat a message with \\`moreComing=\"true\"\\` as partial; the reply is complete only when \\`moreComing=\"false\"\\` arrives. Fold the answer into your work and cite it as remembered context rather than as something you verified yourself.`);\n }\n sections.push(lines.join('\\n'));\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,c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ACnB,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\ninterface ToolGuidanceOptions {\n hasWebSearch?: boolean;\n hasSubagents?: boolean;\n /** Subconscious knowledge tools are registered (experimental subconscious enabled). */\n hasSubconscious?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const plansDir = options.plansDir ?? '.mastracode/plans';\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read files before editing them. NEVER propose changes to code you haven't read.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- 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- You MUST read a file with \\`${MC_TOOLS.VIEW}\\` before editing it.\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- If overwriting an existing file, you MUST have read it first with \\`${MC_TOOLS.VIEW}\\`.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (!denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n sections.push(`\n${webTools.join(' / ')} — Search the web / extract page content\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Subconscious knowledge tools (all modes, conditionally available) ---\n\n if (options.hasSubconscious) {\n const knowledgeTools = ['knowledge_search', 'knowledge_read', 'knowledge_browse'].filter(name => !denied.has(name));\n const hasAskMemory = !denied.has('ask_memory');\n if (knowledgeTools.length > 0 || hasAskMemory) {\n const lines = [\n `\n# Subconscious Memory\n\nA background memory system (the \"subconscious\") runs alongside you. After conversations, it extracts durable knowledge — decisions, preferences, people, files, repos, work items — into a knowledge graph scoped to this project, visible across your sessions here. It also delivers reminders (\\`<remembered>\\`) and pinned knowledge into your context on its own; you do not manage those directly.`,\n ];\n if (knowledgeTools.length > 0) {\n const bullets: string[] = [];\n if (knowledgeTools.includes('knowledge_search')) {\n bullets.push(\n \"- Use `knowledge_search` for a quick lexical + semantic lookup when you need a specific fact (a past decision, a person's role, what a file is for). Cheaper than re-deriving it from the codebase or asking the user.\",\n );\n }\n if (knowledgeTools.includes('knowledge_read')) {\n bullets.push('- Use `knowledge_read` to open a node by name or ID and see the records about it.');\n }\n if (knowledgeTools.includes('knowledge_browse')) {\n bullets.push(\n \"- Use `knowledge_browse` to list nodes by kind or name prefix, or to walk a node's mentions and backlinks.\",\n );\n }\n if (!denied.has('recall')) {\n bullets.push(\n '- Prefer these over `recall` when the question is about durable facts rather than what was said in a specific past conversation.',\n );\n }\n lines.push(`\n${knowledgeTools.map(name => `**${name}**`).join(' / ')} — Query the knowledge graph directly\n${bullets.join('\\n')}`);\n }\n if (hasAskMemory) {\n lines.push(`\n**ask_memory** — Ask the reminder sidekick a question about existing memory\n- Use only when the answer is not already in your context and a direct search is not enough: open-ended questions (\"what did we decide about X and why?\") or questions that need synthesis across several memories. It answers from what is already remembered; it does not store anything.\n- It is ASYNCHRONOUS. The tool returns as soon as the question is accepted; the answer arrives later as one or more \\`<remind-answer source=\"subconscious\" agent=\"remind\" replyId=\"…\" moreComing=\"true|false\">\\` messages in your context. Keep working — do not poll or wait, and do not re-ask the same question.\n- Treat a message with \\`moreComing=\"true\"\\` as partial; the reply is complete only when \\`moreComing=\"false\"\\` arrives. Fold the answer into your work and cite it as remembered context rather than as something you verified yourself.`);\n }\n sections.push(lines.join('\\n'));\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,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,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAMtD,CAAC"}
1
+ {"version":3,"file":"tool-availability.d.ts","sourceRoot":"","sources":["../../src/agents/tool-availability.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AA4D7F,wBAAgB,2BAA2B,CAAC,EAAE,iBAAiB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,wBAAwB;;;cA0B1G;AAID,wBAAgB,8BAA8B,CAAC,sBAAsB,UAAQ,GAAG,oBAAoB,CAiCnG;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"}
@@ -59,6 +59,10 @@ function createMastraCodeWorkspaceTools(backgroundToolsEnabled = false) {
59
59
  const background = backgroundToolsEnabled ? BACKGROUND_TOOL_CONFIG : void 0;
60
60
  return {
61
61
  ...TOOL_NAME_OVERRIDES,
62
+ [WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]: {
63
+ ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND],
64
+ requireDescription: true
65
+ },
62
66
  [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: {
63
67
  ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.READ_FILE],
64
68
  ...background ? { background } : {}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-availability.js","names":[],"sources":["../../src/agents/tool-availability.ts"],"sourcesContent":["import { WORKSPACE_TOOLS } from '@mastra/core/workspace';\nimport type { WorkspaceToolHookContext, WorkspaceToolsConfig } from '@mastra/core/workspace';\nimport { MC_TOOLS, TOOL_NAME_OVERRIDES } from '../tool-names.js';\nimport { getLocalPlansRelativeDir, isPlanFilePath } from '../utils/plans.js';\n\nconst PLAN_MODE_WRITE_TOOL_NAMES = new Set<string>([\n WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,\n WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,\n]);\n\nfunction getRequestContextValue(requestContext: unknown, key: string): unknown {\n if (!requestContext) return undefined;\n if (typeof (requestContext as { get?: unknown }).get === 'function') {\n return (requestContext as { get: (key: string) => unknown }).get(key);\n }\n return (requestContext as Record<string, unknown>)[key];\n}\n\n/**\n * Subset of the real `HarnessRequestContext` shape (see\n * packages/core/src/harness/types.ts). The mode is a string property\n * (`session.modeId`) and live state is read via `session.state.get()`.\n */\ninterface PlanModeGuardHarness {\n session?: {\n modeId?: unknown;\n state?: { get?: () => unknown };\n };\n}\n\nfunction getHarnessContext(context: unknown): PlanModeGuardHarness | undefined {\n const requestContext = (context as { requestContext?: unknown } | undefined)?.requestContext;\n const harness = getRequestContextValue(requestContext, 'harness');\n return harness && typeof harness === 'object' ? (harness as PlanModeGuardHarness) : undefined;\n}\n\nfunction getHarnessState(harness: PlanModeGuardHarness | undefined): Record<string, unknown> | undefined {\n const state = harness?.session?.state?.get?.();\n return state && typeof state === 'object' ? (state as Record<string, unknown>) : undefined;\n}\n\nfunction getHarnessModeId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const modeId = harness?.session?.modeId ?? getHarnessState(harness)?.modeId;\n return typeof modeId === 'string' ? modeId : undefined;\n}\n\nfunction getHarnessProjectPath(harness: PlanModeGuardHarness | undefined): string | undefined {\n const projectPath = getHarnessState(harness)?.projectPath;\n return typeof projectPath === 'string' ? projectPath : undefined;\n}\n\nfunction getHarnessFactoryProjectId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const factoryProjectId = getHarnessState(harness)?.factoryProjectId;\n return typeof factoryProjectId === 'string' ? factoryProjectId : undefined;\n}\n\nfunction getToolInputPath(input: unknown): string | undefined {\n const toolPath = (input as { path?: unknown } | undefined)?.path;\n return typeof toolPath === 'string' ? toolPath : undefined;\n}\n\nexport function guardPlanModePlanFileWrites({ workspaceToolName, input, context }: WorkspaceToolHookContext) {\n if (!PLAN_MODE_WRITE_TOOL_NAMES.has(workspaceToolName)) return;\n\n const harness = getHarnessContext(context);\n if (getHarnessModeId(harness) !== 'plan') return;\n\n const factoryProjectId = getHarnessFactoryProjectId(harness);\n const planOptions = { factoryProjectId };\n const planDirHint = `${getLocalPlansRelativeDir(planOptions)}/`;\n const projectPath = getHarnessProjectPath(harness);\n const inputPath = getToolInputPath(input);\n if (!projectPath || !inputPath) {\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}.`,\n };\n }\n\n // Plan mode may write any `.md` file directly inside the configured plan directory,\n // but nothing else in the project.\n if (isPlanFilePath(projectPath, inputPath, planOptions)) return;\n\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}. Refusing to edit ${inputPath}.`,\n };\n}\n\nconst BACKGROUND_TOOL_CONFIG = { enabled: true, defaultDisposition: 'foreground' } as const;\n\nexport function createMastraCodeWorkspaceTools(backgroundToolsEnabled = false): WorkspaceToolsConfig {\n const background = backgroundToolsEnabled ? BACKGROUND_TOOL_CONFIG : undefined;\n return {\n ...TOOL_NAME_OVERRIDES,\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: guardPlanModePlanFileWrites,\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 MC_TOOLS.FILE_STAT,\n MC_TOOLS.LS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AS;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"}
1
+ {"version":3,"file":"tool-availability.js","names":[],"sources":["../../src/agents/tool-availability.ts"],"sourcesContent":["import { WORKSPACE_TOOLS } from '@mastra/core/workspace';\nimport type { WorkspaceToolHookContext, WorkspaceToolsConfig } from '@mastra/core/workspace';\nimport { MC_TOOLS, TOOL_NAME_OVERRIDES } from '../tool-names.js';\nimport { getLocalPlansRelativeDir, isPlanFilePath } from '../utils/plans.js';\n\nconst PLAN_MODE_WRITE_TOOL_NAMES = new Set<string>([\n WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,\n WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,\n]);\n\nfunction getRequestContextValue(requestContext: unknown, key: string): unknown {\n if (!requestContext) return undefined;\n if (typeof (requestContext as { get?: unknown }).get === 'function') {\n return (requestContext as { get: (key: string) => unknown }).get(key);\n }\n return (requestContext as Record<string, unknown>)[key];\n}\n\n/**\n * Subset of the real `HarnessRequestContext` shape (see\n * packages/core/src/harness/types.ts). The mode is a string property\n * (`session.modeId`) and live state is read via `session.state.get()`.\n */\ninterface PlanModeGuardHarness {\n session?: {\n modeId?: unknown;\n state?: { get?: () => unknown };\n };\n}\n\nfunction getHarnessContext(context: unknown): PlanModeGuardHarness | undefined {\n const requestContext = (context as { requestContext?: unknown } | undefined)?.requestContext;\n const harness = getRequestContextValue(requestContext, 'harness');\n return harness && typeof harness === 'object' ? (harness as PlanModeGuardHarness) : undefined;\n}\n\nfunction getHarnessState(harness: PlanModeGuardHarness | undefined): Record<string, unknown> | undefined {\n const state = harness?.session?.state?.get?.();\n return state && typeof state === 'object' ? (state as Record<string, unknown>) : undefined;\n}\n\nfunction getHarnessModeId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const modeId = harness?.session?.modeId ?? getHarnessState(harness)?.modeId;\n return typeof modeId === 'string' ? modeId : undefined;\n}\n\nfunction getHarnessProjectPath(harness: PlanModeGuardHarness | undefined): string | undefined {\n const projectPath = getHarnessState(harness)?.projectPath;\n return typeof projectPath === 'string' ? projectPath : undefined;\n}\n\nfunction getHarnessFactoryProjectId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const factoryProjectId = getHarnessState(harness)?.factoryProjectId;\n return typeof factoryProjectId === 'string' ? factoryProjectId : undefined;\n}\n\nfunction getToolInputPath(input: unknown): string | undefined {\n const toolPath = (input as { path?: unknown } | undefined)?.path;\n return typeof toolPath === 'string' ? toolPath : undefined;\n}\n\nexport function guardPlanModePlanFileWrites({ workspaceToolName, input, context }: WorkspaceToolHookContext) {\n if (!PLAN_MODE_WRITE_TOOL_NAMES.has(workspaceToolName)) return;\n\n const harness = getHarnessContext(context);\n if (getHarnessModeId(harness) !== 'plan') return;\n\n const factoryProjectId = getHarnessFactoryProjectId(harness);\n const planOptions = { factoryProjectId };\n const planDirHint = `${getLocalPlansRelativeDir(planOptions)}/`;\n const projectPath = getHarnessProjectPath(harness);\n const inputPath = getToolInputPath(input);\n if (!projectPath || !inputPath) {\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}.`,\n };\n }\n\n // Plan mode may write any `.md` file directly inside the configured plan directory,\n // but nothing else in the project.\n if (isPlanFilePath(projectPath, inputPath, planOptions)) return;\n\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}. Refusing to edit ${inputPath}.`,\n };\n}\n\nconst BACKGROUND_TOOL_CONFIG = { enabled: true, defaultDisposition: 'foreground' } as const;\n\nexport function createMastraCodeWorkspaceTools(backgroundToolsEnabled = false): WorkspaceToolsConfig {\n const background = backgroundToolsEnabled ? BACKGROUND_TOOL_CONFIG : undefined;\n return {\n ...TOOL_NAME_OVERRIDES,\n // Quiet mode 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: guardPlanModePlanFileWrites,\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 MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n];\n"],"mappings":";;;;AAKA,MAAM,6CAA6B,IAAI,IAAY,CACjD,gBAAgB,WAAW,YAC3B,gBAAgB,WAAW,SAC7B,CAAC;AAED,SAAS,uBAAuB,gBAAyB,KAAsB;CAC7E,IAAI,CAAC,gBAAgB,OAAO,KAAA;CAC5B,IAAI,OAAQ,eAAqC,QAAQ,YACvD,OAAQ,eAAqD,IAAI,GAAG;CAEtE,OAAQ,eAA2C;AACrD;AAcA,SAAS,kBAAkB,SAAoD;CAC7E,MAAM,iBAAkB,SAAsD;CAC9E,MAAM,UAAU,uBAAuB,gBAAgB,SAAS;CAChE,OAAO,WAAW,OAAO,YAAY,WAAY,UAAmC,KAAA;AACtF;AAEA,SAAS,gBAAgB,SAAgF;CACvG,MAAM,QAAQ,SAAS,SAAS,OAAO,MAAM;CAC7C,OAAO,SAAS,OAAO,UAAU,WAAY,QAAoC,KAAA;AACnF;AAEA,SAAS,iBAAiB,SAA+D;CACvF,MAAM,SAAS,SAAS,SAAS,UAAU,gBAAgB,OAAO,CAAC,EAAE;CACrE,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AAW;GAClD,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC;GACC,gBAAgB,WAAW,aAAa;GACvC,GAAG,oBAAoB,gBAAgB,WAAW;GAClD,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC;GACC,gBAAgB,WAAW,YAAY;GACtC,GAAG,oBAAoB,gBAAgB,WAAW;GAClD,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC;GACC,gBAAgB,WAAW,OAAO;GACjC,GAAG,oBAAoB,gBAAgB,WAAW;GAClD,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC;GACC,gBAAgB,IAAI,cAAc;GACjC,GAAG,oBAAoB,gBAAgB,IAAI;GAC3C,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC;EACA,OAAO,EACL,gBAAgB,4BAClB;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"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EAErB,mBAAmB,EACnB,uBAAuB,EAEvB,OAAO,EACR,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAAE,MAAM,EAAE,MA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AC;CACzF,GACA,OAAO,CAAC;IACT,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,+BAA+B,CAAC,CAAC,CAAC;IAClE,UAAU,EAAE,WAAW,CAAC,qBAAqB,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B,CAAC,CA4DD;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iCAA2B,CAAC;AACzD,cAAc,0BAA0B,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D;;;;GAIG;AACH,OAAO,EACL,KAAK,EACL,QAAQ,EACR,eAAe,EACf,iBAAiB,EACjB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -486,6 +486,7 @@ async function createMastraCodeAgentController(config) {
486
486
  const state = getInjectorSessionState(requestContext);
487
487
  return state?.untrustedCheckout !== true || typeof state?.baseRef === "string";
488
488
  },
489
+ getBasePath: ({ requestContext }) => getInjectorSessionState(requestContext)?.projectPath ?? project.rootPath,
489
490
  getReader: ({ requestContext }) => {
490
491
  const state = getInjectorSessionState(requestContext);
491
492
  if (state?.untrustedCheckout !== true || typeof state?.baseRef !== "string") return void 0;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["createScopedKnowledgeInspector"],"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport path from 'node:path';\n\nimport type { Agent } from '@mastra/core/agent';\nimport { AgentController } from '@mastra/core/agent-controller';\nimport type {\n IntervalHandler,\n AgentControllerConfig,\n AgentControllerEvent,\n AgentControllerMode,\n AgentControllerSubagent,\n AgentControllerRequestContext,\n Session,\n} from '@mastra/core/agent-controller';\nimport { createCodingAgent } from '@mastra/core/coding-agent';\nimport type { PubSub } from '@mastra/core/events';\nimport { PROVIDER_REGISTRY } from '@mastra/core/llm';\nimport type { ProviderConfig } from '@mastra/core/llm';\nimport { Mastra } from '@mastra/core/mastra';\nimport { defaultNotificationDeliveryDecision } from '@mastra/core/notifications';\nimport {\n AgentsMDInjector,\n createBackgroundWorkSignalProcessor,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport type { InputProcessor, Processor } from '@mastra/core/processors';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { PublicSchema } from '@mastra/core/schema';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { TaskSignalProvider } from '@mastra/core/signals';\nimport { InMemoryHarness, MastraCompositeStore } from '@mastra/core/storage';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '@mastra/core/tools';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\nimport { PostgresStore } from '@mastra/pg';\n\nimport { createSessionThreadAdvertisement } from './agent-connections/session-advertisement.js';\nimport { AgentConnectionsSignalProvider } from './agent-connections/signal-provider.js';\nimport type { AgentConnectionsSignalProviderOptions } from './agent-connections/signal-provider.js';\nimport { createBackgroundCompletionEvents } from './agents/background-completion-events.js';\nimport { createBackgroundCompletionCallbacks } from './agents/background-completion.js';\nimport { hasCredentialStoreProvider } from './agents/credential-resolver.js';\nimport { getDynamicInstructions } from './agents/instructions.js';\nimport { getDynamicMemory, hasSubconsciousTools } from './agents/memory.js';\nimport { createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from './agents/model.js';\nimport { buildMode } from './agents/modes/build.js';\nimport { fastMode } from './agents/modes/explore.js';\nimport { planMode } from './agents/modes/plan.js';\nimport {\n createGitRefInstructionReader,\n createGitRefReminderReader,\n getStaticallyLoadedInstructionPaths,\n} from './agents/prompts/agent-instructions.js';\nimport { executeSubagent } from './agents/subagents/execute.js';\nimport { exploreSubagent } from './agents/subagents/explore.js';\nimport { planSubagent } from './agents/subagents/plan.js';\nimport { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from './agents/thread-caveman-state.js';\nimport { createDynamicTools, createToolHooks } from './agents/tools.js';\nimport type { PostToolObserver, ToolLike } from './agents/tools.js';\n\nimport { getDynamicWorkspace, getGoalJudgeTools } from './agents/workspace.js';\nimport {\n AccountRotationProcessor,\n AccountStartNoticeProcessor,\n PACK_FALLBACK_STATE_KEY,\n} from './auth/account-rotation-processor.js';\nimport { isKimiCodingDeviceId } from './auth/providers/kimi-coding.js';\nimport { AuthStorage } from './auth/storage.js';\nimport { DEFAULT_CONFIG_DIR, validateConfigDirName } from './constants.js';\nimport { createOutcomeScorer, createEfficiencyScorer } from './evals/scorers/index.js';\nimport { HookManager } from './hooks/index.js';\nimport { createKnowledgeInspector as createScopedKnowledgeInspector } from './knowledge-inspector.js';\nimport { createMcpManager } from './mcp/index.js';\nimport type { McpServerConfig } from './mcp/index.js';\nimport { hasExplicitOMConfiguration } from './onboarding/om-settings.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks, selectPreferredOMPack } from './onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_GATEWAY_PROVIDER,\n OBSERVABILITY_AUTH_PREFIX,\n resolveModelDefaults,\n resolveOmRoleModel,\n saveSettings,\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n} from './onboarding/settings.js';\nimport { getToolCategory } from './permissions.js';\nimport { PluginManager } from './plugins/manager.js';\nimport { PluginSignalLane } from './plugins/signal-lane.js';\nimport type { PluginProcessorEntries } from './plugins/types.js';\nimport { PlanRejectionAbortProcessor } from './processors/plan-rejection-abort.js';\nimport { createAmazonBedrockGateway } from './providers/amazon-bedrock-gateway.js';\nimport { setAuthStorage } from './providers/claude-max.js';\nimport { setAuthStorage as setGitHubCopilotAuthStorage } from './providers/github-copilot.js';\nimport { setAuthStorage as setKimiCodingAuthStorage } from './providers/kimi-coding.js';\nimport { setAuthStorage as setOpenAIAuthStorage } from './providers/openai-codex.js';\nimport { setAuthStorage as setXAIAuthStorage } from './providers/xai.js';\n\nimport { stateSchema } from './schema.js';\nimport type { MastraCodeState } from './schema.js';\n\nimport { mastraBrand } from './theme-palette.js';\nimport { syncGateways } from './utils/gateway-sync.js';\nimport {\n detectProject,\n getObservabilityDatabasePath,\n getStorageConfig,\n getResourceIdOverride,\n} from './utils/project.js';\nimport type { StorageConfig } from './utils/project.js';\nimport { createSignalsPubSub } from './utils/signals-pubsub.js';\nimport { createStorage, createVectorStore } from './utils/storage-factory.js';\nimport type { StorageResult } from './utils/storage-factory.js';\nimport { createStorageMaintenance, DEFAULT_RETENTION, resolveLocalDbFiles } from './utils/storage-maintenance.js';\nimport type { StorageMaintenance } from './utils/storage-maintenance.js';\nimport { acquireThreadLock, releaseThreadLock } from './utils/thread-lock.js';\nimport { registerWorkflowBuilderPrimitives } from './workflows/register-primitives.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient provider failures (e.g. dropped sockets and server errors).\n// Applied centrally to every model call via StreamErrorRetryProcessor, independent of model-pack\n// settings, so all modes/subagents benefit from a short wait before retrying a transient failure.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 10;\n// Shared ceiling for the whole processor error lane: core counts every\n// processor-requested retry against this one number. Sized for the largest\n// legitimate cascade — a rotation step per remaining account per pack hop\n// (8 representative accounts x 8 packs) — rather than an open-ended budget, so\n// a custom or plugin processor that returns `retry: true` loops at most this\n// many times instead of amplifying one request without bound.\nconst MASTRACODE_MAX_PROCESSOR_RETRIES = 64;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 500;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 30000;\n\nconst TRANSIENT_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE']);\nconst TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;\n// Any 5xx is treated as transient so server errors exhaust the transient retry\n// budget before the account-rotation processor classifies them as a persistent\n// outage (hop). Must stay aligned with `classifyRotationError`'s 5xx check.\nconst isTransientServerStatus = (status: number) => status >= 500 && status < 600;\nconst TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN = /internal server|server error|api may be experiencing issues/i;\n\n/**\n * Matcher for transient connection failures. Cause-chain traversal is handled\n * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each\n * matcher at every level of the cause chain.\n */\n/**\n * Read the session state fields the AgentsMDInjector callbacks need from the\n * controller request context (set by hosts like the factory review flow).\n */\nfunction getInjectorSessionState(\n requestContext: { get: (key: string) => unknown } | undefined,\n): { untrustedCheckout?: boolean; baseRef?: string; projectPath?: string } | undefined {\n const agentControllerContext = requestContext?.get('controller') as\n | AgentControllerRequestContext<{ untrustedCheckout?: boolean; baseRef?: string; projectPath?: string }>\n | undefined;\n return agentControllerContext?.getState();\n}\n\nfunction isTransientConnectionError(error: unknown): boolean {\n if (!error) return false;\n\n const code = typeof error === 'object' && 'code' in error ? (error as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\nfunction isTransientServerError(error: unknown): boolean {\n if (!error) return false;\n\n const errorObj = typeof error === 'object' ? (error as { status?: unknown; statusCode?: unknown }) : undefined;\n if (\n (typeof errorObj?.status === 'number' && isTransientServerStatus(errorObj.status)) ||\n (typeof errorObj?.statusCode === 'number' && isTransientServerStatus(errorObj.statusCode))\n ) {\n return true;\n }\n\n const message = error instanceof Error ? error.message : undefined;\n return typeof message === 'string' && TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN.test(message);\n}\n\nfunction getTransientRetryDelay(retryCount: number): number {\n return Math.min(\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS,\n );\n}\n\nfunction emitTransientRetry(\n error: unknown,\n retryCount: number,\n delayMs: number,\n requestContext?: RequestContext,\n): void {\n const controllerContext = requestContext?.get('controller') as AgentControllerRequestContext | undefined;\n controllerContext?.emitEvent?.({\n type: 'error',\n error: error instanceof Error ? error : new Error(String(error)),\n retryable: true,\n retryDelay: delayMs,\n retryAttempt: retryCount + 1,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n });\n}\n\n/** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */\nfunction shortHash(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 12);\n}\n\nfunction applyEffectiveDefaultsToModes(\n modes: AgentControllerMode[],\n effectiveDefaults: Record<string, string>,\n): AgentControllerMode[] {\n return modes.map(mode => {\n const savedModel = effectiveDefaults[mode.id];\n if (!savedModel) {\n return mode;\n }\n return {\n ...mode,\n defaultModelId: savedModel,\n };\n });\n}\n\nfunction addPluginToolsToModeAllowlists(\n modes: AgentControllerMode[],\n pluginToolNames: string[],\n): AgentControllerMode[] {\n if (pluginToolNames.length === 0) return modes;\n return modes.map(mode => {\n if (!mode.availableTools) return mode;\n return {\n ...mode,\n availableTools: Array.from(new Set([...mode.availableTools, ...pluginToolNames])),\n };\n });\n}\n\nexport interface MastraCodeConfig {\n /** Working directory for project detection. Default: process.cwd() */\n cwd?: string;\n /** Home directory for global config discovery. Default: os.homedir() */\n homeDir?: string;\n /** Override modes (model IDs, colors, which modes exist). Default: build/plan/fast */\n modes?: AgentControllerMode[];\n /** Replace subagent definitions. Default: explore/plan/execute. An empty array disables subagents. */\n subagents?: AgentControllerSubagent[];\n /** Extra tools merged into the dynamic tool set. Can be a static record or a (sync or async) function that receives requestContext. */\n extraTools?:\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */\n postToolObserver?: PostToolObserver;\n /**\n * Stateless input processor instances prepended before Mastra Code's mandatory processors.\n * Embedders may extend processing but cannot replace built-in safety and compatibility policy.\n */\n inputProcessors?: InputProcessor[];\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /**\n * Custom storage config instead of auto-detected default, or a pre-built\n * store instance. An instance is used as-is: no connection test and no\n * LibSQL fallback — if the injected store fails, that's a hard error.\n */\n storage?: StorageConfig | MastraCompositeStore;\n /** Backend for an injected custom storage instance. Inferred for LibSQLStore and PostgresStore. */\n storageBackend?: 'libsql' | 'pg';\n /** Pre-built vector store instance for recall search. Skips the default vector store creation. */\n vector?: MastraVector;\n /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */\n omScope?: 'thread' | 'resource';\n /** Path to a custom settings.json file. Default: global settings */\n settingsPath?: string;\n /** Initial state overrides (yolo, thinkingLevel, etc.) */\n initialState?: Partial<MastraCodeState>;\n /** Trusted host instructions resolved outside mutable session state. */\n hostInstructions?:\n | string\n | ((ctx: { requestContext: RequestContext }) => string | undefined | Promise<string | undefined>);\n /** Commit co-author identity included in coding-agent commit guidance. Unspecified fields use core defaults. */\n coAuthor?: { name?: string; email?: string };\n /** Override id generation for threads/messages. Primarily useful for deterministic tests. */\n idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];\n /** Override interval handlers. Default: gateway-sync */\n intervalHandlers?: IntervalHandler[];\n /** Override the workspace. Default: local filesystem + local sandbox based on detected project */\n workspace?: AgentControllerConfig<MastraCodeState>['workspace'];\n /** Override the config directory name. Default: '.mastracode'. Replaces '.mastracode' in all project-level and global config paths (MCP, hooks, commands, database, skills, agent instructions). */\n configDir?: string;\n /** Programmatic MCP server configurations, merged with (and overriding) file-based configs. */\n mcpServers?: Record<string, McpServerConfig>;\n /** Disable MCP server discovery. Default: false */\n disableMcp?: boolean;\n /** Disable hooks. Default: false */\n disableHooks?: boolean;\n /** Disable plugin discovery/loading. Default: false */\n disablePlugins?: boolean;\n /** Disable the polling-based GitHub signal provider even when enabled in global settings. Default: false */\n disableGithubSignals?: boolean;\n /**\n * Skip seeding observational-memory knobs (observer/reflector models,\n * thresholds, caveman mode, attachment observation) from settings.json.\n * Server deployments that persist memory settings in their own database\n * (the factory's `memory-settings` domain) set this so the host machine's\n * TUI settings file never leaks into server sessions. Default: false.\n */\n disableSettingsOmSeed?: boolean;\n /** Override the plugin manager. Primarily useful for tests or embedding. */\n pluginManager?: PluginManager;\n /**\n * Override the memory instance (or dynamic factory) passed to the AgentController.\n * When provided, this replaces the default `getDynamicMemory(storage, vector)` which\n * uses mastracode's built-in model gateway (Anthropic OAuth, OpenAI Codex,\n * custom providers, and models.dev fallback).\n *\n * Use this when you need to override memory model behavior completely.\n */\n memory?: AgentControllerConfig<MastraCodeState>['memory'] | false;\n /** Browser provider for browser automation tools. When set, the agent gains access to browser tools. */\n browser?: AgentControllerConfig<MastraCodeState>['browser'];\n /** PubSub for signal routing. When crossProcessPubSub is true, thread locks are disabled. */\n pubsub?: PubSub;\n /** Use Mastra Code's built-in Unix socket PubSub for local cross-process signal routing. */\n unixSocketPubSub?: boolean;\n /** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */\n crossProcessPubSub?: boolean;\n /** Agent connection state and discovery options. */\n agentConnections?: AgentConnectionsSignalProviderOptions;\n /**\n * Enable experimental cross-agent communication: thread ownership\n * advertisement, peer discovery, and the agent connection tools. Defaults to\n * the `signals.experimentalCrossAgentSignals` global setting (off). This does\n * not gate the PubSub transport itself — cross-agent communication simply\n * uses the configured PubSub when enabled.\n */\n crossAgentSignals?: boolean;\n /**\n * Prepare the request context of a wake: a run on a thread with no inbound\n * request, such as a notification or cross-agent signal delivered to an idle\n * thread. Hosts that resolve credentials per tenant use this to attach the\n * identity that owns `resourceId` before the run starts. Called only when a\n * session owns `resourceId`, whenever Mastra Code builds a wake's stream\n * options.\n */\n prepareWakeRequestContext?: (args: {\n requestContext: RequestContext;\n resourceId: string;\n threadId: string;\n }) => void | Promise<void>;\n}\n\nexport function createAuthStorage() {\n const authStorage = new AuthStorage();\n setAuthStorage(authStorage);\n setOpenAIAuthStorage(authStorage);\n setGitHubCopilotAuthStorage(authStorage);\n setKimiCodingAuthStorage(authStorage);\n setXAIAuthStorage(authStorage);\n return authStorage;\n}\n\n/**\n * Resolve cloud observability credentials for the MastraPlatformExporter.\n * Priority: per-resource settings > MASTRACODE_* environment variables > undefined (no exporter).\n *\n * The env vars are deliberately namespaced `MASTRACODE_*`, not `MASTRA_*`: the\n * cwd `.env` is loaded into `process.env`, so reading `MASTRA_PROJECT_ID` /\n * `MASTRA_CLOUD_ACCESS_TOKEN` would export Mastra Code's own traces into\n * whatever Mastra project the user happens to be working in (and crash on\n * project ids the exporter rejects).\n */\nexport function resolveCloudObservabilityConfig(\n settings: ReturnType<typeof loadSettings>,\n authStorage: AuthStorage,\n resourceId: string,\n env: NodeJS.ProcessEnv = process.env,\n): { accessToken: string; projectId?: string } | undefined {\n const resourceConfig = settings.observability.resources[resourceId];\n if (resourceConfig) {\n const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);\n if (token) {\n return { accessToken: token, projectId: resourceConfig.projectId };\n }\n }\n const accessToken = env.MASTRACODE_CLOUD_ACCESS_TOKEN?.trim();\n if (!accessToken) return undefined;\n return { accessToken, projectId: env.MASTRACODE_PROJECT_ID?.trim() || undefined };\n}\n\n/**\n * Base factory: builds every shared MastraCode resource (storage, observability,\n * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but\n * does NOT call `init()` or create a session. The controller is returned inert so\n * the composition layer can decide its Mastra ownership and session model.\n *\n * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).\n */\n/**\n * `instanceof` checks against Mastra classes are unreliable here: published\n * packages pin exact `@mastra/core` versions, so a user's dependency graph can\n * contain multiple copies of core (and peer-keyed copies of `@mastra/libsql` /\n * `@mastra/pg`). A store built against one copy fails `instanceof` against\n * another — the injected instance then silently fell through to the\n * StorageConfig path and crashed on `config.url`. These structural checks work\n * across duplicated copies.\n */\nfunction isInjectedStorageInstance(storage: MastraCodeConfig['storage']): storage is MastraCompositeStore {\n if (!storage) return false;\n if (storage instanceof MastraCompositeStore) return true;\n // A StorageConfig is a plain data object with a string `backend`\n // discriminant; a store instance carries the MastraCompositeStore method\n // surface.\n const candidate = storage as Partial<MastraCompositeStore>;\n return typeof candidate.init === 'function' && typeof candidate.__registerMastra === 'function';\n}\n\n/** Cross-copy-safe class check: walks the prototype chain by constructor name. */\nfunction hasAncestorClassNamed(value: object, className: string): boolean {\n for (let proto = Object.getPrototypeOf(value); proto; proto = Object.getPrototypeOf(proto)) {\n if (proto.constructor?.name === className) return true;\n }\n return false;\n}\n\nfunction resolveInjectedStorageBackend(\n storage: MastraCompositeStore,\n configuredBackend?: 'libsql' | 'pg',\n): 'libsql' | 'pg' {\n if (configuredBackend) return configuredBackend;\n if (storage instanceof LibSQLStore || hasAncestorClassNamed(storage, 'LibSQLStore')) return 'libsql';\n if (storage instanceof PostgresStore || hasAncestorClassNamed(storage, 'PostgresStore')) return 'pg';\n throw new Error('storageBackend is required when injecting a custom storage instance.');\n}\n\nexport async function createMastraCodeAgentController(config?: MastraCodeConfig) {\n const cwd = config?.cwd ?? process.cwd();\n const homeDir = config?.homeDir ?? config?.initialState?.homeDir;\n const configDir = config?.configDir ?? DEFAULT_CONFIG_DIR;\n // The single session for this process, assigned once `createSession()` runs\n // below. Config callbacks defined before then (e.g. notification stream\n // options) read it lazily through this holder.\n let activeSession: Session<MastraCodeState> | undefined;\n // Same trick for the controller, which plugins reach through a lazy accessor.\n // Plugins load well before the controller is constructed, and a closure over\n // the `controller` binding itself would throw on early access rather than\n // reporting \"not ready yet\", so the accessor reads this holder instead.\n let pluginRuntimeController: AgentController<MastraCodeState> | undefined;\n if (configDir !== DEFAULT_CONFIG_DIR) {\n validateConfigDirName(configDir);\n }\n\n // Load .env file from cwd if present (for observability API keys, etc.)\n try {\n process.loadEnvFile(path.join(cwd, '.env'));\n } catch {\n // No .env file — that's fine, keys may be in shell environment\n }\n\n // Auth storage (shared with Claude Max / OpenAI providers and AgentController)\n const authStorage = createAuthStorage();\n const globalSettings = loadSettings(config?.settingsPath);\n const backgroundToolsEnabled = globalSettings.backgroundTools?.enabled ?? false;\n const storedGatewayKey = authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER);\n const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;\n\n if (storedGatewayKey) {\n process.env['MASTRA_GATEWAY_API_KEY'] ??= storedGatewayKey;\n }\n\n if (storedGatewayUrl) {\n process.env['MASTRA_GATEWAY_URL'] ??= storedGatewayUrl;\n }\n\n // Load user-entered API keys from auth.json into process.env\n // (only sets env vars that aren't already present — env vars take precedence).\n // Skipped in deployed multi-tenant mode: when a per-tenant credential store\n // provider is registered, provider keys are resolved per request and must\n // never leak into process-global env vars.\n if (!hasCredentialStoreProvider()) {\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n const providerEnvVars: Record<string, string | undefined> = {};\n for (const [provider, cfg] of Object.entries(registry)) {\n const envVars = cfg?.apiKeyEnvVar;\n providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;\n }\n providerEnvVars[MASTRA_GATEWAY_PROVIDER] ??= 'MASTRA_GATEWAY_API_KEY';\n authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);\n } catch {\n // Registry unavailable — load well-known provider keys so non-gateway flows still work\n authStorage.loadStoredApiKeysIntoEnv({\n [MASTRA_GATEWAY_PROVIDER]: 'MASTRA_GATEWAY_API_KEY',\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_GENERATIVE_AI_API_KEY',\n cerebras: 'CEREBRAS_API_KEY',\n deepseek: 'DEEPSEEK_API_KEY',\n });\n }\n }\n\n const mgApiKey = process.env['MASTRA_GATEWAY_API_KEY'] ?? storedGatewayKey;\n const mastraGatewayBaseUrl = (\n process.env['MASTRA_GATEWAY_URL'] ??\n storedGatewayUrl ??\n 'https://gateway-api.mastra.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n const mastraCodeGateway = createMastraCodeGateway({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: false,\n settingsPath: config?.settingsPath,\n });\n const amazonBedrockGateway = createAmazonBedrockGateway();\n\n // Project detection\n const project = detectProject(cwd);\n\n const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);\n if (resourceIdOverride) {\n project.resourceId = resourceIdOverride;\n project.resourceIdOverride = true;\n }\n\n const cloudObservabilityConfig = resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId);\n\n // Stable session id unique to this project/resource, and a machine-bound owner\n // id. resourceId encodes root path + git identity and honors overrides, so it\n // is the right input for scoping the session to the cwd/project.\n const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;\n const ownerId = `mastracode-${shortHash(`${hostname()}\\0${project.rootPath}`)}`;\n\n const configuredPubSub = config?.pubsub;\n const useUnixSocketPubSub =\n (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== 'win32';\n const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : undefined);\n const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);\n if (crossProcessPubSub && !signalsPubSub) {\n throw new Error('crossProcessPubSub requires a pubsub instance');\n }\n // Cross-agent communication is experimental and opt-in. It gates the agent\n // connections provider/tools and the session thread-ownership lifecycle, but\n // never the PubSub transport itself.\n const useCrossAgentSignals =\n config?.crossAgentSignals ?? globalSettings.signals?.experimentalCrossAgentSignals ?? false;\n\n // Storage. An injected instance is used as-is — no connection test, no\n // LibSQL fallback: if the injected store fails, that's a hard error.\n const injectedStorage = isInjectedStorageInstance(config?.storage) ? config.storage : undefined;\n const storageConfig = injectedStorage\n ? undefined\n : ((config?.storage as StorageConfig | undefined) ??\n getStorageConfig(project.rootPath, globalSettings.storage, configDir));\n const storageResult: StorageResult = injectedStorage\n ? { storage: injectedStorage, backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend) }\n : await createStorage(storageConfig!);\n const storageWarning = storageResult.warning;\n\n // Observability storage (DuckDB — separate file for OLAP-style trace/score/feedback queries).\n // Local tracing is opt-in via `/observability local on`. When disabled, the\n // MastraStorageExporter is omitted entirely so traces never fall through to\n // the default libsql backend.\n let observabilityDomain: DuckDBStore['observability'] | undefined;\n let observabilityWarning: string | undefined;\n if (globalSettings.observability.localTracing) {\n try {\n const observabilityDuckDB = new DuckDBStore({\n id: 'mastra-code-observability',\n path: getObservabilityDatabasePath(),\n });\n // Force an early connection attempt so the lock error surfaces now, not mid-session.\n await observabilityDuckDB.db.getConnection();\n observabilityDomain = observabilityDuckDB.observability;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isLockError = /lock|locked|busy/i.test(message);\n if (isLockError) {\n observabilityWarning =\n 'Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.';\n } else {\n observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;\n }\n }\n }\n\n const harnessStorage = new InMemoryHarness();\n\n const storage = new MastraCompositeStore({\n id: 'mastra-code-storage',\n default: storageResult.storage,\n domains: {\n // When local tracing is off, disable the observability domain entirely so\n // trace/score/feedback writes never fall through to the default libsql store.\n observability: observabilityDomain ?? false,\n harness: harnessStorage,\n },\n });\n\n // Observability (tracing, scoring, feedback)\n const observability = new Observability({\n configs: {\n default: {\n serviceName: 'mastracode',\n // Only these requestContext keys are stored on spans — prevents leaking\n // large objects (controller state, workspace, env vars) into trace data.\n // Use dot-notation because these are nested inside the 'controller' key.\n //\n // Session identifiers:\n // threadId, resourceId, session.modeId, agentControllerId\n // Environment & project:\n // state.projectName, state.gitBranch\n // Model configuration:\n // session.modelId, state.subagentModelId\n // Agent settings:\n // state.yolo, state.thinkingLevel, state.smartEditing\n // Observational memory settings:\n // state.omScope, state.observerModelId, state.reflectorModelId,\n // state.observationThreshold, state.reflectionThreshold\n requestContextKeys: [\n // Session identifiers\n 'controller.threadId',\n 'controller.resourceId',\n 'controller.session.modeId',\n 'controller.controllerId',\n // Environment & project\n 'controller.state.projectName',\n 'controller.state.gitBranch',\n // Model configuration\n 'controller.session.modelId',\n 'controller.state.subagentModelId',\n // Agent settings\n 'controller.state.yolo',\n 'controller.state.thinkingLevel',\n 'controller.state.smartEditing',\n // Observational memory settings\n 'controller.state.omScope',\n 'controller.state.observerModelId',\n 'controller.state.reflectorModelId',\n 'controller.state.observationThreshold',\n 'controller.state.reflectionThreshold',\n ],\n exporters: [\n // Only persist traces locally when DuckDB observability is available\n // (via `/observability local on`). Without this guard the storage\n // exporter falls through to the default libsql backend and silently\n // fills the main database with gigabytes of span data.\n ...(observabilityDomain ? [new MastraStorageExporter({ strategy: 'event-sourced' })] : []),\n // Credentials are always passed explicitly; `resolveFromEnv: false`\n // stops the exporter from picking up the cwd project's MASTRA_* vars.\n new MastraPlatformExporter({ ...cloudObservabilityConfig, resolveFromEnv: false }),\n ],\n spanOutputProcessors: [new SensitiveDataFilter()],\n },\n },\n });\n\n // Vector store for recall search (separate DB file to avoid bloating main\n // storage). An injected instance is used as-is; with an injected storage\n // instance and no injected vector, recall search stays vector-less.\n const vector =\n config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : undefined);\n\n // Maintenance handle for /prune: prunes via the inner store (whose retention\n // config covers every domain, including legacy libsql observability spans)\n // and can compact local libsql files to reclaim disk. The vector store's\n // connection must close alongside storage — the compaction's file swap\n // refuses to run while any connection is open.\n const storageMaintenance: StorageMaintenance = createStorageMaintenance({\n storage: storageResult.storage,\n backend: storageResult.backend,\n retention: DEFAULT_RETENTION,\n localDbFiles: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],\n closeVector: vector instanceof LibSQLVector ? () => vector.close() : undefined,\n });\n\n const memory =\n config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vector, config?.settingsPath));\n // Only the default memory wiring registers the subconscious tools; a\n // caller-supplied memory is opaque here, so its prompt must not advertise them.\n const hasSubconscious =\n config?.memory === undefined ? (state: MastraCodeState | undefined) => hasSubconsciousTools(vector, state) : false;\n\n // MCP\n const mcpManager = config?.disableMcp\n ? undefined\n : createMcpManager(project.rootPath, configDir, config?.mcpServers, globalSettings.mcp);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(\n project.rootPath,\n 'session-init',\n configDir,\n homeDir,\n project.isWorktree\n ? { path: project.rootPath, branch: project.gitBranch, mainRepoPath: project.mainRepoPath }\n : undefined,\n );\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ??\n new PluginManager({\n projectRoot: project.rootPath,\n configDir,\n homeDir,\n }));\n // Publish the runtime accessors to whichever manager is in play — including an\n // injected one, which would otherwise hand plugins `undefined` for\n // `getController`/`getActiveSession`. Lazy closures: both locals are assigned\n // after the controller is constructed below.\n pluginManager?.setRuntime({\n getController: () => pluginRuntimeController,\n getActiveSession: () => activeSession,\n getStorage: () => ({ storage, storageBackend: storageResult.backend, vector }),\n });\n const loadedPlugins = pluginManager ? await pluginManager.reload() : [];\n const pluginTools = pluginManager?.getPluginTools() ?? {};\n\n // Scorers (live evaluation with sampling)\n const outcomeScorer = createOutcomeScorer();\n const efficiencyScorer = createEfficiencyScorer();\n\n // Agent — githubSignals is created before `controller` but the closure below\n // captures `controller` by reference; it is only invoked at notification time,\n // well after controller is constructed (line ~692). Explicit type annotations\n // on githubSignals, codeAgent, modes, and controller break the circular\n // inference chain this forward reference would otherwise create.\n // Builds the stream options of every wake (a run with no inbound request).\n // Shared by GithubSignals (immediate sends) and the code agent's\n // notification delivery policy (notifications and cross-agent signals,\n // including deferred sends re-dispatched by the core notification dispatch\n // workflow) — all need the target session's request context, or a woken idle\n // thread has no model to run with (\"No model selected\"). New wake paths must\n // build their options here so `prepareWakeRequestContext` runs for them.\n const getWakeStreamOptions = async ({ resourceId, threadId }: { resourceId: string; threadId: string }) => {\n // Run the woken notification as the session that owns the target\n // resource so it uses that session's model/mode/state. Fall back to\n // the current session only when no session owns the resource yet.\n const owningSession = await controller.getSessionByResource(resourceId);\n const session = owningSession ?? activeSession;\n // No session owns the resource and none is active yet (e.g. a deferred\n // notification comes due before any session boots). Nothing to resolve a\n // model from; return undefined so the dispatcher sends a bare wake\n // instead of throwing mid-delivery.\n if (!session) return undefined;\n // A long-running system must be able to drive work unattended, so a\n // target session without an explicit model selection falls back to a\n // real model rather than failing the run: the current session's live\n // selection (what the user actually picked), then the mode's default.\n const targetThread = await session.thread.getById({ threadId });\n const metadata =\n targetThread?.resourceId === resourceId\n ? (targetThread.metadata as Record<string, unknown> | undefined)\n : undefined;\n const modes = controller.listModes();\n const savedModeId = metadata?.currentModeId;\n const defaultMode = modes.find(mode => mode.default) ?? modes[0];\n const modeId =\n typeof savedModeId === 'string' && modes.some(mode => mode.id === savedModeId)\n ? savedModeId\n : (defaultMode?.id ?? session.mode.get());\n const savedModeModelId = metadata?.[`modeModelId_${modeId}`];\n const legacyModelId = metadata?.currentModelId;\n const defaultModeModelId = modes.find(mode => mode.id === modeId)?.defaultModelId;\n const modelId =\n (typeof savedModeModelId === 'string' ? savedModeModelId : undefined) ??\n (typeof legacyModelId === 'string' ? legacyModelId : undefined) ??\n defaultModeModelId ??\n session.model.get() ??\n '';\n const baseState = { ...session.state.get() } as MastraCodeState;\n delete baseState.activeModelPackId;\n delete baseState.mastracodePendingPackFallback;\n const persistedSandboxPaths = metadata?.sandboxAllowedPaths;\n baseState.sandboxAllowedPaths =\n Array.isArray(persistedSandboxPaths) && persistedSandboxPaths.every(path => typeof path === 'string')\n ? persistedSandboxPaths\n : [];\n const persistedStateKeys = [\n 'thinkingLevel',\n 'notifications',\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n PACK_FALLBACK_STATE_KEY,\n ] as const;\n for (const key of persistedStateKeys) {\n const value = metadata?.[key];\n if (value !== undefined) (baseState as Record<string, unknown>)[key] = value;\n }\n let notificationState = baseState;\n const getNotificationState = () => ({ ...notificationState });\n const setNotificationState = async (updates: Partial<MastraCodeState>) => {\n notificationState = { ...notificationState, ...updates };\n if (session.thread.getId() === threadId) await session.state.set(updates);\n };\n const updateNotificationState: NonNullable<AgentControllerRequestContext['updateState']> = async updater => {\n const update = await updater(getNotificationState());\n if (update.updates) await setNotificationState(update.updates);\n for (const event of update.events ?? []) {\n if (session.thread.getId() === threadId) session.emit(event);\n }\n return update.result;\n };\n const requestContext = new RequestContext();\n const agentControllerContext: AgentControllerRequestContext = {\n controllerId: controller.id,\n state: getNotificationState(),\n getState: getNotificationState,\n setState: setNotificationState,\n updateState: updateNotificationState,\n getThreadSetting: key => session.thread.getSettingOn({ threadId, key }),\n setThreadSetting: setting => session.thread.setSettingOn({ threadId, key: setting.key, value: setting.value }),\n isThreadActive: () => session.thread.getId() === threadId,\n threadId,\n resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId,\n state: {\n get: getNotificationState,\n set: setNotificationState,\n update: updateNotificationState,\n },\n },\n workspace: session.getWorkspace(),\n emitEvent: event => {\n if (session.thread.getId() === threadId) session.emit(event);\n },\n getSubagentModelId: params => {\n const agentType = params?.agentType;\n const perType = agentType ? metadata?.[`subagentModelId_${agentType}`] : undefined;\n const global = metadata?.subagentModelId;\n if (typeof perType === 'string') return perType;\n if (typeof global === 'string') return global;\n return session.thread.getId() === threadId ? session.subagents.model.get(params ?? {}) : null;\n },\n };\n requestContext.set('controller', agentControllerContext);\n // Tenant identity/credentials must come from the session that owns the\n // resource; the active-session fallback is only safe for model selection.\n if (owningSession) {\n await config?.prepareWakeRequestContext?.({ requestContext, resourceId, threadId });\n }\n\n return {\n memory: { thread: threadId, resource: resourceId },\n requestContext,\n maxSteps: 1000,\n savePerStep: false,\n requireToolApproval: notificationState.yolo !== true,\n modelSettings: { temperature: 1 },\n };\n };\n\n const githubSignals: GithubSignals | undefined =\n globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals\n ? new GithubSignals({\n cwd: project.rootPath,\n pollIntervalMs: globalSettings.signals.githubPollIntervalMs,\n gitcrawlCommand:\n process.env.MASTRACODE_GITCRAWL_BIN ??\n process.env.GITCRAWL_BIN ??\n process.env.MASTRACODE_GITCRAWL_COMMAND ??\n process.env.GITCRAWL_COMMAND,\n getNotificationStreamOptions: getWakeStreamOptions,\n })\n : undefined;\n // Mastra Code's own processors are constructed once, here, rather than inside\n // the resolver below: the resolver runs before every LLM call, and rebuilding\n // stateful processors per request would reset them.\n const mastraCodeInputProcessors: InputProcessor[] = [\n ...(config?.inputProcessors ?? []),\n new PlanRejectionAbortProcessor(),\n ...(backgroundToolsEnabled ? [createBackgroundWorkSignalProcessor()] : []),\n new AgentsMDInjector({\n // Untrusted checkouts (review sessions on PR branches) must not have\n // the working tree's instruction files injected as system reminders —\n // those files are attacker-writable content, not configuration. When\n // the session carries a trusted base ref, reminders are served from\n // that ref instead (see getReader); without one they are disabled.\n isEnabled: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n return state?.untrustedCheckout !== true || typeof state?.baseRef === 'string';\n },\n getReader: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n if (state?.untrustedCheckout !== true || typeof state?.baseRef !== 'string') return undefined;\n return createGitRefReminderReader(state?.projectPath ?? project.rootPath, state.baseRef);\n },\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n const projectPath = state?.projectPath ?? project.rootPath;\n // On untrusted checkouts the static prompt loads from the base ref,\n // so compute the statically-loaded paths through the same reader to\n // keep the dedup consistent.\n const projectReader =\n state?.untrustedCheckout === true && typeof state?.baseRef === 'string'\n ? createGitRefInstructionReader(projectPath, state.baseRef)\n : undefined;\n return getStaticallyLoadedInstructionPaths(projectPath, undefined, projectReader);\n },\n }),\n new ProviderHistoryCompat(),\n ];\n\n // Built-in providers are named so the plugin lane can reserve their ids.\n const taskSignalProvider = new TaskSignalProvider();\n const agentConnectionsSignalProvider = useCrossAgentSignals\n ? new AgentConnectionsSignalProvider(config?.agentConnections)\n : undefined;\n\n const NO_PLUGIN_PROCESSORS: PluginProcessorEntries = { input: [], output: [] };\n let pluginProcessorReadWarned = false;\n\n // Providers contributed by plugins are driven from here rather than through\n // the agent's `signals` array: the Agent constructor harvests a provider's\n // processors into a closure it can never undo, so a provider wired there\n // could not be removed when its plugin is disabled, updated or uninstalled.\n // The built-in providers are seeded as reserved ids because they are wired\n // through the constructor and are therefore invisible to the lane.\n const pluginSignalLane = pluginManager\n ? new PluginSignalLane({\n reservedProviderIds: [\n taskSignalProvider.id,\n ...(agentConnectionsSignalProvider ? [agentConnectionsSignalProvider.id] : []),\n ...(githubSignals ? [githubSignals.id] : []),\n ],\n })\n : undefined;\n let unsubscribePluginReload: (() => void) | undefined;\n\n /**\n * Plugin processors are read through a function so that enabling, disabling or\n * updating a plugin takes effect on the next request rather than requiring a\n * new agent. This runs before every LLM call, and also outside the request\n * path when the Agent catalogues its configured processors — where a throw is\n * swallowed into a debug log. So it only reads already-resolved state: no\n * filesystem, no network, no construction, and it never throws.\n */\n const readPluginProcessors = (): PluginProcessorEntries => {\n try {\n return pluginManager?.getPluginProcessors() ?? NO_PLUGIN_PROCESSORS;\n } catch (error) {\n // Warn once: this is on the hot path, and a broken read repeats.\n if (!pluginProcessorReadWarned) {\n pluginProcessorReadWarned = true;\n console.warn('Failed to read plugin processors:', error);\n }\n return NO_PLUGIN_PROCESSORS;\n }\n };\n\n const codeAgent: Agent = createCodingAgent({\n id: CODE_AGENT_ID,\n name: 'Code Agent',\n // Workspace is wired per-request at the AgentController level (see\n // `config.workspace` below), so opt out of the factory's default local\n // workspace. An explicit `undefined` is required: the factory only builds a\n // default when the `workspace` key is absent.\n workspace: undefined,\n instructions: async ({ requestContext }) => {\n const configured = config?.hostInstructions;\n const hostInstructions = typeof configured === 'function' ? await configured({ requestContext }) : configured;\n return getDynamicInstructions({\n requestContext,\n hostInstructions,\n coAuthor: config?.coAuthor,\n hasSubconscious,\n hasSubagents: subagents.length > 0,\n });\n },\n // `settingsPath` matches the source `createMastraCode()` reads from so the\n // per-mode thinking defaults resolve against the same config file.\n model: ctx => getDynamicModel(ctx, config?.settingsPath),\n // Deferred notifications are re-dispatched by the core notification\n // dispatch workflow long after the originating send; the delivery policy\n // rebuilds the request context (model selection included) at delivery time\n // so waking an idle thread does not fail with \"No model selected\". The\n // default decision logic is kept as-is — the policy only attaches\n // streamOptions on top of it.\n notifications: {\n deliveryPolicy: {\n decide: async input => {\n const decision = defaultNotificationDeliveryDecision(input);\n // Without a resourceId there is no session to resolve options from —\n // don't fall through to the active session and wake it under an\n // empty resource binding.\n if (!input.record.resourceId) return decision;\n const streamOptions = await getWakeStreamOptions({\n resourceId: input.record.resourceId,\n threadId: input.record.threadId,\n });\n return streamOptions ? { ...decision, streamOptions } : decision;\n },\n },\n },\n tools: createDynamicTools(\n mcpManager,\n config?.extraTools,\n config?.disabledTools,\n storage,\n pluginTools,\n backgroundToolsEnabled,\n ),\n hooks: createToolHooks(hookManager, config?.postToolObserver),\n scorers: {\n outcome: {\n scorer: outcomeScorer,\n sampling: { type: 'none' },\n },\n efficiency: {\n scorer: efficiencyScorer,\n sampling: { type: 'ratio', rate: 0.3 },\n },\n },\n // TaskSignalProvider bundles the task tools + TaskStateProcessor: it merges\n // the tools into the toolset and registers the task state-signal processor,\n // so the task list persists across turns and survives OM truncation.\n signals: [\n taskSignalProvider,\n ...(agentConnectionsSignalProvider ? [agentConnectionsSignalProvider] : []),\n ...(githubSignals ? [githubSignals] : []),\n ],\n // Native goal mechanism: the in-loop goal step judges the thread's active\n // objective each qualifying iteration. The judge model is required for any\n // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires\n // the GoalStateProcessor so the `<current-objective>` signal persists across\n // turns. Per-thread overrides live in the ThreadState `goal` record and win\n // over these defaults.\n goal: {\n // Resolve the judge model through mastracode's gateway (a model-resolver\n // function) so provider credentials are injected; returns undefined when no\n // judge model is configured, keeping the goal step a no-op. Bind the same\n // `settingsPath` used above so the judge model and `maxRuns` come from one\n // config (a custom settings file would otherwise diverge).\n judge: ctx => getGoalJudgeModel(ctx, config?.settingsPath),\n maxRuns: globalSettings.models.goalMaxTurns ?? 50,\n maxSteps: 1000,\n prompt: DEFAULT_GOAL_JUDGE_PROMPT,\n // Read-only workspace tools the default goal judge may call to verify the\n // agent's work against the actual filesystem (view, search_content,\n // find_files, file_stat, lsp_inspect) rather than grading prose alone —\n // restoring the original MastraCode judge's verification ability. Resolved\n // per-request from the active workspace (mirrors `judge`).\n tools: getGoalJudgeTools,\n },\n inputProcessors: () => [\n ...mastraCodeInputProcessors,\n // Input-lane notice ONLY (no processAPIError — see the class doc): the\n // runner walks input processors first in runProcessAPIError, so an\n // input-lane processAPIError would rotate before transient retries run.\n new AccountStartNoticeProcessor({ credentialStore: authStorage, settingsPath: config?.settingsPath }),\n ...readPluginProcessors().input.map(entry => entry.value),\n ...(pluginSignalLane?.getInputProcessors() ?? []),\n ],\n // Mastra Code contributes no output processors of its own; the lane exists\n // so plugins can. Like the input lane, plugin processors sit last — after\n // the layers they customize, before the channel and memory layers the\n // Agent appends.\n outputProcessors: () => [\n ...readPluginProcessors().output.map(entry => entry.value),\n ...(pluginSignalLane?.getOutputProcessors() ?? []),\n ],\n errorProcessors: [\n // ProviderHistoryCompat must run before StreamErrorRetryProcessor: both react to\n // HTTP 400s, but ProviderHistoryCompat repairs the incompatible history (e.g.\n // sanitizing tool-call IDs) before retrying, while StreamErrorRetryProcessor's\n // isBadRequestError matcher retries the identical request. Error processors\n // short-circuit on the first `retry: true`, so a blind retry first would resend\n // the broken history and fail again.\n new ProviderHistoryCompat(),\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isTransientConnectionError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n {\n match: isTransientServerError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n ],\n }),\n new PrefillErrorHandler(),\n // Rotation runs last in the error lane: a transient error reaching here\n // means StreamErrorRetryProcessor already spent its budget, which is the\n // hop condition; quota/auth errors were never transient-matched and\n // rotate immediately.\n new AccountRotationProcessor({\n credentialStore: authStorage,\n // Same budget core enforces (maxProcessorRetries below): past it, core\n // discards retry:true, so the processor no-ops instead of rotating.\n maxProcessorRetries: MASTRACODE_MAX_PROCESSOR_RETRIES,\n // Same settings file getDynamicModel reads (model: above) so the pack\n // cascade the processor announces matches the chain core will walk.\n settingsPath: config?.settingsPath,\n }),\n ],\n // Individual processors have tighter limits; this remains a defensive\n // ceiling for custom/plugin processors that might retry indefinitely.\n maxProcessorRetries: MASTRACODE_MAX_PROCESSOR_RETRIES,\n });\n\n // const defaultSubAgents: Array<AgentControllerSubagent> = [];\n // const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];\n\n const defaultModes: AgentControllerMode[] = [\n {\n ...buildMode,\n metadata: {\n ...buildMode.metadata,\n color: mastraBrand.green,\n },\n },\n {\n ...planMode,\n metadata: {\n ...planMode.metadata,\n color: mastraBrand.purple,\n },\n },\n {\n ...fastMode,\n metadata: {\n ...fastMode.metadata,\n color: mastraBrand.orange,\n },\n },\n ];\n\n const defaultIntervalHandlers: IntervalHandler[] = [\n {\n id: 'gateway-sync',\n intervalMs: 5 * 60 * 1000,\n immediate: false,\n handler: () => syncGateways(),\n },\n ];\n const intervalHandlers = config?.intervalHandlers ?? defaultIntervalHandlers;\n\n // Build lightweight provider access for resolving built-in packs at startup.\n // Anthropic/OpenAI use AuthStorage; other providers use env API keys.\n // Also scan the full provider registry so configured API keys satisfy access checks.\n const anthropicCred = authStorage.get('anthropic');\n const openaiCred = authStorage.get('openai-codex');\n const githubCopilotCred = authStorage.get('github-copilot');\n const kimiCodingCred = authStorage.get('kimi-for-coding');\n const startupAccess: ProviderAccess = {\n anthropic:\n anthropicCred?.type === 'oauth'\n ? 'oauth'\n : anthropicCred?.type === 'api_key' && anthropicCred.key.trim().length > 0\n ? 'apikey'\n : false,\n openai:\n openaiCred?.type === 'oauth'\n ? 'oauth'\n : openaiCred?.type === 'api_key' && openaiCred.key.trim().length > 0\n ? 'apikey'\n : false,\n cerebras: process.env.CEREBRAS_API_KEY ? 'apikey' : false,\n google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? 'apikey' : false,\n deepseek: process.env.DEEPSEEK_API_KEY ? 'apikey' : false,\n 'github-copilot': githubCopilotCred?.type === 'oauth' ? 'oauth' : false,\n 'kimi-for-coding':\n kimiCodingCred?.type === 'oauth' && isKimiCodingDeviceId(kimiCodingCred.deviceId)\n ? 'oauth'\n : (kimiCodingCred?.type === 'api_key' && kimiCodingCred.key.trim().length > 0) ||\n Boolean(process.env.KIMI_API_KEY?.trim())\n ? 'apikey'\n : false,\n };\n // Gateway covers all providers — ensure Anthropic/OpenAI packs are visible\n if (mgApiKey) {\n if (!startupAccess.anthropic) startupAccess.anthropic = 'apikey';\n if (!startupAccess.openai) startupAccess.openai = 'apikey';\n }\n // Check all providers in the registry for API keys\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n for (const [provider, config] of Object.entries(registry)) {\n if (startupAccess[provider] === 'oauth' || startupAccess[provider] === 'apikey') continue; // Already enabled above\n if (provider === 'anthropic' || provider === 'openai') continue;\n const envVars = config?.apiKeyEnvVar;\n const envVarList = Array.isArray(envVars) ? envVars : envVars ? [envVars] : [];\n if (envVarList.some(envVar => process.env[envVar])) {\n startupAccess[provider] = 'apikey';\n }\n }\n } catch {\n // Registry may not be loaded yet; the 5 hardcoded providers are sufficient fallback\n }\n const builtinPacks = getAvailableModePacks(startupAccess);\n const builtinOmPacks = getAvailableOmPacks(startupAccess);\n const effectiveDefaults = resolveModelDefaults(globalSettings, builtinPacks);\n const activeProviderId = effectiveDefaults.build?.split('/')[0];\n const preferredOmModel = hasExplicitOMConfiguration(globalSettings)\n ? undefined\n : selectPreferredOMPack(startupAccess, activeProviderId)?.modelId;\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks) || preferredOmModel;\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks) || preferredOmModel;\n const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? undefined;\n const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? undefined;\n const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? undefined;\n const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? 'auto';\n\n const modes = addPluginToolsToModeAllowlists(\n applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults),\n Object.keys(pluginTools),\n );\n const defaultModeId =\n modes.find(mode => mode.metadata?.default === true)?.id ??\n modes.find(mode => mode.id === 'build')?.id ??\n modes[0]?.id;\n if (!defaultModeId) {\n throw new Error('MastraCode requires at least one mode');\n }\n\n const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n const disabledTools = new Set(config?.disabledTools);\n const subagents = (config?.subagents ?? [exploreSubagent, planSubagent, executeSubagent]).map(definition => ({\n ...definition,\n ...(config?.subagents == null && {\n defaultModelId:\n modes.find(mode => mode.id === subagentModeMap[definition.id])?.defaultModelId ??\n modes.find(mode => mode.id === defaultModeId)?.defaultModelId,\n }),\n allowedControllerTools: definition.allowedControllerTools?.filter(name => !disabledTools.has(name)),\n allowedWorkspaceTools: definition.allowedWorkspaceTools?.filter(name => !disabledTools.has(name)),\n ...(definition.tools && {\n tools: Object.fromEntries(Object.entries(definition.tools).filter(([name]) => !disabledTools.has(name))),\n }),\n }));\n\n // Build initial state with global preferences. OM knobs are skipped when the\n // host persists memory settings elsewhere (`disableSettingsOmSeed`) so the\n // machine-local settings.json never leaks into server sessions.\n const globalInitialState: Partial<MastraCodeState> = {};\n if (!config?.disableSettingsOmSeed) {\n if (effectiveObserverModel) {\n globalInitialState.observerModelId = effectiveObserverModel;\n }\n if (effectiveReflectorModel) {\n globalInitialState.reflectorModelId = effectiveReflectorModel;\n }\n if (effectiveObservationThreshold !== undefined) {\n globalInitialState.observationThreshold = effectiveObservationThreshold;\n }\n if (effectiveReflectionThreshold !== undefined) {\n globalInitialState.reflectionThreshold = effectiveReflectionThreshold;\n }\n if (effectiveCavemanObservations !== undefined) {\n globalInitialState.cavemanObservations = effectiveCavemanObservations;\n }\n if (effectiveObserveAttachments !== undefined) {\n globalInitialState.observeAttachments = effectiveObserveAttachments;\n }\n }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n // Note: `thinkingLevel` is intentionally NOT seeded into session state. The\n // state slot is a session-level override; the effective level is resolved at\n // request time (per-mode defaults → global preference) in getDynamicModel so\n // settings changes apply to the next request of every session.\n if (config?.omScope) {\n globalInitialState.omScope = config.omScope;\n }\n // Seed subagent models from global settings\n for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) {\n if (key === 'default' || key === '_default') {\n globalInitialState.subagentModelId = modelId;\n } else {\n globalInitialState[`subagentModelId_${key}`] = modelId;\n }\n }\n\n const typedStateSchema = stateSchema as PublicSchema<MastraCodeState>;\n const backgroundCompletionEvents = backgroundToolsEnabled ? createBackgroundCompletionEvents() : undefined;\n let controller: AgentController<MastraCodeState>;\n controller = new AgentController<MastraCodeState>({\n id: 'mastra-code',\n resourceId: project.resourceId,\n storage,\n ...(backgroundToolsEnabled\n ? {\n backgroundTasks: {\n enabled: true,\n recoverStaleTasksOnStart: false,\n ...createBackgroundCompletionCallbacks(() => controller, backgroundCompletionEvents),\n },\n }\n : {}),\n observability,\n memory,\n pubsub: signalsPubSub,\n stateSchema: typedStateSchema,\n agent: codeAgent,\n subagents,\n gateways: [amazonBedrockGateway, mastraCodeGateway],\n workspace: config?.workspace ?? (args => getDynamicWorkspace({ ...args, backgroundToolsEnabled })),\n browser: config?.browser,\n idGenerator: config?.idGenerator,\n toolCategoryResolver: getToolCategory,\n initialState: {\n projectPath: project.rootPath,\n projectName: project.name,\n gitBranch: project.gitBranch,\n pluginSkillPaths: loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : [])),\n pluginCommandPaths: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' ? (plugin.commandPaths ?? []) : [],\n ),\n pluginInstructions: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n ),\n yolo: true,\n ...globalInitialState,\n ...config?.initialState,\n // configDir must always win over initialState spreads to stay in sync\n // with MCP/hooks/storage which were already initialized with this value.\n configDir,\n },\n modes,\n intervalHandlers,\n modelUseCountProvider: () => loadSettings().modelUseCounts,\n modelUseCountTracker: modelId => {\n try {\n const settings = loadSettings();\n settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;\n saveSettings(settings);\n } catch (error) {\n console.error('Failed to persist model usage count', error);\n }\n },\n threadLock: crossProcessPubSub\n ? undefined\n : {\n acquire: acquireThreadLock,\n release: releaseThreadLock,\n },\n });\n\n const sessionPeerCleanup = new WeakMap<Session<MastraCodeState>, () => void>();\n // Thread ownership advertisement is part of experimental cross-agent\n // communication: without it, sessions never claim or advertise their thread to\n // peers. Every thread a session has loaded stays claimed (see\n // `createSessionThreadAdvertisement`) so peers that saved it stay connected\n // after the user moves to another thread.\n if (useCrossAgentSignals) {\n controller.onSessionCreated(\n async session => {\n const advertisement = createSessionThreadAdvertisement({\n session,\n controller,\n projectName: project.name,\n });\n sessionPeerCleanup.set(session, () => advertisement.close());\n const initialThreadId = session.thread.getId();\n if (initialThreadId) {\n // This listener blocks session creation, so bound the initial claim:\n // an unsettled PubSub subscription must not hang createSession().\n // The claim keeps settling in the background either way.\n await Promise.race([\n advertisement.claim(initialThreadId),\n new Promise<void>(resolve => {\n const timer = setTimeout(resolve, 5_000);\n timer.unref?.();\n }),\n ]);\n }\n },\n { blocking: true },\n );\n controller.onSessionDeleted(session => {\n sessionPeerCleanup.get(session)?.();\n sessionPeerCleanup.delete(session);\n });\n }\n\n // Publish the controller to the plugin runtime accessors now that it exists.\n pluginRuntimeController = controller;\n\n if (pluginSignalLane && pluginManager) {\n // Register the plugins loaded at startup, and re-reconcile on every reload.\n // Providers are not started here: they need a Mastra instance for storage,\n // and Mastra does not exist until the composition layer boots the controller\n // (see `startPluginSignalProviders` on the returned object).\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders());\n unsubscribePluginReload = pluginManager.onReload(() =>\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders()),\n );\n }\n\n // The AgentController is fully constructed but intentionally NOT inited here. Init and\n // session creation are deferred to the composition layer (see below) so the\n // controller can be wired in three ways:\n //\n // 1. Server + Web — registered on a server Mastra, then inited; sessions\n // minted per browser client over HTTP.\n // 2. Server + TUI — same server composition; the TUI drives a session\n // (in-process today; remote transport is future work).\n // 3. Local + TUI — controller builds its own internal Mastra on init() and\n // mints one eager session for the whole process.\n //\n // Cases 1 & 2 use `mountAgentControllerOnMastra` (register-before-init, no eager\n // session). Case 3 uses `bootLocalAgentController` (init + one wired session).\n return {\n controller: controller,\n storage,\n storageMaintenance,\n createKnowledgeInspector: (session: Session<MastraCodeState>) =>\n createScopedKnowledgeInspector({ storage, session }),\n observability,\n memory,\n mcpManager,\n hookManager,\n pluginManager,\n loadedPlugins,\n pluginTools,\n signalsPubSub,\n authStorage,\n resolveModel,\n storageWarning,\n observabilityWarning,\n builtinPacks,\n builtinOmPacks,\n effectiveDefaults,\n githubSignals,\n backgroundToolsEnabled,\n backgroundCompletionEvents,\n // Identity for the single local session (Case 3). Servers ignore these and\n // mint per-request sessions with client-supplied resourceIds instead.\n sessionId,\n ownerId,\n // Surface the project root so boot/mount paths can wire workflow tools\n // against a workspace anchored at it without re-running detectProject().\n projectPath: project.rootPath,\n // Surface the Agent instance so registerWorkflowBuilderPrimitives can add\n // it as a plain agent on the Mastra registry. Workflows then compose it\n // as an agent step (agentId: 'code-agent') and delegate open-ended tool\n // orchestration to it — code-agent already has full workspace / MCP / web\n // access via its dynamic tool factory.\n codeAgent,\n // Lets the composition layer publish the created session back into the\n // config closures (e.g. notification stream options read it lazily).\n setActiveSession: (session: Session<MastraCodeState>) => {\n activeSession = session;\n },\n /**\n * Starts the signal providers contributed by plugins. Called by the\n * composition layer once the controller is inited, because that is when a\n * Mastra instance exists — a provider without one has no storage, and\n * nothing else will hand it one: the Agent propagates Mastra only to the\n * providers in its own `signals` array, which these deliberately are not in.\n */\n startPluginSignalProviders: () => {\n const mastra = controller.getMastra();\n if (!pluginSignalLane || !mastra) return;\n pluginSignalLane.setMastra(mastra, codeAgent);\n },\n /**\n * Stops every plugin-contributed signal provider and stops listening for\n * plugin reloads. The inverse of `startPluginSignalProviders`, for an\n * embedder that is done with this controller: a `pluginManager` shared\n * across controllers (`MastraCodeConfig.pluginManager`) outlives any one of\n * them, so without this its providers keep polling and its reload listener\n * keeps firing for a controller that is gone.\n */\n stopPluginSignalProviders: () => {\n unsubscribePluginReload?.();\n unsubscribePluginReload = undefined;\n pluginSignalLane?.stopAll();\n },\n /**\n * Hands Mastra to the statically configured input processors.\n *\n * The Agent does this itself, but only for processors configured as a\n * plain array (`Array.isArray` in `__registerMastra`). This lane is a\n * function so plugins can contribute to it, which takes those processors\n * out of that branch — including any an embedder passed as\n * `config.inputProcessors`, some of which need Mastra to work at all\n * (`CostGuardProcessor` reads observability storage there). Doing it here\n * keeps that unchanged.\n *\n * Plugin processors are deliberately not included: they come and go with\n * their plugin, and the registry keeps the first instance registered under\n * an id forever, which would leave a retired instance behind. Plugins\n * reach Mastra through `getController()` on the plugin context instead.\n */\n registerConfiguredProcessorsWithMastra: () => {\n const mastra = controller.getMastra();\n if (!mastra) return;\n for (const processor of mastraCodeInputProcessors) {\n mastra.addProcessor(processor as Processor);\n mastra.addProcessorConfiguration(processor as Processor, CODE_AGENT_ID, 'input');\n }\n },\n };\n}\n\n/**\n * Result of {@link createMastraCodeAgentController}: every shared resource plus the\n * inert AgentController, ready to be either booted locally or mounted on a server\n * Mastra.\n */\nexport type MastraCodeAgentController = Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n\n/**\n * Wires the session-scoped concerns MastraCode layers on top of a Session:\n * hookManager thread-id sync, GitHub PR polling for the current thread, and\n * per-thread persistence of the mastracode-only `/om` settings.\n *\n * Used by {@link bootLocalAgentController} for the single local session. A server can\n * call this for any session it mints if it wants the same background wiring.\n */\nexport async function wireSessionConcerns(\n base: Pick<MastraCodeAgentController, 'hookManager' | 'githubSignals' | 'setActiveSession'>,\n session: Session<MastraCodeState>,\n): Promise<void> {\n const { hookManager, githubSignals } = base;\n base.setActiveSession(session);\n\n // Sync hookManager session ID on thread changes\n if (hookManager) {\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') {\n hookManager.setSessionId(event.threadId);\n } else if (event.type === 'thread_created') {\n hookManager.setSessionId(event.thread.id);\n }\n });\n }\n\n if (githubSignals) {\n const startGithubPollingForCurrentThread = async (threadId?: string | null) => {\n if (!threadId) return;\n githubSignals.stopAllPolling();\n try {\n const threads = await session.thread.list({ allResources: true });\n const thread = threads.find((item: { id: string }) => item.id === threadId);\n await githubSignals.startPollingForThread(\n {\n threadId,\n resourceId: thread?.resourceId ?? session.identity.getResourceId(),\n },\n { pollImmediately: true },\n );\n } catch (error) {\n console.warn('Failed to start GitHub PR polling:', error);\n }\n };\n\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') void startGithubPollingForCurrentThread(event.threadId);\n else if (event.type === 'thread_created') void startGithubPollingForCurrentThread(event.thread.id);\n });\n void startGithubPollingForCurrentThread(session.thread.getId());\n }\n\n // Persist MastraCode-owned /om settings per-thread (mastracode-only concern;\n // intentionally not in core's controller loadThreadMetadata).\n const omThreadStateSession = session as unknown as Session<Record<string, unknown>>;\n attachOMThreadStatePersistence(omThreadStateSession);\n await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {\n // Persistence is best-effort; don't crash startup if storage hiccups.\n });\n}\n\n/**\n * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its\n * own internal Mastra via `init()`, and mint the single eager session that all\n * work in this process runs through. The AgentController owns no session of its own.\n */\nexport async function bootLocalAgentController(config?: MastraCodeConfig) {\n const base = await createMastraCodeAgentController(config);\n const { controller, sessionId, ownerId, projectPath, codeAgent, mcpManager } = base;\n\n await controller.init();\n // Register workflow primitives (sub-agent + workspace tools + code-agent\n // + web + notification_inbox + snapshot of MCP tools) on the controller's\n // Mastra so the dynamic-workflow loading in startWorkers() can rehydrate\n // saved workflows against the right tool/agent registry.\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n await mastra?.startWorkers();\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\n const session = await controller.createSession({ id: sessionId, ownerId });\n await wireSessionConcerns(base, session);\n const knowledgeInspector = await base.createKnowledgeInspector(session);\n\n return {\n ...base,\n session,\n knowledgeInspector,\n knowledgeInspectorUnavailableReason: knowledgeInspector\n ? undefined\n : 'Knowledge inspection requires a configured knowledge storage domain.',\n };\n}\n\n/** Result of {@link mountAgentControllerOnMastra}: shared handles plus the owning Mastra. */\nexport type MountedMastraCode = MastraCodeAgentController & { mastra: Mastra };\n\n/**\n * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a\n * server-owned Mastra, THEN init it. Registering before `init()` is what makes\n * the controller inherit the server's Mastra (storage, agents, gateways) instead of\n * spinning up its own internal one — there is a single shared Mastra.\n *\n * No eager session is minted: each client (browser or terminal) creates/resumes\n * its own isolated session via `controller.createSession({ resourceId })`, so one\n * server can drive many concurrent users.\n *\n * Pass an existing `mastra` to mount onto a Mastra that already hosts other\n * primitives; otherwise a Mastra is created that owns the controller's storage so\n * durability is configured in one place.\n */\nexport async function mountAgentControllerOnMastra(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n /**\n * Additional `server` config to fold onto the constructed Mastra alongside\n * the assembled `apiRoutes` (e.g. `middleware`, `cors`). Used by the\n * platform entry (`src/mastra/index.ts`) to own the WorkOS gate + tenant\n * dispatcher + CORS on the instance the deployer generates its server from.\n * Ignored when `mastra` is provided (mounting onto a caller-owned instance).\n */\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<MountedMastraCode> {\n const prepared = await prepareAgentControllerMount(config);\n if (config?.mastra) {\n // Mounting onto a Mastra the caller already built. Ensure the controller's\n // back-reference points at it (idempotent — only sets #externalMastra).\n prepared.base.controller.__registerMastra(config.mastra);\n await prepared.finalize();\n return { ...prepared.base, mastra: config.mastra };\n }\n const mastra = new Mastra(prepared.mastraArgs);\n await prepared.finalize();\n return { ...prepared.base, mastra };\n}\n\n/**\n * Assemble everything needed to construct the server-owned Mastra WITHOUT\n * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can\n * run the `new Mastra(...)` literal in its own module. The deployer's\n * `checkConfigExport` Babel plugin only marks the config valid when it finds a\n * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the\n * construction inside this helper would trip the \"Invalid Mastra config\" warning.\n *\n * Returns the constructor args plus a `finalize()` that runs the post-construct\n * boot (`controller.init()` + `startWorkers()`). The controller is registered on\n * the Mastra via the `agentControllers` arg at construction time.\n */\nexport async function prepareAgentControllerMount(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<{\n base: Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n mastraArgs: NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n finalize: () => Promise<void>;\n}> {\n const base = await createMastraCodeAgentController(config);\n const {\n controller,\n storage,\n authStorage,\n projectPath,\n codeAgent,\n mcpManager,\n backgroundToolsEnabled,\n backgroundCompletionEvents,\n } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n // Only register workflow primitives when we own the Mastra. If the caller\n // brought their own, they're responsible for what's registered on it.\n const weOwnTheMastra = !config?.mastra;\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n ...(backgroundToolsEnabled\n ? {\n backgroundTasks: {\n enabled: true,\n recoverStaleTasksOnStart: false,\n ...createBackgroundCompletionCallbacks(() => controller, backgroundCompletionEvents),\n },\n }\n : {}),\n // Mirror the controller's internal-Mastra construction (which passes\n // `config.pubsub` through): the server-owned Mastra must run its event\n // bus on the same transport so streams/workflows/signals stay\n // cross-process when a distributed PubSub (e.g. Redis Streams) is\n // configured.\n ...(base.signalsPubSub ? { pubsub: base.signalsPubSub } : {}),\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n if (weOwnTheMastra) {\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n }\n await controller.getMastra()?.startWorkers();\n // Anchored here rather than at a `new Mastra(...)` call site: finalize runs\n // in every mount path (caller-supplied Mastra, SDK-constructed Mastra, and\n // the platform entry that constructs its own), so plugin providers start\n // exactly once regardless of how Mastra Code was mounted.\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\n };\n\n return { base, mastraArgs, finalize };\n}\n\n/**\n * Back-compat alias. Historically `createMastraCode` built and booted a local\n * controller with a single session; that behavior now lives in\n * {@link bootLocalAgentController}. New code should call the explicit factory for its\n * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).\n */\nexport const createMastraCode = bootLocalAgentController;\nexport * from './knowledge-inspector.js';\nexport { LOCAL_KNOWLEDGE_ORG_ID } from './knowledge-scope.js';\n\n/**\n * Programmatic headless API. `runMC` runs an already-built controller/session\n * (from {@link createMastraCode}) as an async-iterable run that also resolves to\n * a typed result. Also available via the `mastracode/headless` subpath.\n */\nexport {\n runMC,\n runMCCli,\n hasHeadlessFlag,\n autoApprovePolicy,\n denyPolicy,\n permissionModeToPolicy,\n formatHuman,\n formatJsonl,\n renderTextResult,\n renderJsonResult,\n} from './headless/index.js';\nexport type {\n RunMCOptions,\n RunMCResult,\n RunMC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,QAAQ,gBAAgB,WAAW;CACxD,MAAM,YAAY,QAAQ,iBAAiB;EAAE;EAAY;CAAY,CAAC;CACtE,MAAM,oBAAoB,QAAQ,oBAAoB;EAAE;EAAY;CAAY,CAAC;CAGjF,MAAM,iBAAiB,CAAC,QAAQ;CAEhC,MAAM,eAAe;EACnB,GAAG;EACH,GAAI,WAAW,SAAS,EAAE,UAAU,IAAI,CAAC;CAC3C;CACA,MAAM,aAAa;EACjB,kBAAkB,GAAG,eAAe,WAAW;EAC/C;EACA,GAAI,yBACA,EACE,iBAAiB;GACf,SAAS;GACT,0BAA0B;GAC1B,GAAG,0CAA0C,YAAY,0BAA0B;EACrF,EACF,IACA,CAAC;EAML,GAAI,KAAK,gBAAgB,EAAE,QAAQ,KAAK,cAAc,IAAI,CAAC;EAC3D,GAAI,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,EAAE,QAAQ,aAAa,IAAI,CAAC;CACrE;CAEA,MAAM,WAAW,YAAY;EAC3B,MAAM,WAAW,KAAK;EACtB,IAAI,gBAAgB;GAClB,MAAM,SAAS,WAAW,UAAU;GACpC,IAAI,QAAQ,MAAM,kCAAkC,QAAQ;IAAE;IAAa;IAAW;GAAW,CAAC;EACpG;EACA,MAAM,WAAW,UAAU,CAAC,EAAE,aAAa;EAK3C,KAAK,uCAAuC;EAC5C,KAAK,2BAA2B;CAClC;CAEA,OAAO;EAAE;EAAM;EAAY;CAAS;AACtC;;;;;;;AAQA,MAAa,mBAAmB"}
1
+ {"version":3,"file":"index.js","names":["createScopedKnowledgeInspector"],"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport path from 'node:path';\n\nimport type { Agent } from '@mastra/core/agent';\nimport { AgentController } from '@mastra/core/agent-controller';\nimport type {\n IntervalHandler,\n AgentControllerConfig,\n AgentControllerEvent,\n AgentControllerMode,\n AgentControllerSubagent,\n AgentControllerRequestContext,\n Session,\n} from '@mastra/core/agent-controller';\nimport { createCodingAgent } from '@mastra/core/coding-agent';\nimport type { PubSub } from '@mastra/core/events';\nimport { PROVIDER_REGISTRY } from '@mastra/core/llm';\nimport type { ProviderConfig } from '@mastra/core/llm';\nimport { Mastra } from '@mastra/core/mastra';\nimport { defaultNotificationDeliveryDecision } from '@mastra/core/notifications';\nimport {\n AgentsMDInjector,\n createBackgroundWorkSignalProcessor,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport type { InputProcessor, Processor } from '@mastra/core/processors';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { PublicSchema } from '@mastra/core/schema';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { TaskSignalProvider } from '@mastra/core/signals';\nimport { InMemoryHarness, MastraCompositeStore } from '@mastra/core/storage';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '@mastra/core/tools';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\nimport { PostgresStore } from '@mastra/pg';\n\nimport { createSessionThreadAdvertisement } from './agent-connections/session-advertisement.js';\nimport { AgentConnectionsSignalProvider } from './agent-connections/signal-provider.js';\nimport type { AgentConnectionsSignalProviderOptions } from './agent-connections/signal-provider.js';\nimport { createBackgroundCompletionEvents } from './agents/background-completion-events.js';\nimport { createBackgroundCompletionCallbacks } from './agents/background-completion.js';\nimport { hasCredentialStoreProvider } from './agents/credential-resolver.js';\nimport { getDynamicInstructions } from './agents/instructions.js';\nimport { getDynamicMemory, hasSubconsciousTools } from './agents/memory.js';\nimport { createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from './agents/model.js';\nimport { buildMode } from './agents/modes/build.js';\nimport { fastMode } from './agents/modes/explore.js';\nimport { planMode } from './agents/modes/plan.js';\nimport {\n createGitRefInstructionReader,\n createGitRefReminderReader,\n getStaticallyLoadedInstructionPaths,\n} from './agents/prompts/agent-instructions.js';\nimport { executeSubagent } from './agents/subagents/execute.js';\nimport { exploreSubagent } from './agents/subagents/explore.js';\nimport { planSubagent } from './agents/subagents/plan.js';\nimport { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from './agents/thread-caveman-state.js';\nimport { createDynamicTools, createToolHooks } from './agents/tools.js';\nimport type { PostToolObserver, ToolLike } from './agents/tools.js';\n\nimport { getDynamicWorkspace, getGoalJudgeTools } from './agents/workspace.js';\nimport {\n AccountRotationProcessor,\n AccountStartNoticeProcessor,\n PACK_FALLBACK_STATE_KEY,\n} from './auth/account-rotation-processor.js';\nimport { isKimiCodingDeviceId } from './auth/providers/kimi-coding.js';\nimport { AuthStorage } from './auth/storage.js';\nimport { DEFAULT_CONFIG_DIR, validateConfigDirName } from './constants.js';\nimport { createOutcomeScorer, createEfficiencyScorer } from './evals/scorers/index.js';\nimport { HookManager } from './hooks/index.js';\nimport { createKnowledgeInspector as createScopedKnowledgeInspector } from './knowledge-inspector.js';\nimport { createMcpManager } from './mcp/index.js';\nimport type { McpServerConfig } from './mcp/index.js';\nimport { hasExplicitOMConfiguration } from './onboarding/om-settings.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks, selectPreferredOMPack } from './onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_GATEWAY_PROVIDER,\n OBSERVABILITY_AUTH_PREFIX,\n resolveModelDefaults,\n resolveOmRoleModel,\n saveSettings,\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n} from './onboarding/settings.js';\nimport { getToolCategory } from './permissions.js';\nimport { PluginManager } from './plugins/manager.js';\nimport { PluginSignalLane } from './plugins/signal-lane.js';\nimport type { PluginProcessorEntries } from './plugins/types.js';\nimport { PlanRejectionAbortProcessor } from './processors/plan-rejection-abort.js';\nimport { createAmazonBedrockGateway } from './providers/amazon-bedrock-gateway.js';\nimport { setAuthStorage } from './providers/claude-max.js';\nimport { setAuthStorage as setGitHubCopilotAuthStorage } from './providers/github-copilot.js';\nimport { setAuthStorage as setKimiCodingAuthStorage } from './providers/kimi-coding.js';\nimport { setAuthStorage as setOpenAIAuthStorage } from './providers/openai-codex.js';\nimport { setAuthStorage as setXAIAuthStorage } from './providers/xai.js';\n\nimport { stateSchema } from './schema.js';\nimport type { MastraCodeState } from './schema.js';\n\nimport { mastraBrand } from './theme-palette.js';\nimport { syncGateways } from './utils/gateway-sync.js';\nimport {\n detectProject,\n getObservabilityDatabasePath,\n getStorageConfig,\n getResourceIdOverride,\n} from './utils/project.js';\nimport type { StorageConfig } from './utils/project.js';\nimport { createSignalsPubSub } from './utils/signals-pubsub.js';\nimport { createStorage, createVectorStore } from './utils/storage-factory.js';\nimport type { StorageResult } from './utils/storage-factory.js';\nimport { createStorageMaintenance, DEFAULT_RETENTION, resolveLocalDbFiles } from './utils/storage-maintenance.js';\nimport type { StorageMaintenance } from './utils/storage-maintenance.js';\nimport { acquireThreadLock, releaseThreadLock } from './utils/thread-lock.js';\nimport { registerWorkflowBuilderPrimitives } from './workflows/register-primitives.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient provider failures (e.g. dropped sockets and server errors).\n// Applied centrally to every model call via StreamErrorRetryProcessor, independent of model-pack\n// settings, so all modes/subagents benefit from a short wait before retrying a transient failure.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 10;\n// Shared ceiling for the whole processor error lane: core counts every\n// processor-requested retry against this one number. Sized for the largest\n// legitimate cascade — a rotation step per remaining account per pack hop\n// (8 representative accounts x 8 packs) — rather than an open-ended budget, so\n// a custom or plugin processor that returns `retry: true` loops at most this\n// many times instead of amplifying one request without bound.\nconst MASTRACODE_MAX_PROCESSOR_RETRIES = 64;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 500;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 30000;\n\nconst TRANSIENT_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE']);\nconst TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;\n// Any 5xx is treated as transient so server errors exhaust the transient retry\n// budget before the account-rotation processor classifies them as a persistent\n// outage (hop). Must stay aligned with `classifyRotationError`'s 5xx check.\nconst isTransientServerStatus = (status: number) => status >= 500 && status < 600;\nconst TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN = /internal server|server error|api may be experiencing issues/i;\n\n/**\n * Matcher for transient connection failures. Cause-chain traversal is handled\n * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each\n * matcher at every level of the cause chain.\n */\n/**\n * Read the session state fields the AgentsMDInjector callbacks need from the\n * controller request context (set by hosts like the factory review flow).\n */\nfunction getInjectorSessionState(\n requestContext: { get: (key: string) => unknown } | undefined,\n): { untrustedCheckout?: boolean; baseRef?: string; projectPath?: string } | undefined {\n const agentControllerContext = requestContext?.get('controller') as\n | AgentControllerRequestContext<{ untrustedCheckout?: boolean; baseRef?: string; projectPath?: string }>\n | undefined;\n return agentControllerContext?.getState();\n}\n\nfunction isTransientConnectionError(error: unknown): boolean {\n if (!error) return false;\n\n const code = typeof error === 'object' && 'code' in error ? (error as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\nfunction isTransientServerError(error: unknown): boolean {\n if (!error) return false;\n\n const errorObj = typeof error === 'object' ? (error as { status?: unknown; statusCode?: unknown }) : undefined;\n if (\n (typeof errorObj?.status === 'number' && isTransientServerStatus(errorObj.status)) ||\n (typeof errorObj?.statusCode === 'number' && isTransientServerStatus(errorObj.statusCode))\n ) {\n return true;\n }\n\n const message = error instanceof Error ? error.message : undefined;\n return typeof message === 'string' && TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN.test(message);\n}\n\nfunction getTransientRetryDelay(retryCount: number): number {\n return Math.min(\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS,\n );\n}\n\nfunction emitTransientRetry(\n error: unknown,\n retryCount: number,\n delayMs: number,\n requestContext?: RequestContext,\n): void {\n const controllerContext = requestContext?.get('controller') as AgentControllerRequestContext | undefined;\n controllerContext?.emitEvent?.({\n type: 'error',\n error: error instanceof Error ? error : new Error(String(error)),\n retryable: true,\n retryDelay: delayMs,\n retryAttempt: retryCount + 1,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n });\n}\n\n/** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */\nfunction shortHash(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 12);\n}\n\nfunction applyEffectiveDefaultsToModes(\n modes: AgentControllerMode[],\n effectiveDefaults: Record<string, string>,\n): AgentControllerMode[] {\n return modes.map(mode => {\n const savedModel = effectiveDefaults[mode.id];\n if (!savedModel) {\n return mode;\n }\n return {\n ...mode,\n defaultModelId: savedModel,\n };\n });\n}\n\nfunction addPluginToolsToModeAllowlists(\n modes: AgentControllerMode[],\n pluginToolNames: string[],\n): AgentControllerMode[] {\n if (pluginToolNames.length === 0) return modes;\n return modes.map(mode => {\n if (!mode.availableTools) return mode;\n return {\n ...mode,\n availableTools: Array.from(new Set([...mode.availableTools, ...pluginToolNames])),\n };\n });\n}\n\nexport interface MastraCodeConfig {\n /** Working directory for project detection. Default: process.cwd() */\n cwd?: string;\n /** Home directory for global config discovery. Default: os.homedir() */\n homeDir?: string;\n /** Override modes (model IDs, colors, which modes exist). Default: build/plan/fast */\n modes?: AgentControllerMode[];\n /** Replace subagent definitions. Default: explore/plan/execute. An empty array disables subagents. */\n subagents?: AgentControllerSubagent[];\n /** Extra tools merged into the dynamic tool set. Can be a static record or a (sync or async) function that receives requestContext. */\n extraTools?:\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */\n postToolObserver?: PostToolObserver;\n /**\n * Stateless input processor instances prepended before Mastra Code's mandatory processors.\n * Embedders may extend processing but cannot replace built-in safety and compatibility policy.\n */\n inputProcessors?: InputProcessor[];\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /**\n * Custom storage config instead of auto-detected default, or a pre-built\n * store instance. An instance is used as-is: no connection test and no\n * LibSQL fallback — if the injected store fails, that's a hard error.\n */\n storage?: StorageConfig | MastraCompositeStore;\n /** Backend for an injected custom storage instance. Inferred for LibSQLStore and PostgresStore. */\n storageBackend?: 'libsql' | 'pg';\n /** Pre-built vector store instance for recall search. Skips the default vector store creation. */\n vector?: MastraVector;\n /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */\n omScope?: 'thread' | 'resource';\n /** Path to a custom settings.json file. Default: global settings */\n settingsPath?: string;\n /** Initial state overrides (yolo, thinkingLevel, etc.) */\n initialState?: Partial<MastraCodeState>;\n /** Trusted host instructions resolved outside mutable session state. */\n hostInstructions?:\n | string\n | ((ctx: { requestContext: RequestContext }) => string | undefined | Promise<string | undefined>);\n /** Commit co-author identity included in coding-agent commit guidance. Unspecified fields use core defaults. */\n coAuthor?: { name?: string; email?: string };\n /** Override id generation for threads/messages. Primarily useful for deterministic tests. */\n idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];\n /** Override interval handlers. Default: gateway-sync */\n intervalHandlers?: IntervalHandler[];\n /** Override the workspace. Default: local filesystem + local sandbox based on detected project */\n workspace?: AgentControllerConfig<MastraCodeState>['workspace'];\n /** Override the config directory name. Default: '.mastracode'. Replaces '.mastracode' in all project-level and global config paths (MCP, hooks, commands, database, skills, agent instructions). */\n configDir?: string;\n /** Programmatic MCP server configurations, merged with (and overriding) file-based configs. */\n mcpServers?: Record<string, McpServerConfig>;\n /** Disable MCP server discovery. Default: false */\n disableMcp?: boolean;\n /** Disable hooks. Default: false */\n disableHooks?: boolean;\n /** Disable plugin discovery/loading. Default: false */\n disablePlugins?: boolean;\n /** Disable the polling-based GitHub signal provider even when enabled in global settings. Default: false */\n disableGithubSignals?: boolean;\n /**\n * Skip seeding observational-memory knobs (observer/reflector models,\n * thresholds, caveman mode, attachment observation) from settings.json.\n * Server deployments that persist memory settings in their own database\n * (the factory's `memory-settings` domain) set this so the host machine's\n * TUI settings file never leaks into server sessions. Default: false.\n */\n disableSettingsOmSeed?: boolean;\n /** Override the plugin manager. Primarily useful for tests or embedding. */\n pluginManager?: PluginManager;\n /**\n * Override the memory instance (or dynamic factory) passed to the AgentController.\n * When provided, this replaces the default `getDynamicMemory(storage, vector)` which\n * uses mastracode's built-in model gateway (Anthropic OAuth, OpenAI Codex,\n * custom providers, and models.dev fallback).\n *\n * Use this when you need to override memory model behavior completely.\n */\n memory?: AgentControllerConfig<MastraCodeState>['memory'] | false;\n /** Browser provider for browser automation tools. When set, the agent gains access to browser tools. */\n browser?: AgentControllerConfig<MastraCodeState>['browser'];\n /** PubSub for signal routing. When crossProcessPubSub is true, thread locks are disabled. */\n pubsub?: PubSub;\n /** Use Mastra Code's built-in Unix socket PubSub for local cross-process signal routing. */\n unixSocketPubSub?: boolean;\n /** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */\n crossProcessPubSub?: boolean;\n /** Agent connection state and discovery options. */\n agentConnections?: AgentConnectionsSignalProviderOptions;\n /**\n * Enable experimental cross-agent communication: thread ownership\n * advertisement, peer discovery, and the agent connection tools. Defaults to\n * the `signals.experimentalCrossAgentSignals` global setting (off). This does\n * not gate the PubSub transport itself — cross-agent communication simply\n * uses the configured PubSub when enabled.\n */\n crossAgentSignals?: boolean;\n /**\n * Prepare the request context of a wake: a run on a thread with no inbound\n * request, such as a notification or cross-agent signal delivered to an idle\n * thread. Hosts that resolve credentials per tenant use this to attach the\n * identity that owns `resourceId` before the run starts. Called only when a\n * session owns `resourceId`, whenever Mastra Code builds a wake's stream\n * options.\n */\n prepareWakeRequestContext?: (args: {\n requestContext: RequestContext;\n resourceId: string;\n threadId: string;\n }) => void | Promise<void>;\n}\n\nexport function createAuthStorage() {\n const authStorage = new AuthStorage();\n setAuthStorage(authStorage);\n setOpenAIAuthStorage(authStorage);\n setGitHubCopilotAuthStorage(authStorage);\n setKimiCodingAuthStorage(authStorage);\n setXAIAuthStorage(authStorage);\n return authStorage;\n}\n\n/**\n * Resolve cloud observability credentials for the MastraPlatformExporter.\n * Priority: per-resource settings > MASTRACODE_* environment variables > undefined (no exporter).\n *\n * The env vars are deliberately namespaced `MASTRACODE_*`, not `MASTRA_*`: the\n * cwd `.env` is loaded into `process.env`, so reading `MASTRA_PROJECT_ID` /\n * `MASTRA_CLOUD_ACCESS_TOKEN` would export Mastra Code's own traces into\n * whatever Mastra project the user happens to be working in (and crash on\n * project ids the exporter rejects).\n */\nexport function resolveCloudObservabilityConfig(\n settings: ReturnType<typeof loadSettings>,\n authStorage: AuthStorage,\n resourceId: string,\n env: NodeJS.ProcessEnv = process.env,\n): { accessToken: string; projectId?: string } | undefined {\n const resourceConfig = settings.observability.resources[resourceId];\n if (resourceConfig) {\n const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);\n if (token) {\n return { accessToken: token, projectId: resourceConfig.projectId };\n }\n }\n const accessToken = env.MASTRACODE_CLOUD_ACCESS_TOKEN?.trim();\n if (!accessToken) return undefined;\n return { accessToken, projectId: env.MASTRACODE_PROJECT_ID?.trim() || undefined };\n}\n\n/**\n * Base factory: builds every shared MastraCode resource (storage, observability,\n * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but\n * does NOT call `init()` or create a session. The controller is returned inert so\n * the composition layer can decide its Mastra ownership and session model.\n *\n * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).\n */\n/**\n * `instanceof` checks against Mastra classes are unreliable here: published\n * packages pin exact `@mastra/core` versions, so a user's dependency graph can\n * contain multiple copies of core (and peer-keyed copies of `@mastra/libsql` /\n * `@mastra/pg`). A store built against one copy fails `instanceof` against\n * another — the injected instance then silently fell through to the\n * StorageConfig path and crashed on `config.url`. These structural checks work\n * across duplicated copies.\n */\nfunction isInjectedStorageInstance(storage: MastraCodeConfig['storage']): storage is MastraCompositeStore {\n if (!storage) return false;\n if (storage instanceof MastraCompositeStore) return true;\n // A StorageConfig is a plain data object with a string `backend`\n // discriminant; a store instance carries the MastraCompositeStore method\n // surface.\n const candidate = storage as Partial<MastraCompositeStore>;\n return typeof candidate.init === 'function' && typeof candidate.__registerMastra === 'function';\n}\n\n/** Cross-copy-safe class check: walks the prototype chain by constructor name. */\nfunction hasAncestorClassNamed(value: object, className: string): boolean {\n for (let proto = Object.getPrototypeOf(value); proto; proto = Object.getPrototypeOf(proto)) {\n if (proto.constructor?.name === className) return true;\n }\n return false;\n}\n\nfunction resolveInjectedStorageBackend(\n storage: MastraCompositeStore,\n configuredBackend?: 'libsql' | 'pg',\n): 'libsql' | 'pg' {\n if (configuredBackend) return configuredBackend;\n if (storage instanceof LibSQLStore || hasAncestorClassNamed(storage, 'LibSQLStore')) return 'libsql';\n if (storage instanceof PostgresStore || hasAncestorClassNamed(storage, 'PostgresStore')) return 'pg';\n throw new Error('storageBackend is required when injecting a custom storage instance.');\n}\n\nexport async function createMastraCodeAgentController(config?: MastraCodeConfig) {\n const cwd = config?.cwd ?? process.cwd();\n const homeDir = config?.homeDir ?? config?.initialState?.homeDir;\n const configDir = config?.configDir ?? DEFAULT_CONFIG_DIR;\n // The single session for this process, assigned once `createSession()` runs\n // below. Config callbacks defined before then (e.g. notification stream\n // options) read it lazily through this holder.\n let activeSession: Session<MastraCodeState> | undefined;\n // Same trick for the controller, which plugins reach through a lazy accessor.\n // Plugins load well before the controller is constructed, and a closure over\n // the `controller` binding itself would throw on early access rather than\n // reporting \"not ready yet\", so the accessor reads this holder instead.\n let pluginRuntimeController: AgentController<MastraCodeState> | undefined;\n if (configDir !== DEFAULT_CONFIG_DIR) {\n validateConfigDirName(configDir);\n }\n\n // Load .env file from cwd if present (for observability API keys, etc.)\n try {\n process.loadEnvFile(path.join(cwd, '.env'));\n } catch {\n // No .env file — that's fine, keys may be in shell environment\n }\n\n // Auth storage (shared with Claude Max / OpenAI providers and AgentController)\n const authStorage = createAuthStorage();\n const globalSettings = loadSettings(config?.settingsPath);\n const backgroundToolsEnabled = globalSettings.backgroundTools?.enabled ?? false;\n const storedGatewayKey = authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER);\n const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;\n\n if (storedGatewayKey) {\n process.env['MASTRA_GATEWAY_API_KEY'] ??= storedGatewayKey;\n }\n\n if (storedGatewayUrl) {\n process.env['MASTRA_GATEWAY_URL'] ??= storedGatewayUrl;\n }\n\n // Load user-entered API keys from auth.json into process.env\n // (only sets env vars that aren't already present — env vars take precedence).\n // Skipped in deployed multi-tenant mode: when a per-tenant credential store\n // provider is registered, provider keys are resolved per request and must\n // never leak into process-global env vars.\n if (!hasCredentialStoreProvider()) {\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n const providerEnvVars: Record<string, string | undefined> = {};\n for (const [provider, cfg] of Object.entries(registry)) {\n const envVars = cfg?.apiKeyEnvVar;\n providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;\n }\n providerEnvVars[MASTRA_GATEWAY_PROVIDER] ??= 'MASTRA_GATEWAY_API_KEY';\n authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);\n } catch {\n // Registry unavailable — load well-known provider keys so non-gateway flows still work\n authStorage.loadStoredApiKeysIntoEnv({\n [MASTRA_GATEWAY_PROVIDER]: 'MASTRA_GATEWAY_API_KEY',\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_GENERATIVE_AI_API_KEY',\n cerebras: 'CEREBRAS_API_KEY',\n deepseek: 'DEEPSEEK_API_KEY',\n });\n }\n }\n\n const mgApiKey = process.env['MASTRA_GATEWAY_API_KEY'] ?? storedGatewayKey;\n const mastraGatewayBaseUrl = (\n process.env['MASTRA_GATEWAY_URL'] ??\n storedGatewayUrl ??\n 'https://gateway-api.mastra.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n const mastraCodeGateway = createMastraCodeGateway({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: false,\n settingsPath: config?.settingsPath,\n });\n const amazonBedrockGateway = createAmazonBedrockGateway();\n\n // Project detection\n const project = detectProject(cwd);\n\n const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);\n if (resourceIdOverride) {\n project.resourceId = resourceIdOverride;\n project.resourceIdOverride = true;\n }\n\n const cloudObservabilityConfig = resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId);\n\n // Stable session id unique to this project/resource, and a machine-bound owner\n // id. resourceId encodes root path + git identity and honors overrides, so it\n // is the right input for scoping the session to the cwd/project.\n const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;\n const ownerId = `mastracode-${shortHash(`${hostname()}\\0${project.rootPath}`)}`;\n\n const configuredPubSub = config?.pubsub;\n const useUnixSocketPubSub =\n (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== 'win32';\n const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : undefined);\n const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);\n if (crossProcessPubSub && !signalsPubSub) {\n throw new Error('crossProcessPubSub requires a pubsub instance');\n }\n // Cross-agent communication is experimental and opt-in. It gates the agent\n // connections provider/tools and the session thread-ownership lifecycle, but\n // never the PubSub transport itself.\n const useCrossAgentSignals =\n config?.crossAgentSignals ?? globalSettings.signals?.experimentalCrossAgentSignals ?? false;\n\n // Storage. An injected instance is used as-is — no connection test, no\n // LibSQL fallback: if the injected store fails, that's a hard error.\n const injectedStorage = isInjectedStorageInstance(config?.storage) ? config.storage : undefined;\n const storageConfig = injectedStorage\n ? undefined\n : ((config?.storage as StorageConfig | undefined) ??\n getStorageConfig(project.rootPath, globalSettings.storage, configDir));\n const storageResult: StorageResult = injectedStorage\n ? { storage: injectedStorage, backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend) }\n : await createStorage(storageConfig!);\n const storageWarning = storageResult.warning;\n\n // Observability storage (DuckDB — separate file for OLAP-style trace/score/feedback queries).\n // Local tracing is opt-in via `/observability local on`. When disabled, the\n // MastraStorageExporter is omitted entirely so traces never fall through to\n // the default libsql backend.\n let observabilityDomain: DuckDBStore['observability'] | undefined;\n let observabilityWarning: string | undefined;\n if (globalSettings.observability.localTracing) {\n try {\n const observabilityDuckDB = new DuckDBStore({\n id: 'mastra-code-observability',\n path: getObservabilityDatabasePath(),\n });\n // Force an early connection attempt so the lock error surfaces now, not mid-session.\n await observabilityDuckDB.db.getConnection();\n observabilityDomain = observabilityDuckDB.observability;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isLockError = /lock|locked|busy/i.test(message);\n if (isLockError) {\n observabilityWarning =\n 'Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.';\n } else {\n observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;\n }\n }\n }\n\n const harnessStorage = new InMemoryHarness();\n\n const storage = new MastraCompositeStore({\n id: 'mastra-code-storage',\n default: storageResult.storage,\n domains: {\n // When local tracing is off, disable the observability domain entirely so\n // trace/score/feedback writes never fall through to the default libsql store.\n observability: observabilityDomain ?? false,\n harness: harnessStorage,\n },\n });\n\n // Observability (tracing, scoring, feedback)\n const observability = new Observability({\n configs: {\n default: {\n serviceName: 'mastracode',\n // Only these requestContext keys are stored on spans — prevents leaking\n // large objects (controller state, workspace, env vars) into trace data.\n // Use dot-notation because these are nested inside the 'controller' key.\n //\n // Session identifiers:\n // threadId, resourceId, session.modeId, agentControllerId\n // Environment & project:\n // state.projectName, state.gitBranch\n // Model configuration:\n // session.modelId, state.subagentModelId\n // Agent settings:\n // state.yolo, state.thinkingLevel, state.smartEditing\n // Observational memory settings:\n // state.omScope, state.observerModelId, state.reflectorModelId,\n // state.observationThreshold, state.reflectionThreshold\n requestContextKeys: [\n // Session identifiers\n 'controller.threadId',\n 'controller.resourceId',\n 'controller.session.modeId',\n 'controller.controllerId',\n // Environment & project\n 'controller.state.projectName',\n 'controller.state.gitBranch',\n // Model configuration\n 'controller.session.modelId',\n 'controller.state.subagentModelId',\n // Agent settings\n 'controller.state.yolo',\n 'controller.state.thinkingLevel',\n 'controller.state.smartEditing',\n // Observational memory settings\n 'controller.state.omScope',\n 'controller.state.observerModelId',\n 'controller.state.reflectorModelId',\n 'controller.state.observationThreshold',\n 'controller.state.reflectionThreshold',\n ],\n exporters: [\n // Only persist traces locally when DuckDB observability is available\n // (via `/observability local on`). Without this guard the storage\n // exporter falls through to the default libsql backend and silently\n // fills the main database with gigabytes of span data.\n ...(observabilityDomain ? [new MastraStorageExporter({ strategy: 'event-sourced' })] : []),\n // Credentials are always passed explicitly; `resolveFromEnv: false`\n // stops the exporter from picking up the cwd project's MASTRA_* vars.\n new MastraPlatformExporter({ ...cloudObservabilityConfig, resolveFromEnv: false }),\n ],\n spanOutputProcessors: [new SensitiveDataFilter()],\n },\n },\n });\n\n // Vector store for recall search (separate DB file to avoid bloating main\n // storage). An injected instance is used as-is; with an injected storage\n // instance and no injected vector, recall search stays vector-less.\n const vector =\n config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : undefined);\n\n // Maintenance handle for /prune: prunes via the inner store (whose retention\n // config covers every domain, including legacy libsql observability spans)\n // and can compact local libsql files to reclaim disk. The vector store's\n // connection must close alongside storage — the compaction's file swap\n // refuses to run while any connection is open.\n const storageMaintenance: StorageMaintenance = createStorageMaintenance({\n storage: storageResult.storage,\n backend: storageResult.backend,\n retention: DEFAULT_RETENTION,\n localDbFiles: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],\n closeVector: vector instanceof LibSQLVector ? () => vector.close() : undefined,\n });\n\n const memory =\n config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vector, config?.settingsPath));\n // Only the default memory wiring registers the subconscious tools; a\n // caller-supplied memory is opaque here, so its prompt must not advertise them.\n const hasSubconscious =\n config?.memory === undefined ? (state: MastraCodeState | undefined) => hasSubconsciousTools(vector, state) : false;\n\n // MCP\n const mcpManager = config?.disableMcp\n ? undefined\n : createMcpManager(project.rootPath, configDir, config?.mcpServers, globalSettings.mcp);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(\n project.rootPath,\n 'session-init',\n configDir,\n homeDir,\n project.isWorktree\n ? { path: project.rootPath, branch: project.gitBranch, mainRepoPath: project.mainRepoPath }\n : undefined,\n );\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ??\n new PluginManager({\n projectRoot: project.rootPath,\n configDir,\n homeDir,\n }));\n // Publish the runtime accessors to whichever manager is in play — including an\n // injected one, which would otherwise hand plugins `undefined` for\n // `getController`/`getActiveSession`. Lazy closures: both locals are assigned\n // after the controller is constructed below.\n pluginManager?.setRuntime({\n getController: () => pluginRuntimeController,\n getActiveSession: () => activeSession,\n getStorage: () => ({ storage, storageBackend: storageResult.backend, vector }),\n });\n const loadedPlugins = pluginManager ? await pluginManager.reload() : [];\n const pluginTools = pluginManager?.getPluginTools() ?? {};\n\n // Scorers (live evaluation with sampling)\n const outcomeScorer = createOutcomeScorer();\n const efficiencyScorer = createEfficiencyScorer();\n\n // Agent — githubSignals is created before `controller` but the closure below\n // captures `controller` by reference; it is only invoked at notification time,\n // well after controller is constructed (line ~692). Explicit type annotations\n // on githubSignals, codeAgent, modes, and controller break the circular\n // inference chain this forward reference would otherwise create.\n // Builds the stream options of every wake (a run with no inbound request).\n // Shared by GithubSignals (immediate sends) and the code agent's\n // notification delivery policy (notifications and cross-agent signals,\n // including deferred sends re-dispatched by the core notification dispatch\n // workflow) — all need the target session's request context, or a woken idle\n // thread has no model to run with (\"No model selected\"). New wake paths must\n // build their options here so `prepareWakeRequestContext` runs for them.\n const getWakeStreamOptions = async ({ resourceId, threadId }: { resourceId: string; threadId: string }) => {\n // Run the woken notification as the session that owns the target\n // resource so it uses that session's model/mode/state. Fall back to\n // the current session only when no session owns the resource yet.\n const owningSession = await controller.getSessionByResource(resourceId);\n const session = owningSession ?? activeSession;\n // No session owns the resource and none is active yet (e.g. a deferred\n // notification comes due before any session boots). Nothing to resolve a\n // model from; return undefined so the dispatcher sends a bare wake\n // instead of throwing mid-delivery.\n if (!session) return undefined;\n // A long-running system must be able to drive work unattended, so a\n // target session without an explicit model selection falls back to a\n // real model rather than failing the run: the current session's live\n // selection (what the user actually picked), then the mode's default.\n const targetThread = await session.thread.getById({ threadId });\n const metadata =\n targetThread?.resourceId === resourceId\n ? (targetThread.metadata as Record<string, unknown> | undefined)\n : undefined;\n const modes = controller.listModes();\n const savedModeId = metadata?.currentModeId;\n const defaultMode = modes.find(mode => mode.default) ?? modes[0];\n const modeId =\n typeof savedModeId === 'string' && modes.some(mode => mode.id === savedModeId)\n ? savedModeId\n : (defaultMode?.id ?? session.mode.get());\n const savedModeModelId = metadata?.[`modeModelId_${modeId}`];\n const legacyModelId = metadata?.currentModelId;\n const defaultModeModelId = modes.find(mode => mode.id === modeId)?.defaultModelId;\n const modelId =\n (typeof savedModeModelId === 'string' ? savedModeModelId : undefined) ??\n (typeof legacyModelId === 'string' ? legacyModelId : undefined) ??\n defaultModeModelId ??\n session.model.get() ??\n '';\n const baseState = { ...session.state.get() } as MastraCodeState;\n delete baseState.activeModelPackId;\n delete baseState.mastracodePendingPackFallback;\n const persistedSandboxPaths = metadata?.sandboxAllowedPaths;\n baseState.sandboxAllowedPaths =\n Array.isArray(persistedSandboxPaths) && persistedSandboxPaths.every(path => typeof path === 'string')\n ? persistedSandboxPaths\n : [];\n const persistedStateKeys = [\n 'thinkingLevel',\n 'notifications',\n THREAD_ACTIVE_MODEL_PACK_ID_KEY,\n PACK_FALLBACK_STATE_KEY,\n ] as const;\n for (const key of persistedStateKeys) {\n const value = metadata?.[key];\n if (value !== undefined) (baseState as Record<string, unknown>)[key] = value;\n }\n let notificationState = baseState;\n const getNotificationState = () => ({ ...notificationState });\n const setNotificationState = async (updates: Partial<MastraCodeState>) => {\n notificationState = { ...notificationState, ...updates };\n if (session.thread.getId() === threadId) await session.state.set(updates);\n };\n const updateNotificationState: NonNullable<AgentControllerRequestContext['updateState']> = async updater => {\n const update = await updater(getNotificationState());\n if (update.updates) await setNotificationState(update.updates);\n for (const event of update.events ?? []) {\n if (session.thread.getId() === threadId) session.emit(event);\n }\n return update.result;\n };\n const requestContext = new RequestContext();\n const agentControllerContext: AgentControllerRequestContext = {\n controllerId: controller.id,\n state: getNotificationState(),\n getState: getNotificationState,\n setState: setNotificationState,\n updateState: updateNotificationState,\n getThreadSetting: key => session.thread.getSettingOn({ threadId, key }),\n setThreadSetting: setting => session.thread.setSettingOn({ threadId, key: setting.key, value: setting.value }),\n isThreadActive: () => session.thread.getId() === threadId,\n threadId,\n resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId,\n state: {\n get: getNotificationState,\n set: setNotificationState,\n update: updateNotificationState,\n },\n },\n workspace: session.getWorkspace(),\n emitEvent: event => {\n if (session.thread.getId() === threadId) session.emit(event);\n },\n getSubagentModelId: params => {\n const agentType = params?.agentType;\n const perType = agentType ? metadata?.[`subagentModelId_${agentType}`] : undefined;\n const global = metadata?.subagentModelId;\n if (typeof perType === 'string') return perType;\n if (typeof global === 'string') return global;\n return session.thread.getId() === threadId ? session.subagents.model.get(params ?? {}) : null;\n },\n };\n requestContext.set('controller', agentControllerContext);\n // Tenant identity/credentials must come from the session that owns the\n // resource; the active-session fallback is only safe for model selection.\n if (owningSession) {\n await config?.prepareWakeRequestContext?.({ requestContext, resourceId, threadId });\n }\n\n return {\n memory: { thread: threadId, resource: resourceId },\n requestContext,\n maxSteps: 1000,\n savePerStep: false,\n requireToolApproval: notificationState.yolo !== true,\n modelSettings: { temperature: 1 },\n };\n };\n\n const githubSignals: GithubSignals | undefined =\n globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals\n ? new GithubSignals({\n cwd: project.rootPath,\n pollIntervalMs: globalSettings.signals.githubPollIntervalMs,\n gitcrawlCommand:\n process.env.MASTRACODE_GITCRAWL_BIN ??\n process.env.GITCRAWL_BIN ??\n process.env.MASTRACODE_GITCRAWL_COMMAND ??\n process.env.GITCRAWL_COMMAND,\n getNotificationStreamOptions: getWakeStreamOptions,\n })\n : undefined;\n // Mastra Code's own processors are constructed once, here, rather than inside\n // the resolver below: the resolver runs before every LLM call, and rebuilding\n // stateful processors per request would reset them.\n const mastraCodeInputProcessors: InputProcessor[] = [\n ...(config?.inputProcessors ?? []),\n new PlanRejectionAbortProcessor(),\n ...(backgroundToolsEnabled ? [createBackgroundWorkSignalProcessor()] : []),\n new AgentsMDInjector({\n // Untrusted checkouts (review sessions on PR branches) must not have\n // the working tree's instruction files injected as system reminders —\n // those files are attacker-writable content, not configuration. When\n // the session carries a trusted base ref, reminders are served from\n // that ref instead (see getReader); without one they are disabled.\n isEnabled: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n return state?.untrustedCheckout !== true || typeof state?.baseRef === 'string';\n },\n // Resolve relative tool paths against the session checkout (not the host\n // process cwd) and never surface instruction files from outside it.\n getBasePath: ({ requestContext }) => getInjectorSessionState(requestContext)?.projectPath ?? project.rootPath,\n getReader: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n if (state?.untrustedCheckout !== true || typeof state?.baseRef !== 'string') return undefined;\n return createGitRefReminderReader(state?.projectPath ?? project.rootPath, state.baseRef);\n },\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n const projectPath = state?.projectPath ?? project.rootPath;\n // On untrusted checkouts the static prompt loads from the base ref,\n // so compute the statically-loaded paths through the same reader to\n // keep the dedup consistent.\n const projectReader =\n state?.untrustedCheckout === true && typeof state?.baseRef === 'string'\n ? createGitRefInstructionReader(projectPath, state.baseRef)\n : undefined;\n return getStaticallyLoadedInstructionPaths(projectPath, undefined, projectReader);\n },\n }),\n new ProviderHistoryCompat(),\n ];\n\n // Built-in providers are named so the plugin lane can reserve their ids.\n const taskSignalProvider = new TaskSignalProvider();\n const agentConnectionsSignalProvider = useCrossAgentSignals\n ? new AgentConnectionsSignalProvider(config?.agentConnections)\n : undefined;\n\n const NO_PLUGIN_PROCESSORS: PluginProcessorEntries = { input: [], output: [] };\n let pluginProcessorReadWarned = false;\n\n // Providers contributed by plugins are driven from here rather than through\n // the agent's `signals` array: the Agent constructor harvests a provider's\n // processors into a closure it can never undo, so a provider wired there\n // could not be removed when its plugin is disabled, updated or uninstalled.\n // The built-in providers are seeded as reserved ids because they are wired\n // through the constructor and are therefore invisible to the lane.\n const pluginSignalLane = pluginManager\n ? new PluginSignalLane({\n reservedProviderIds: [\n taskSignalProvider.id,\n ...(agentConnectionsSignalProvider ? [agentConnectionsSignalProvider.id] : []),\n ...(githubSignals ? [githubSignals.id] : []),\n ],\n })\n : undefined;\n let unsubscribePluginReload: (() => void) | undefined;\n\n /**\n * Plugin processors are read through a function so that enabling, disabling or\n * updating a plugin takes effect on the next request rather than requiring a\n * new agent. This runs before every LLM call, and also outside the request\n * path when the Agent catalogues its configured processors — where a throw is\n * swallowed into a debug log. So it only reads already-resolved state: no\n * filesystem, no network, no construction, and it never throws.\n */\n const readPluginProcessors = (): PluginProcessorEntries => {\n try {\n return pluginManager?.getPluginProcessors() ?? NO_PLUGIN_PROCESSORS;\n } catch (error) {\n // Warn once: this is on the hot path, and a broken read repeats.\n if (!pluginProcessorReadWarned) {\n pluginProcessorReadWarned = true;\n console.warn('Failed to read plugin processors:', error);\n }\n return NO_PLUGIN_PROCESSORS;\n }\n };\n\n const codeAgent: Agent = createCodingAgent({\n id: CODE_AGENT_ID,\n name: 'Code Agent',\n // Workspace is wired per-request at the AgentController level (see\n // `config.workspace` below), so opt out of the factory's default local\n // workspace. An explicit `undefined` is required: the factory only builds a\n // default when the `workspace` key is absent.\n workspace: undefined,\n instructions: async ({ requestContext }) => {\n const configured = config?.hostInstructions;\n const hostInstructions = typeof configured === 'function' ? await configured({ requestContext }) : configured;\n return getDynamicInstructions({\n requestContext,\n hostInstructions,\n coAuthor: config?.coAuthor,\n hasSubconscious,\n hasSubagents: subagents.length > 0,\n });\n },\n // `settingsPath` matches the source `createMastraCode()` reads from so the\n // per-mode thinking defaults resolve against the same config file.\n model: ctx => getDynamicModel(ctx, config?.settingsPath),\n // Deferred notifications are re-dispatched by the core notification\n // dispatch workflow long after the originating send; the delivery policy\n // rebuilds the request context (model selection included) at delivery time\n // so waking an idle thread does not fail with \"No model selected\". The\n // default decision logic is kept as-is — the policy only attaches\n // streamOptions on top of it.\n notifications: {\n deliveryPolicy: {\n decide: async input => {\n const decision = defaultNotificationDeliveryDecision(input);\n // Without a resourceId there is no session to resolve options from —\n // don't fall through to the active session and wake it under an\n // empty resource binding.\n if (!input.record.resourceId) return decision;\n const streamOptions = await getWakeStreamOptions({\n resourceId: input.record.resourceId,\n threadId: input.record.threadId,\n });\n return streamOptions ? { ...decision, streamOptions } : decision;\n },\n },\n },\n tools: createDynamicTools(\n mcpManager,\n config?.extraTools,\n config?.disabledTools,\n storage,\n pluginTools,\n backgroundToolsEnabled,\n ),\n hooks: createToolHooks(hookManager, config?.postToolObserver),\n scorers: {\n outcome: {\n scorer: outcomeScorer,\n sampling: { type: 'none' },\n },\n efficiency: {\n scorer: efficiencyScorer,\n sampling: { type: 'ratio', rate: 0.3 },\n },\n },\n // TaskSignalProvider bundles the task tools + TaskStateProcessor: it merges\n // the tools into the toolset and registers the task state-signal processor,\n // so the task list persists across turns and survives OM truncation.\n signals: [\n taskSignalProvider,\n ...(agentConnectionsSignalProvider ? [agentConnectionsSignalProvider] : []),\n ...(githubSignals ? [githubSignals] : []),\n ],\n // Native goal mechanism: the in-loop goal step judges the thread's active\n // objective each qualifying iteration. The judge model is required for any\n // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires\n // the GoalStateProcessor so the `<current-objective>` signal persists across\n // turns. Per-thread overrides live in the ThreadState `goal` record and win\n // over these defaults.\n goal: {\n // Resolve the judge model through mastracode's gateway (a model-resolver\n // function) so provider credentials are injected; returns undefined when no\n // judge model is configured, keeping the goal step a no-op. Bind the same\n // `settingsPath` used above so the judge model and `maxRuns` come from one\n // config (a custom settings file would otherwise diverge).\n judge: ctx => getGoalJudgeModel(ctx, config?.settingsPath),\n maxRuns: globalSettings.models.goalMaxTurns ?? 50,\n maxSteps: 1000,\n prompt: DEFAULT_GOAL_JUDGE_PROMPT,\n // Read-only workspace tools the default goal judge may call to verify the\n // agent's work against the actual filesystem (view, search_content,\n // find_files, file_stat, lsp_inspect) rather than grading prose alone —\n // restoring the original MastraCode judge's verification ability. Resolved\n // per-request from the active workspace (mirrors `judge`).\n tools: getGoalJudgeTools,\n },\n inputProcessors: () => [\n ...mastraCodeInputProcessors,\n // Input-lane notice ONLY (no processAPIError — see the class doc): the\n // runner walks input processors first in runProcessAPIError, so an\n // input-lane processAPIError would rotate before transient retries run.\n new AccountStartNoticeProcessor({ credentialStore: authStorage, settingsPath: config?.settingsPath }),\n ...readPluginProcessors().input.map(entry => entry.value),\n ...(pluginSignalLane?.getInputProcessors() ?? []),\n ],\n // Mastra Code contributes no output processors of its own; the lane exists\n // so plugins can. Like the input lane, plugin processors sit last — after\n // the layers they customize, before the channel and memory layers the\n // Agent appends.\n outputProcessors: () => [\n ...readPluginProcessors().output.map(entry => entry.value),\n ...(pluginSignalLane?.getOutputProcessors() ?? []),\n ],\n errorProcessors: [\n // ProviderHistoryCompat must run before StreamErrorRetryProcessor: both react to\n // HTTP 400s, but ProviderHistoryCompat repairs the incompatible history (e.g.\n // sanitizing tool-call IDs) before retrying, while StreamErrorRetryProcessor's\n // isBadRequestError matcher retries the identical request. Error processors\n // short-circuit on the first `retry: true`, so a blind retry first would resend\n // the broken history and fail again.\n new ProviderHistoryCompat(),\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isTransientConnectionError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n {\n match: isTransientServerError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n ],\n }),\n new PrefillErrorHandler(),\n // Rotation runs last in the error lane: a transient error reaching here\n // means StreamErrorRetryProcessor already spent its budget, which is the\n // hop condition; quota/auth errors were never transient-matched and\n // rotate immediately.\n new AccountRotationProcessor({\n credentialStore: authStorage,\n // Same budget core enforces (maxProcessorRetries below): past it, core\n // discards retry:true, so the processor no-ops instead of rotating.\n maxProcessorRetries: MASTRACODE_MAX_PROCESSOR_RETRIES,\n // Same settings file getDynamicModel reads (model: above) so the pack\n // cascade the processor announces matches the chain core will walk.\n settingsPath: config?.settingsPath,\n }),\n ],\n // Individual processors have tighter limits; this remains a defensive\n // ceiling for custom/plugin processors that might retry indefinitely.\n maxProcessorRetries: MASTRACODE_MAX_PROCESSOR_RETRIES,\n });\n\n // const defaultSubAgents: Array<AgentControllerSubagent> = [];\n // const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];\n\n const defaultModes: AgentControllerMode[] = [\n {\n ...buildMode,\n metadata: {\n ...buildMode.metadata,\n color: mastraBrand.green,\n },\n },\n {\n ...planMode,\n metadata: {\n ...planMode.metadata,\n color: mastraBrand.purple,\n },\n },\n {\n ...fastMode,\n metadata: {\n ...fastMode.metadata,\n color: mastraBrand.orange,\n },\n },\n ];\n\n const defaultIntervalHandlers: IntervalHandler[] = [\n {\n id: 'gateway-sync',\n intervalMs: 5 * 60 * 1000,\n immediate: false,\n handler: () => syncGateways(),\n },\n ];\n const intervalHandlers = config?.intervalHandlers ?? defaultIntervalHandlers;\n\n // Build lightweight provider access for resolving built-in packs at startup.\n // Anthropic/OpenAI use AuthStorage; other providers use env API keys.\n // Also scan the full provider registry so configured API keys satisfy access checks.\n const anthropicCred = authStorage.get('anthropic');\n const openaiCred = authStorage.get('openai-codex');\n const githubCopilotCred = authStorage.get('github-copilot');\n const kimiCodingCred = authStorage.get('kimi-for-coding');\n const startupAccess: ProviderAccess = {\n anthropic:\n anthropicCred?.type === 'oauth'\n ? 'oauth'\n : anthropicCred?.type === 'api_key' && anthropicCred.key.trim().length > 0\n ? 'apikey'\n : false,\n openai:\n openaiCred?.type === 'oauth'\n ? 'oauth'\n : openaiCred?.type === 'api_key' && openaiCred.key.trim().length > 0\n ? 'apikey'\n : false,\n cerebras: process.env.CEREBRAS_API_KEY ? 'apikey' : false,\n google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? 'apikey' : false,\n deepseek: process.env.DEEPSEEK_API_KEY ? 'apikey' : false,\n 'github-copilot': githubCopilotCred?.type === 'oauth' ? 'oauth' : false,\n 'kimi-for-coding':\n kimiCodingCred?.type === 'oauth' && isKimiCodingDeviceId(kimiCodingCred.deviceId)\n ? 'oauth'\n : (kimiCodingCred?.type === 'api_key' && kimiCodingCred.key.trim().length > 0) ||\n Boolean(process.env.KIMI_API_KEY?.trim())\n ? 'apikey'\n : false,\n };\n // Gateway covers all providers — ensure Anthropic/OpenAI packs are visible\n if (mgApiKey) {\n if (!startupAccess.anthropic) startupAccess.anthropic = 'apikey';\n if (!startupAccess.openai) startupAccess.openai = 'apikey';\n }\n // Check all providers in the registry for API keys\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n for (const [provider, config] of Object.entries(registry)) {\n if (startupAccess[provider] === 'oauth' || startupAccess[provider] === 'apikey') continue; // Already enabled above\n if (provider === 'anthropic' || provider === 'openai') continue;\n const envVars = config?.apiKeyEnvVar;\n const envVarList = Array.isArray(envVars) ? envVars : envVars ? [envVars] : [];\n if (envVarList.some(envVar => process.env[envVar])) {\n startupAccess[provider] = 'apikey';\n }\n }\n } catch {\n // Registry may not be loaded yet; the 5 hardcoded providers are sufficient fallback\n }\n const builtinPacks = getAvailableModePacks(startupAccess);\n const builtinOmPacks = getAvailableOmPacks(startupAccess);\n const effectiveDefaults = resolveModelDefaults(globalSettings, builtinPacks);\n const activeProviderId = effectiveDefaults.build?.split('/')[0];\n const preferredOmModel = hasExplicitOMConfiguration(globalSettings)\n ? undefined\n : selectPreferredOMPack(startupAccess, activeProviderId)?.modelId;\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks) || preferredOmModel;\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks) || preferredOmModel;\n const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? undefined;\n const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? undefined;\n const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? undefined;\n const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? 'auto';\n\n const modes = addPluginToolsToModeAllowlists(\n applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults),\n Object.keys(pluginTools),\n );\n const defaultModeId =\n modes.find(mode => mode.metadata?.default === true)?.id ??\n modes.find(mode => mode.id === 'build')?.id ??\n modes[0]?.id;\n if (!defaultModeId) {\n throw new Error('MastraCode requires at least one mode');\n }\n\n const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n const disabledTools = new Set(config?.disabledTools);\n const subagents = (config?.subagents ?? [exploreSubagent, planSubagent, executeSubagent]).map(definition => ({\n ...definition,\n ...(config?.subagents == null && {\n defaultModelId:\n modes.find(mode => mode.id === subagentModeMap[definition.id])?.defaultModelId ??\n modes.find(mode => mode.id === defaultModeId)?.defaultModelId,\n }),\n allowedControllerTools: definition.allowedControllerTools?.filter(name => !disabledTools.has(name)),\n allowedWorkspaceTools: definition.allowedWorkspaceTools?.filter(name => !disabledTools.has(name)),\n ...(definition.tools && {\n tools: Object.fromEntries(Object.entries(definition.tools).filter(([name]) => !disabledTools.has(name))),\n }),\n }));\n\n // Build initial state with global preferences. OM knobs are skipped when the\n // host persists memory settings elsewhere (`disableSettingsOmSeed`) so the\n // machine-local settings.json never leaks into server sessions.\n const globalInitialState: Partial<MastraCodeState> = {};\n if (!config?.disableSettingsOmSeed) {\n if (effectiveObserverModel) {\n globalInitialState.observerModelId = effectiveObserverModel;\n }\n if (effectiveReflectorModel) {\n globalInitialState.reflectorModelId = effectiveReflectorModel;\n }\n if (effectiveObservationThreshold !== undefined) {\n globalInitialState.observationThreshold = effectiveObservationThreshold;\n }\n if (effectiveReflectionThreshold !== undefined) {\n globalInitialState.reflectionThreshold = effectiveReflectionThreshold;\n }\n if (effectiveCavemanObservations !== undefined) {\n globalInitialState.cavemanObservations = effectiveCavemanObservations;\n }\n if (effectiveObserveAttachments !== undefined) {\n globalInitialState.observeAttachments = effectiveObserveAttachments;\n }\n }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n // Note: `thinkingLevel` is intentionally NOT seeded into session state. The\n // state slot is a session-level override; the effective level is resolved at\n // request time (per-mode defaults → global preference) in getDynamicModel so\n // settings changes apply to the next request of every session.\n if (config?.omScope) {\n globalInitialState.omScope = config.omScope;\n }\n // Seed subagent models from global settings\n for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) {\n if (key === 'default' || key === '_default') {\n globalInitialState.subagentModelId = modelId;\n } else {\n globalInitialState[`subagentModelId_${key}`] = modelId;\n }\n }\n\n const typedStateSchema = stateSchema as PublicSchema<MastraCodeState>;\n const backgroundCompletionEvents = backgroundToolsEnabled ? createBackgroundCompletionEvents() : undefined;\n let controller: AgentController<MastraCodeState>;\n controller = new AgentController<MastraCodeState>({\n id: 'mastra-code',\n resourceId: project.resourceId,\n storage,\n ...(backgroundToolsEnabled\n ? {\n backgroundTasks: {\n enabled: true,\n recoverStaleTasksOnStart: false,\n ...createBackgroundCompletionCallbacks(() => controller, backgroundCompletionEvents),\n },\n }\n : {}),\n observability,\n memory,\n pubsub: signalsPubSub,\n stateSchema: typedStateSchema,\n agent: codeAgent,\n subagents,\n gateways: [amazonBedrockGateway, mastraCodeGateway],\n workspace: config?.workspace ?? (args => getDynamicWorkspace({ ...args, backgroundToolsEnabled })),\n browser: config?.browser,\n idGenerator: config?.idGenerator,\n toolCategoryResolver: getToolCategory,\n initialState: {\n projectPath: project.rootPath,\n projectName: project.name,\n gitBranch: project.gitBranch,\n pluginSkillPaths: loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : [])),\n pluginCommandPaths: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' ? (plugin.commandPaths ?? []) : [],\n ),\n pluginInstructions: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n ),\n yolo: true,\n ...globalInitialState,\n ...config?.initialState,\n // configDir must always win over initialState spreads to stay in sync\n // with MCP/hooks/storage which were already initialized with this value.\n configDir,\n },\n modes,\n intervalHandlers,\n modelUseCountProvider: () => loadSettings().modelUseCounts,\n modelUseCountTracker: modelId => {\n try {\n const settings = loadSettings();\n settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;\n saveSettings(settings);\n } catch (error) {\n console.error('Failed to persist model usage count', error);\n }\n },\n threadLock: crossProcessPubSub\n ? undefined\n : {\n acquire: acquireThreadLock,\n release: releaseThreadLock,\n },\n });\n\n const sessionPeerCleanup = new WeakMap<Session<MastraCodeState>, () => void>();\n // Thread ownership advertisement is part of experimental cross-agent\n // communication: without it, sessions never claim or advertise their thread to\n // peers. Every thread a session has loaded stays claimed (see\n // `createSessionThreadAdvertisement`) so peers that saved it stay connected\n // after the user moves to another thread.\n if (useCrossAgentSignals) {\n controller.onSessionCreated(\n async session => {\n const advertisement = createSessionThreadAdvertisement({\n session,\n controller,\n projectName: project.name,\n });\n sessionPeerCleanup.set(session, () => advertisement.close());\n const initialThreadId = session.thread.getId();\n if (initialThreadId) {\n // This listener blocks session creation, so bound the initial claim:\n // an unsettled PubSub subscription must not hang createSession().\n // The claim keeps settling in the background either way.\n await Promise.race([\n advertisement.claim(initialThreadId),\n new Promise<void>(resolve => {\n const timer = setTimeout(resolve, 5_000);\n timer.unref?.();\n }),\n ]);\n }\n },\n { blocking: true },\n );\n controller.onSessionDeleted(session => {\n sessionPeerCleanup.get(session)?.();\n sessionPeerCleanup.delete(session);\n });\n }\n\n // Publish the controller to the plugin runtime accessors now that it exists.\n pluginRuntimeController = controller;\n\n if (pluginSignalLane && pluginManager) {\n // Register the plugins loaded at startup, and re-reconcile on every reload.\n // Providers are not started here: they need a Mastra instance for storage,\n // and Mastra does not exist until the composition layer boots the controller\n // (see `startPluginSignalProviders` on the returned object).\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders());\n unsubscribePluginReload = pluginManager.onReload(() =>\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders()),\n );\n }\n\n // The AgentController is fully constructed but intentionally NOT inited here. Init and\n // session creation are deferred to the composition layer (see below) so the\n // controller can be wired in three ways:\n //\n // 1. Server + Web — registered on a server Mastra, then inited; sessions\n // minted per browser client over HTTP.\n // 2. Server + TUI — same server composition; the TUI drives a session\n // (in-process today; remote transport is future work).\n // 3. Local + TUI — controller builds its own internal Mastra on init() and\n // mints one eager session for the whole process.\n //\n // Cases 1 & 2 use `mountAgentControllerOnMastra` (register-before-init, no eager\n // session). Case 3 uses `bootLocalAgentController` (init + one wired session).\n return {\n controller: controller,\n storage,\n storageMaintenance,\n createKnowledgeInspector: (session: Session<MastraCodeState>) =>\n createScopedKnowledgeInspector({ storage, session }),\n observability,\n memory,\n mcpManager,\n hookManager,\n pluginManager,\n loadedPlugins,\n pluginTools,\n signalsPubSub,\n authStorage,\n resolveModel,\n storageWarning,\n observabilityWarning,\n builtinPacks,\n builtinOmPacks,\n effectiveDefaults,\n githubSignals,\n backgroundToolsEnabled,\n backgroundCompletionEvents,\n // Identity for the single local session (Case 3). Servers ignore these and\n // mint per-request sessions with client-supplied resourceIds instead.\n sessionId,\n ownerId,\n // Surface the project root so boot/mount paths can wire workflow tools\n // against a workspace anchored at it without re-running detectProject().\n projectPath: project.rootPath,\n // Surface the Agent instance so registerWorkflowBuilderPrimitives can add\n // it as a plain agent on the Mastra registry. Workflows then compose it\n // as an agent step (agentId: 'code-agent') and delegate open-ended tool\n // orchestration to it — code-agent already has full workspace / MCP / web\n // access via its dynamic tool factory.\n codeAgent,\n // Lets the composition layer publish the created session back into the\n // config closures (e.g. notification stream options read it lazily).\n setActiveSession: (session: Session<MastraCodeState>) => {\n activeSession = session;\n },\n /**\n * Starts the signal providers contributed by plugins. Called by the\n * composition layer once the controller is inited, because that is when a\n * Mastra instance exists — a provider without one has no storage, and\n * nothing else will hand it one: the Agent propagates Mastra only to the\n * providers in its own `signals` array, which these deliberately are not in.\n */\n startPluginSignalProviders: () => {\n const mastra = controller.getMastra();\n if (!pluginSignalLane || !mastra) return;\n pluginSignalLane.setMastra(mastra, codeAgent);\n },\n /**\n * Stops every plugin-contributed signal provider and stops listening for\n * plugin reloads. The inverse of `startPluginSignalProviders`, for an\n * embedder that is done with this controller: a `pluginManager` shared\n * across controllers (`MastraCodeConfig.pluginManager`) outlives any one of\n * them, so without this its providers keep polling and its reload listener\n * keeps firing for a controller that is gone.\n */\n stopPluginSignalProviders: () => {\n unsubscribePluginReload?.();\n unsubscribePluginReload = undefined;\n pluginSignalLane?.stopAll();\n },\n /**\n * Hands Mastra to the statically configured input processors.\n *\n * The Agent does this itself, but only for processors configured as a\n * plain array (`Array.isArray` in `__registerMastra`). This lane is a\n * function so plugins can contribute to it, which takes those processors\n * out of that branch — including any an embedder passed as\n * `config.inputProcessors`, some of which need Mastra to work at all\n * (`CostGuardProcessor` reads observability storage there). Doing it here\n * keeps that unchanged.\n *\n * Plugin processors are deliberately not included: they come and go with\n * their plugin, and the registry keeps the first instance registered under\n * an id forever, which would leave a retired instance behind. Plugins\n * reach Mastra through `getController()` on the plugin context instead.\n */\n registerConfiguredProcessorsWithMastra: () => {\n const mastra = controller.getMastra();\n if (!mastra) return;\n for (const processor of mastraCodeInputProcessors) {\n mastra.addProcessor(processor as Processor);\n mastra.addProcessorConfiguration(processor as Processor, CODE_AGENT_ID, 'input');\n }\n },\n };\n}\n\n/**\n * Result of {@link createMastraCodeAgentController}: every shared resource plus the\n * inert AgentController, ready to be either booted locally or mounted on a server\n * Mastra.\n */\nexport type MastraCodeAgentController = Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n\n/**\n * Wires the session-scoped concerns MastraCode layers on top of a Session:\n * hookManager thread-id sync, GitHub PR polling for the current thread, and\n * per-thread persistence of the mastracode-only `/om` settings.\n *\n * Used by {@link bootLocalAgentController} for the single local session. A server can\n * call this for any session it mints if it wants the same background wiring.\n */\nexport async function wireSessionConcerns(\n base: Pick<MastraCodeAgentController, 'hookManager' | 'githubSignals' | 'setActiveSession'>,\n session: Session<MastraCodeState>,\n): Promise<void> {\n const { hookManager, githubSignals } = base;\n base.setActiveSession(session);\n\n // Sync hookManager session ID on thread changes\n if (hookManager) {\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') {\n hookManager.setSessionId(event.threadId);\n } else if (event.type === 'thread_created') {\n hookManager.setSessionId(event.thread.id);\n }\n });\n }\n\n if (githubSignals) {\n const startGithubPollingForCurrentThread = async (threadId?: string | null) => {\n if (!threadId) return;\n githubSignals.stopAllPolling();\n try {\n const threads = await session.thread.list({ allResources: true });\n const thread = threads.find((item: { id: string }) => item.id === threadId);\n await githubSignals.startPollingForThread(\n {\n threadId,\n resourceId: thread?.resourceId ?? session.identity.getResourceId(),\n },\n { pollImmediately: true },\n );\n } catch (error) {\n console.warn('Failed to start GitHub PR polling:', error);\n }\n };\n\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') void startGithubPollingForCurrentThread(event.threadId);\n else if (event.type === 'thread_created') void startGithubPollingForCurrentThread(event.thread.id);\n });\n void startGithubPollingForCurrentThread(session.thread.getId());\n }\n\n // Persist MastraCode-owned /om settings per-thread (mastracode-only concern;\n // intentionally not in core's controller loadThreadMetadata).\n const omThreadStateSession = session as unknown as Session<Record<string, unknown>>;\n attachOMThreadStatePersistence(omThreadStateSession);\n await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {\n // Persistence is best-effort; don't crash startup if storage hiccups.\n });\n}\n\n/**\n * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its\n * own internal Mastra via `init()`, and mint the single eager session that all\n * work in this process runs through. The AgentController owns no session of its own.\n */\nexport async function bootLocalAgentController(config?: MastraCodeConfig) {\n const base = await createMastraCodeAgentController(config);\n const { controller, sessionId, ownerId, projectPath, codeAgent, mcpManager } = base;\n\n await controller.init();\n // Register workflow primitives (sub-agent + workspace tools + code-agent\n // + web + notification_inbox + snapshot of MCP tools) on the controller's\n // Mastra so the dynamic-workflow loading in startWorkers() can rehydrate\n // saved workflows against the right tool/agent registry.\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n await mastra?.startWorkers();\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\n const session = await controller.createSession({ id: sessionId, ownerId });\n await wireSessionConcerns(base, session);\n const knowledgeInspector = await base.createKnowledgeInspector(session);\n\n return {\n ...base,\n session,\n knowledgeInspector,\n knowledgeInspectorUnavailableReason: knowledgeInspector\n ? undefined\n : 'Knowledge inspection requires a configured knowledge storage domain.',\n };\n}\n\n/** Result of {@link mountAgentControllerOnMastra}: shared handles plus the owning Mastra. */\nexport type MountedMastraCode = MastraCodeAgentController & { mastra: Mastra };\n\n/**\n * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a\n * server-owned Mastra, THEN init it. Registering before `init()` is what makes\n * the controller inherit the server's Mastra (storage, agents, gateways) instead of\n * spinning up its own internal one — there is a single shared Mastra.\n *\n * No eager session is minted: each client (browser or terminal) creates/resumes\n * its own isolated session via `controller.createSession({ resourceId })`, so one\n * server can drive many concurrent users.\n *\n * Pass an existing `mastra` to mount onto a Mastra that already hosts other\n * primitives; otherwise a Mastra is created that owns the controller's storage so\n * durability is configured in one place.\n */\nexport async function mountAgentControllerOnMastra(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n /**\n * Additional `server` config to fold onto the constructed Mastra alongside\n * the assembled `apiRoutes` (e.g. `middleware`, `cors`). Used by the\n * platform entry (`src/mastra/index.ts`) to own the WorkOS gate + tenant\n * dispatcher + CORS on the instance the deployer generates its server from.\n * Ignored when `mastra` is provided (mounting onto a caller-owned instance).\n */\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<MountedMastraCode> {\n const prepared = await prepareAgentControllerMount(config);\n if (config?.mastra) {\n // Mounting onto a Mastra the caller already built. Ensure the controller's\n // back-reference points at it (idempotent — only sets #externalMastra).\n prepared.base.controller.__registerMastra(config.mastra);\n await prepared.finalize();\n return { ...prepared.base, mastra: config.mastra };\n }\n const mastra = new Mastra(prepared.mastraArgs);\n await prepared.finalize();\n return { ...prepared.base, mastra };\n}\n\n/**\n * Assemble everything needed to construct the server-owned Mastra WITHOUT\n * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can\n * run the `new Mastra(...)` literal in its own module. The deployer's\n * `checkConfigExport` Babel plugin only marks the config valid when it finds a\n * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the\n * construction inside this helper would trip the \"Invalid Mastra config\" warning.\n *\n * Returns the constructor args plus a `finalize()` that runs the post-construct\n * boot (`controller.init()` + `startWorkers()`). The controller is registered on\n * the Mastra via the `agentControllers` arg at construction time.\n */\nexport async function prepareAgentControllerMount(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<{\n base: Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n mastraArgs: NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n finalize: () => Promise<void>;\n}> {\n const base = await createMastraCodeAgentController(config);\n const {\n controller,\n storage,\n authStorage,\n projectPath,\n codeAgent,\n mcpManager,\n backgroundToolsEnabled,\n backgroundCompletionEvents,\n } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n // Only register workflow primitives when we own the Mastra. If the caller\n // brought their own, they're responsible for what's registered on it.\n const weOwnTheMastra = !config?.mastra;\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n ...(backgroundToolsEnabled\n ? {\n backgroundTasks: {\n enabled: true,\n recoverStaleTasksOnStart: false,\n ...createBackgroundCompletionCallbacks(() => controller, backgroundCompletionEvents),\n },\n }\n : {}),\n // Mirror the controller's internal-Mastra construction (which passes\n // `config.pubsub` through): the server-owned Mastra must run its event\n // bus on the same transport so streams/workflows/signals stay\n // cross-process when a distributed PubSub (e.g. Redis Streams) is\n // configured.\n ...(base.signalsPubSub ? { pubsub: base.signalsPubSub } : {}),\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n if (weOwnTheMastra) {\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n }\n await controller.getMastra()?.startWorkers();\n // Anchored here rather than at a `new Mastra(...)` call site: finalize runs\n // in every mount path (caller-supplied Mastra, SDK-constructed Mastra, and\n // the platform entry that constructs its own), so plugin providers start\n // exactly once regardless of how Mastra Code was mounted.\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\n };\n\n return { base, mastraArgs, finalize };\n}\n\n/**\n * Back-compat alias. Historically `createMastraCode` built and booted a local\n * controller with a single session; that behavior now lives in\n * {@link bootLocalAgentController}. New code should call the explicit factory for its\n * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).\n */\nexport const createMastraCode = bootLocalAgentController;\nexport * from './knowledge-inspector.js';\nexport { LOCAL_KNOWLEDGE_ORG_ID } from './knowledge-scope.js';\n\n/**\n * Programmatic headless API. `runMC` runs an already-built controller/session\n * (from {@link createMastraCode}) as an async-iterable run that also resolves to\n * a typed result. Also available via the `mastracode/headless` subpath.\n */\nexport {\n runMC,\n runMCCli,\n hasHeadlessFlag,\n autoApprovePolicy,\n denyPolicy,\n permissionModeToPolicy,\n formatHuman,\n formatJsonl,\n renderTextResult,\n renderJsonResult,\n} from './headless/index.js';\nexport type {\n RunMCOptions,\n RunMCResult,\n RunMCStatus,\n RunMCUsage,\n RunMCToolCall,\n RunMCToolResult,\n RunMCError,\n Run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AAM,eAAe,QAAQ,gBAAgB,WAAW;CACxD,MAAM,YAAY,QAAQ,iBAAiB;EAAE;EAAY;CAAY,CAAC;CACtE,MAAM,oBAAoB,QAAQ,oBAAoB;EAAE;EAAY;CAAY,CAAC;CAGjF,MAAM,iBAAiB,CAAC,QAAQ;CAEhC,MAAM,eAAe;EACnB,GAAG;EACH,GAAI,WAAW,SAAS,EAAE,UAAU,IAAI,CAAC;CAC3C;CACA,MAAM,aAAa;EACjB,kBAAkB,GAAG,eAAe,WAAW;EAC/C;EACA,GAAI,yBACA,EACE,iBAAiB;GACf,SAAS;GACT,0BAA0B;GAC1B,GAAG,0CAA0C,YAAY,0BAA0B;EACrF,EACF,IACA,CAAC;EAML,GAAI,KAAK,gBAAgB,EAAE,QAAQ,KAAK,cAAc,IAAI,CAAC;EAC3D,GAAI,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,EAAE,QAAQ,aAAa,IAAI,CAAC;CACrE;CAEA,MAAM,WAAW,YAAY;EAC3B,MAAM,WAAW,KAAK;EACtB,IAAI,gBAAgB;GAClB,MAAM,SAAS,WAAW,UAAU;GACpC,IAAI,QAAQ,MAAM,kCAAkC,QAAQ;IAAE;IAAa;IAAW;GAAW,CAAC;EACpG;EACA,MAAM,WAAW,UAAU,CAAC,EAAE,aAAa;EAK3C,KAAK,uCAAuC;EAC5C,KAAK,2BAA2B;CAClC;CAEA,OAAO;EAAE;EAAM;EAAY;CAAS;AACtC;;;;;;;AAQA,MAAa,mBAAmB"}
@@ -7,7 +7,7 @@ async function installPluginDependencies(pluginRoot, commandRoot = pluginRoot, o
7
7
  if (!fs.existsSync(packageJsonPath)) return false;
8
8
  const packageJson = readPackageJson(pluginRoot);
9
9
  const commandPackageJson = commandRoot === pluginRoot ? packageJson : readPackageJson(commandRoot);
10
- const installCommand = getInstallCommand(pluginRoot, getPnpmVersion(pluginRoot, Object.hasOwn(packageJson, "packageManager") ? packageJson.packageManager : commandPackageJson.packageManager));
10
+ const installCommand = getInstallCommand(pluginRoot, getPnpmSpec(pluginRoot, Object.hasOwn(packageJson, "packageManager") ? packageJson.packageManager : commandPackageJson.packageManager));
11
11
  const child = execa(installCommand.command, installCommand.args, {
12
12
  cwd: pluginRoot,
13
13
  env: {
@@ -56,19 +56,18 @@ function isInsideDirectory(targetPath, root) {
56
56
  const resolvedRoot = path.resolve(root);
57
57
  return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);
58
58
  }
59
- function getPnpmVersion(pluginRoot, packageManager) {
60
- if (typeof packageManager !== "string") throw new Error(`Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using "packageManager": "pnpm@x.y.z".`);
61
- const match = /^pnpm@(\d+\.\d+\.\d+)$/.exec(packageManager);
62
- if (!match?.[1]) throw new Error(`Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using "packageManager": "pnpm@x.y.z".`);
63
- return match[1];
59
+ const PNPM_SPEC_PATTERN = /^pnpm@\d+\.\d+\.\d+(?:\+sha(?:1|224|256|384|512)\.[0-9a-f]+)?$/;
60
+ function getPnpmSpec(pluginRoot, packageManager) {
61
+ if (typeof packageManager !== "string" || !PNPM_SPEC_PATTERN.test(packageManager)) throw new Error(`Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using "packageManager": "pnpm@x.y.z".`);
62
+ return packageManager;
64
63
  }
65
- function getInstallCommand(pluginRoot, pnpmVersion) {
64
+ function getInstallCommand(pluginRoot, pnpmSpec) {
66
65
  const installArgs = ["install", "--ignore-workspace"];
67
66
  if (hasFile(pluginRoot, "pnpm-lock.yaml")) installArgs.push("--frozen-lockfile");
68
67
  installArgs.push("--ignore-scripts");
69
68
  return {
70
69
  command: "corepack",
71
- args: [`pnpm@${pnpmVersion}`, ...installArgs]
70
+ args: [pnpmSpec, ...installArgs]
72
71
  };
73
72
  }
74
73
  function isCommandNotFoundError(error) {
@@ -1 +1 @@
1
- {"version":3,"file":"dependencies.js","names":[],"sources":["../../src/plugins/dependencies.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { execa } from 'execa';\n\ntype InstallCommand = {\n command: string;\n args: string[];\n};\n\nexport type PluginInstallExecutionOptions = {\n onOutput?: (chunk: Buffer | string) => void;\n signal?: AbortSignal;\n};\n\nexport async function installPluginDependencies(\n pluginRoot: string,\n commandRoot = pluginRoot,\n options: PluginInstallExecutionOptions = {},\n): Promise<boolean> {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const packageJson = readPackageJson(pluginRoot);\n const commandPackageJson = commandRoot === pluginRoot ? packageJson : readPackageJson(commandRoot);\n const packageManager = Object.hasOwn(packageJson, 'packageManager')\n ? packageJson.packageManager\n : commandPackageJson.packageManager;\n const pnpmVersion = getPnpmVersion(pluginRoot, packageManager);\n const installCommand = getInstallCommand(pluginRoot, pnpmVersion);\n\n const child = execa(installCommand.command, installCommand.args, {\n cwd: pluginRoot,\n env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },\n stdout: options.onOutput ? 'pipe' : 'ignore',\n stderr: options.onOutput ? 'pipe' : 'ignore',\n cancelSignal: options.signal,\n });\n if (options.onOutput) {\n child.stdout?.on('data', options.onOutput);\n child.stderr?.on('data', options.onOutput);\n }\n try {\n await child;\n } catch (error) {\n if (isCommandNotFoundError(error)) {\n throw new Error(\n 'Mastra Code requires Corepack to install GitHub plugin dependencies. Install it with \"npm install --global corepack\" and try again.',\n { cause: error },\n );\n }\n throw error;\n }\n return true;\n}\n\nexport async function installPluginDependenciesForEntry(\n pluginRoot: string,\n entry: string,\n options: PluginInstallExecutionOptions = {},\n): Promise<void> {\n for (const dependencyRoot of getPluginDependencyRoots(pluginRoot, entry)) {\n await installPluginDependencies(dependencyRoot, pluginRoot, options);\n }\n}\n\nexport function getPluginDependencyRoots(pluginRoot: string, entry: string): string[] {\n const roots = fs.existsSync(path.join(pluginRoot, 'package.json')) ? [pluginRoot] : [];\n const entryPackageRoot = findEntryPackageRoot(pluginRoot, entry);\n if (entryPackageRoot && entryPackageRoot !== pluginRoot) {\n roots.push(entryPackageRoot);\n }\n return roots;\n}\n\nexport function getEntryPackageRoot(pluginRoot: string, entry: string): string {\n return findEntryPackageRoot(pluginRoot, entry) ?? pluginRoot;\n}\n\nfunction findEntryPackageRoot(pluginRoot: string, entry: string): string | undefined {\n const root = path.resolve(pluginRoot);\n let current = path.dirname(path.resolve(pluginRoot, entry));\n\n while (isInsideDirectory(current, root)) {\n if (fs.existsSync(path.join(current, 'package.json'))) {\n return current;\n }\n if (current === root) break;\n current = path.dirname(current);\n }\n\n return undefined;\n}\n\nfunction isInsideDirectory(targetPath: string, root: string): boolean {\n const resolvedTarget = path.resolve(targetPath);\n const resolvedRoot = path.resolve(root);\n return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);\n}\n\nfunction getPnpmVersion(pluginRoot: string, packageManager: unknown): string {\n if (typeof packageManager !== 'string') {\n throw new Error(\n `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using \"packageManager\": \"pnpm@x.y.z\".`,\n );\n }\n\n const match = /^pnpm@(\\d+\\.\\d+\\.\\d+)$/.exec(packageManager);\n if (!match?.[1]) {\n throw new Error(\n `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using \"packageManager\": \"pnpm@x.y.z\".`,\n );\n }\n return match[1];\n}\n\nfunction getInstallCommand(pluginRoot: string, pnpmVersion: string): InstallCommand {\n const installArgs = ['install', '--ignore-workspace'];\n if (hasFile(pluginRoot, 'pnpm-lock.yaml')) installArgs.push('--frozen-lockfile');\n installArgs.push('--ignore-scripts');\n\n return {\n command: 'corepack',\n args: [`pnpm@${pnpmVersion}`, ...installArgs],\n };\n}\n\nfunction isCommandNotFoundError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nfunction readPackageJson(pluginRoot: string): { packageManager?: unknown } {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return {};\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { packageManager?: unknown };\n}\n\nfunction hasFile(pluginRoot: string, fileName: string): boolean {\n return fs.existsSync(path.join(pluginRoot, fileName));\n}\n"],"mappings":";;;;AAeA,eAAsB,0BACpB,YACA,cAAc,YACd,UAAyC,CAAC,GACxB;CAClB,MAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;CAC5D,IAAI,CAAC,GAAG,WAAW,eAAe,GAChC,OAAO;CAGT,MAAM,cAAc,gBAAgB,UAAU;CAC9C,MAAM,qBAAqB,gBAAgB,aAAa,cAAc,gBAAgB,WAAW;CAKjG,MAAM,iBAAiB,kBAAkB,YADrB,eAAe,YAHZ,OAAO,OAAO,aAAa,gBAAgB,IAC9D,YAAY,iBACZ,mBAAmB,cAEwC,CAAC;CAEhE,MAAM,QAAQ,MAAM,eAAe,SAAS,eAAe,MAAM;EAC/D,KAAK;EACL,KAAK;GAAE,GAAG,QAAQ;GAAK,qBAAqB;EAAI;EAChD,QAAQ,QAAQ,WAAW,SAAS;EACpC,QAAQ,QAAQ,WAAW,SAAS;EACpC,cAAc,QAAQ;CACxB,CAAC;CACD,IAAI,QAAQ,UAAU;EACpB,MAAM,QAAQ,GAAG,QAAQ,QAAQ,QAAQ;EACzC,MAAM,QAAQ,GAAG,QAAQ,QAAQ,QAAQ;CAC3C;CACA,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,uBAAuB,KAAK,GAC9B,MAAM,IAAI,MACR,yIACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;CACA,OAAO;AACT;AAEA,eAAsB,kCACpB,YACA,OACA,UAAyC,CAAC,GAC3B;CACf,KAAK,MAAM,kBAAkB,yBAAyB,YAAY,KAAK,GACrE,MAAM,0BAA0B,gBAAgB,YAAY,OAAO;AAEvE;AAEA,SAAgB,yBAAyB,YAAoB,OAAyB;CACpF,MAAM,QAAQ,GAAG,WAAW,KAAK,KAAK,YAAY,cA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D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS;AAC1F;AAEA,SAAS,gBAAgB,YAAkD;CACzE,MAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;CAC5D,IAAI,CAAC,GAAG,WAAW,eAAe,GAAG,OAAO,CAAC;CAC7C,OAAO,KAAK,MAAM,GAAG,aAAa,iBAAiB,MAAM,CAAC;AAC5D;AAEA,SAAS,QAAQ,YAAoB,UAA2B;CAC9D,OAAO,GAAG,WAAW,KAAK,KAAK,YAAY,QAAQ,CAAC;AACtD"}
1
+ {"version":3,"file":"dependencies.js","names":[],"sources":["../../src/plugins/dependencies.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { execa } from 'execa';\n\ntype InstallCommand = {\n command: string;\n args: string[];\n};\n\nexport type PluginInstallExecutionOptions = {\n onOutput?: (chunk: Buffer | string) => void;\n signal?: AbortSignal;\n};\n\nexport async function installPluginDependencies(\n pluginRoot: string,\n commandRoot = pluginRoot,\n options: PluginInstallExecutionOptions = {},\n): Promise<boolean> {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return false;\n }\n\n const packageJson = readPackageJson(pluginRoot);\n const commandPackageJson = commandRoot === pluginRoot ? packageJson : readPackageJson(commandRoot);\n const packageManager = Object.hasOwn(packageJson, 'packageManager')\n ? packageJson.packageManager\n : commandPackageJson.packageManager;\n const pnpmSpec = getPnpmSpec(pluginRoot, packageManager);\n const installCommand = getInstallCommand(pluginRoot, pnpmSpec);\n\n const child = execa(installCommand.command, installCommand.args, {\n cwd: pluginRoot,\n env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },\n stdout: options.onOutput ? 'pipe' : 'ignore',\n stderr: options.onOutput ? 'pipe' : 'ignore',\n cancelSignal: options.signal,\n });\n if (options.onOutput) {\n child.stdout?.on('data', options.onOutput);\n child.stderr?.on('data', options.onOutput);\n }\n try {\n await child;\n } catch (error) {\n if (isCommandNotFoundError(error)) {\n throw new Error(\n 'Mastra Code requires Corepack to install GitHub plugin dependencies. Install it with \"npm install --global corepack\" and try again.',\n { cause: error },\n );\n }\n throw error;\n }\n return true;\n}\n\nexport async function installPluginDependenciesForEntry(\n pluginRoot: string,\n entry: string,\n options: PluginInstallExecutionOptions = {},\n): Promise<void> {\n for (const dependencyRoot of getPluginDependencyRoots(pluginRoot, entry)) {\n await installPluginDependencies(dependencyRoot, pluginRoot, options);\n }\n}\n\nexport function getPluginDependencyRoots(pluginRoot: string, entry: string): string[] {\n const roots = fs.existsSync(path.join(pluginRoot, 'package.json')) ? [pluginRoot] : [];\n const entryPackageRoot = findEntryPackageRoot(pluginRoot, entry);\n if (entryPackageRoot && entryPackageRoot !== pluginRoot) {\n roots.push(entryPackageRoot);\n }\n return roots;\n}\n\nexport function getEntryPackageRoot(pluginRoot: string, entry: string): string {\n return findEntryPackageRoot(pluginRoot, entry) ?? pluginRoot;\n}\n\nfunction findEntryPackageRoot(pluginRoot: string, entry: string): string | undefined {\n const root = path.resolve(pluginRoot);\n let current = path.dirname(path.resolve(pluginRoot, entry));\n\n while (isInsideDirectory(current, root)) {\n if (fs.existsSync(path.join(current, 'package.json'))) {\n return current;\n }\n if (current === root) break;\n current = path.dirname(current);\n }\n\n return undefined;\n}\n\nfunction isInsideDirectory(targetPath: string, root: string): boolean {\n const resolvedTarget = path.resolve(targetPath);\n const resolvedRoot = path.resolve(root);\n return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);\n}\n\n// Accepts the optional Corepack integrity suffix (e.g. `+sha512.<hex>`) written by `corepack use`.\nconst PNPM_SPEC_PATTERN = /^pnpm@\\d+\\.\\d+\\.\\d+(?:\\+sha(?:1|224|256|384|512)\\.[0-9a-f]+)?$/;\n\nfunction getPnpmSpec(pluginRoot: string, packageManager: unknown): string {\n if (typeof packageManager !== 'string' || !PNPM_SPEC_PATTERN.test(packageManager)) {\n throw new Error(\n `Plugin at ${pluginRoot} must declare an exact pnpm version in package.json using \"packageManager\": \"pnpm@x.y.z\".`,\n );\n }\n return packageManager;\n}\n\nfunction getInstallCommand(pluginRoot: string, pnpmSpec: string): InstallCommand {\n const installArgs = ['install', '--ignore-workspace'];\n if (hasFile(pluginRoot, 'pnpm-lock.yaml')) installArgs.push('--frozen-lockfile');\n installArgs.push('--ignore-scripts');\n\n return {\n command: 'corepack',\n args: [pnpmSpec, ...installArgs],\n };\n}\n\nfunction isCommandNotFoundError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nfunction readPackageJson(pluginRoot: string): { packageManager?: unknown } {\n const packageJsonPath = path.join(pluginRoot, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return {};\n return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { packageManager?: unknown };\n}\n\nfunction hasFile(pluginRoot: string, fileName: string): boolean {\n return fs.existsSync(path.join(pluginRoot, fileName));\n}\n"],"mappings":";;;;AAeA,eAAsB,0BACpB,YACA,cAAc,YACd,UAAyC,CAAC,GACxB;CAClB,MAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;CAC5D,IAAI,CAAC,GAAG,WAAW,eAAe,GAChC,OAAO;CAGT,MAAM,cAAc,gBAAgB,UAAU;CAC9C,MAAM,qBAAqB,gBAAgB,aAAa,cAAc,gBAAgB,WAAW;CAKjG,MAAM,iBAAiB,kBAAkB,YADxB,YAAY,YAHN,OAAO,OAAO,aAAa,gBAAgB,IAC9D,YAAY,iBACZ,mBAAmB,cAEqC,CAAC;CAE7D,MAAM,QAAQ,MAAM,eAAe,SAAS,eAAe,MAAM;EAC/D,KAAK;EACL,KAAK;GAAE,GAAG,QAAQ;GAAK,qBAAqB;EAAI;EAChD,QAAQ,QAAQ,WAAW,SAAS;EACpC,QAAQ,QAAQ,WAAW,SAAS;EACpC,cAAc,QAAQ;CACxB,CAAC;CACD,IAAI,QAAQ,UAAU;EACpB,MAAM,QAAQ,GAAG,QAA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C;CACxE,IAAI,OAAO,mBAAmB,YAAY,CAAC,kBAAkB,KAAK,cAAc,GAC9E,MAAM,IAAI,MACR,aAAa,WAAW,0FAC1B;CAEF,OAAO;AACT;AAEA,SAAS,kBAAkB,YAAoB,UAAkC;CAC/E,MAAM,cAAc,CAAC,WAAW,oBAAoB;CACpD,IAAI,QAAQ,YAAY,gBAAgB,GAAG,YAAY,KAAK,mBAAmB;CAC/E,YAAY,KAAK,kBAAkB;CAEnC,OAAO;EACL,SAAS;EACT,MAAM,CAAC,UAAU,GAAG,WAAW;CACjC;AACF;AAEA,SAAS,uBAAuB,OAAyB;CACvD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,SAAS,MAAM,SAAS;AAC1F;AAEA,SAAS,gBAAgB,YAAkD;CACzE,MAAM,kBAAkB,KAAK,KAAK,YAAY,cAAc;CAC5D,IAAI,CAAC,GAAG,WAAW,eAAe,GAAG,OAAO,CAAC;CAC7C,OAAO,KAAK,MAAM,GAAG,aAAa,iBAAiB,MAAM,CAAC;AAC5D;AAEA,SAAS,QAAQ,YAAoB,UAA2B;CAC9D,OAAO,GAAG,WAAW,KAAK,KAAK,YAAY,QAAQ,CAAC;AACtD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/code-sdk",
3
- "version": "1.8.4-alpha.0",
3
+ "version": "1.8.4-alpha.2",
4
4
  "description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -57,18 +57,18 @@
57
57
  "yaml": "^2.7.1",
58
58
  "zod": "^4.6.4",
59
59
  "@mastra/agent-browser": "0.5.3",
60
- "@mastra/core": "1.72.0-alpha.0",
60
+ "@mastra/core": "1.72.0-alpha.2",
61
61
  "@mastra/duckdb": "1.11.1",
62
62
  "@mastra/fastembed": "1.3.2",
63
63
  "@mastra/github-signals": "0.5.0",
64
64
  "@mastra/mcp": "2.1.0",
65
- "@mastra/observability": "1.18.1",
65
+ "@mastra/memory": "1.32.2-alpha.1",
66
+ "@mastra/observability": "1.18.2-alpha.0",
67
+ "@mastra/libsql": "1.23.4-alpha.0",
66
68
  "@mastra/parallel": "0.1.2",
67
- "@mastra/libsql": "1.23.3",
68
- "@mastra/pg": "1.27.2-alpha.0",
69
- "@mastra/schema-compat": "1.3.11",
69
+ "@mastra/schema-compat": "1.3.12-alpha.0",
70
+ "@mastra/pg": "1.27.2-alpha.1",
70
71
  "@mastra/stagehand": "0.3.5",
71
- "@mastra/memory": "1.32.2-alpha.0",
72
72
  "@mastra/tavily": "1.1.2"
73
73
  },
74
74
  "devDependencies": {