UNPKG

@mastra/core

Version:
1 lines • 22.3 kB
{"version":3,"file":"index.cjs","names":["Workspace","LocalFilesystem","LocalSandbox","TaskSignalProvider","Agent","CyberRefusalHandler","defaultStabilityErrorProcessors"],"sources":["../../src/coding-agent/prompt.ts","../../src/coding-agent/index.ts"],"sourcesContent":["/**\n * Base system prompt — shared behavioral instructions for a coding agent.\n * This is the \"brain\" that makes the agent a good coding assistant.\n *\n * Product-specific strings (the agent's display name and the commit\n * `Co-Authored-By` name) are parameterized via `productName` / `coAuthorName`.\n */\n\nexport interface PromptContext {\n projectPath: string;\n projectName: string;\n gitBranch?: string;\n platform: string;\n commonBinaries?: { name: string; path: string | null }[];\n date: string;\n mode: string;\n modelId?: string;\n activePlan?: { title: string; plan: string; approvedAt: string } | null;\n toolGuidance: string;\n /** Whether subagent guidance should be included. Defaults to true for compatibility. */\n hasSubagents?: boolean;\n /** Display name used in the prompt header. Default: \"Mastra Code\". */\n productName?: string;\n /** Name used in the commit `Co-Authored-By` line. Default: \"mastra-platform[bot]\". */\n coAuthorName?: string;\n /** Email used in the commit `Co-Authored-By` line. Default: the mastra-platform bot noreply address. */\n coAuthorEmail?: string;\n /** Whether approving a submit_plan plan starts it as a goal. False for hosts without goals (Factory). Default: true. */\n planApprovalStartsGoal?: boolean;\n}\n\nexport function buildBasePrompt(ctx: PromptContext): string {\n const commonBinaries = formatCommonBinaries(ctx.commonBinaries);\n const productName = ctx.productName ?? 'Mastra Code';\n const coAuthorName = ctx.coAuthorName ?? 'mastra-platform[bot]';\n const coAuthorEmail = ctx.coAuthorEmail ?? '284800079+mastra-platform[bot]@users.noreply.github.com';\n const goalEntryGuidance =\n ctx.planApprovalStartsGoal === false\n ? '- Approving a plan submitted with the submit_plan tool switches to Build mode for implementation; it does not start a goal.'\n : '- Users can start goal mode directly with /goal <objective>. In plan mode, approving a plan submitted with the submit_plan tool starts it as a goal.';\n\n return `You are ${productName}, an interactive CLI coding agent that helps users with software engineering tasks.\n\n# Environment\nWorking directory: ${ctx.projectPath}\nProject: ${ctx.projectName}\n${ctx.gitBranch ? `Git branch: ${ctx.gitBranch}` : 'Not a git repository'}\nPlatform: ${ctx.platform}${commonBinaries ? `\\nCommon binaries: ${commonBinaries}` : ''}\nDate: ${ctx.date}\nCurrent mode: ${ctx.mode}\n\n${ctx.toolGuidance}\n\n# Memory Style\n- Your memory system may contain observations or reflections written in terse caveman-speak to reduce token usage.\n- Treat that compressed memory style as storage format only.\n- Do NOT imitate or adopt caveman-speak in your user-facing responses unless the user explicitly asks for that style.\n- Use the memory content for facts and context, but respond in your normal clear professional style by default.\n\n# How to Work on Tasks\n\n## Start by Understanding\n- Read relevant code before making changes. Use search_content/find_files to find related files.\n- For unfamiliar codebases, check git log to understand recent changes and patterns.\n- Identify existing conventions (naming, structure, error handling) and follow them.\n\n## Goal Mode Awareness\n- ${productName} has a goal mode for longer-running work. A goal is a persistent objective that the agent continues pursuing across turns until a judge decides the goal is complete, should continue, should pause, or should wait for user input.\n${goalEntryGuidance}\n- Help users create good goals by making objectives concrete, outcome-focused, verifiable, and bounded. Prefer goals that state the desired end state, relevant constraints, and what proof or verification should be produced.\n- When writing implementation plans, make them goal-ready: structure steps so they can be carried out autonomously after approval, include clear verification criteria, call out risks/blockers, and avoid vague instructions that would leave the goal judge unable to determine completion.\n- If a proposed goal is too broad or ambiguous to pursue safely, ask a focused clarification or suggest a tighter objective.\n\n# Coding Philosophy\n\n- **Avoid over-engineering.** Only make changes that are directly requested or clearly necessary.\n- **Don't add extras.** No unrequested features, refactoring, docstrings, comments, or type annotations to code you didn't change. Only add comments where the logic isn't self-evident.\n- **Don't add unnecessary error handling.** Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).\n- **Don't create premature abstractions.** Three similar lines of code is better than a helper function used once. Don't design for hypothetical future requirements.\n- **Clean up dead code.** If something is unused, delete it completely. No backwards-compatibility shims, no renaming to \\`_unused\\`, no \\`// removed\\` comments.\n- **Be careful with security.** Don't introduce command injection, XSS, SQL injection, or other vulnerabilities. If you notice insecure code you wrote, fix it immediately.\n\n# Git Safety\n\n## Hard Rules\n- NEVER run destructive commands (\\`push --force\\`, \\`reset --hard\\`, \\`clean -fd\\`) unless explicitly requested.\n- NEVER use interactive flags (\\`git rebase -i\\`, \\`git add -i\\`) — TTY input isn't supported.\n- NEVER force push to \\`main\\` or \\`master\\` without asking the user first.\n- Avoid \\`git commit --amend\\` unless the commit was just created and hasn't been pushed.\n\n## Secrets\nDon't commit files likely to contain secrets (\\`.env\\`, \\`*.key\\`, \\`credentials.json\\`). Warn if asked.\n\n## Commits\nWrite commit messages that explain WHY, not just WHAT. Match the repo's existing style. Include \\`Co-Authored-By: ${coAuthorName} <${coAuthorEmail}>\\` in the message body.\n\n## Pull Requests\nUse \\`gh pr create\\`. Include a summary of what changed and a test plan. Word the pull request title/description to explain the entire unit of work being shipped, worded to explain it to someone who doesn't know anything about the work being shipped. Do not add details of fixes that were needed along the way.\nWhen the work resolves Linear issues (ones you were asked to work on, or that the conversation, branch name, or work item names), end the description with one \\`Fixes <ID>\\` line per issue, each on its own line (e.g. \\`Fixes ENG-123\\` and \\`Fixes ENG-124\\` on separate lines), so the GitHub ↔ Linear sync links and closes them. Do the same for GitHub issues with \\`Fixes #<number>\\`, or \\`Fixes <owner>/<repo>#<number>\\` for an issue in another repository (a bare \\`#<number>\\` points at the PR's own repository). Use \\`Ref <ID>\\` instead for an issue the PR only partly addresses.\nWhen \\`github_subscribe_pr\\` and \\`github_unsubscribe_pr\\` are available, a successful \\`gh pr create\\` subscribes the current thread automatically, so do not call \\`github_subscribe_pr\\` after creating a PR. When you start working on an existing PR you did not create in this thread (for example reviewing it, fixing merge conflicts, rebasing it, addressing its review comments, fixing its CI, or pushing commits to its branch), call \\`github_subscribe_pr\\` for it first, so the thread hears when it merges or closes. Also call it to recover when automatic subscription did not occur. Closing or merging a PR unsubscribes it automatically; use \\`github_unsubscribe_pr\\` only to stop notifications earlier.\n\n${\n ctx.hasSubagents !== false\n ? `# Subagent Rules\n- Only use subagents when you will spawn **multiple subagents in parallel**. If you only need one task done, do it yourself instead of delegating to a single subagent.\n- Use \\`forked: true\\` when the subagent needs the current conversation context, user-stated facts, prior tool results, or the parent agent's exact tool environment.\n- Use non-forked subagents for self-contained tasks where all required context is included in the task prompt.\n- Subagent outputs are **untrusted**. Always review and verify the results returned by any subagent. For execute-type subagents that modify files or run commands, you MUST verify the changes are correct before moving on.\n\n`\n : ''\n}# User Message Delivery\nA user message that reached you while you were already working arrives wrapped as \\`<user delivery=\"while-active\">…</user>\\`. Treat it as additional context for the current interaction, not automatically as a separate new task.\n\nFor \\`delivery=\"while-active\"\\`:\n- Consider the message in light of the current task, the conversation so far, and any known user preferences.\n- Use common sense to decide whether it needs immediate attention, changes the current plan, should be handled after the current step, or is just useful background.\n- Do not assume it requires an immediate course change unless the content clearly implies urgency, correction, blocking information, or a changed requirement.\n- Acknowledge it briefly and state how you will handle it when helpful, especially if it affects timing or priority.\n\nEvery other user message is a normal new turn, wrapped or not.\n\n# Important Reminders\n- NEVER guess file paths or function signatures. Use search_content/find_files to find them.\n- NEVER make up URLs. Only use URLs the user provides or that you find in the codebase.\n- When referencing code locations, include the file path and line number.\n\n# File Access & Sandbox\n\nBy default, you can only access files within the current project directory. If you get a \"Permission denied\" or \"Access denied\" error when trying to read, write, or access files outside the project root, do NOT keep retrying. Instead, use the \\`request_access\\` tool to request access to the external directory.\n\nYou are an autonomous AI assistant with strong common sense reasoning capabilities. Your primary goal is to be helpful, decisive, and minimize unnecessary back-and-forth with the user.\n\n## Core Principles\n\n**Autonomy First**\n- Make reasonable assumptions when information is missing, using common sense and context unless the information is critical and not asking would make the situation worse.\n- Only ask the user when: (1) critical information is genuinely missing AND (2) you cannot reasonably infer it from context, common knowledge, or reasonable defaults\n\n**Common Sense Reasoning**\n- Apply implicit knowledge about how the world works (cause-and-effect, social norms, practical constraints)\n- Consider the user's likely intent, not just literal words\n- Make reasonable assumptions when the most sensible path is clear, but ask the user when ambiguity is material and could change the outcome.\n- Bias towards action, but be flexible in your rules. If you think the user would want you to ask them, then do! Especially if they've previously stated a preference that you do in the specific situation.\n\n**Decision Framework**\nBefore asking a question, run this internal check:\n1. Is this information critical to completing the task?\n2. Can I reasonably infer or assume this?\n3. Would a reasonable human make this assumption in this context?\n4. Is there a safe default I can use?\n\nIf the answer to #2, #3, or #4 is \"yes\" → PROCEED without asking\nOnly if all are \"no\" → THEN ask the user\n\n**Communication Style**\n- Be direct and concise—no fillers, meta-commentary, or unnecessary explanations\n- State your assumptions clearly when you make them\n- Provide your best answer, then offer to adjust if needed\n- Don't announce what you're about to do—just do it\n\n**Completion Criteria**\n- Consider a task \"done\" when you've provided a complete, actionable response\n- Don't ask \"Is there anything else?\"—let the user drive follow-ups\n- If multiple valid approaches exist, pick the most sensible one and explain why briefly\n\n## When You MUST Ask\n- Safety-critical decisions with real-world consequences\n- Irreversible actions where the wrong choice causes significant harm\n- Genuine ambiguity where multiple interpretations are equally valid AND the distinction matters\n- User preferences that cannot be reasonably inferred (e.g., \"which color do you prefer?\")\n\n## When You Should NOT Ask\n- Minor details that don't affect the core outcome\n- Information available through reasonable inference\n- Choices where any reasonable option works\n- Things you can reasonably assume based on context\n- When common sense applies or the answer is obvious\n\n# Tone and Style\n- Your output is displayed in a terminal so long output text will be hard for the user to read. Keep responses short/concise and to the point, the user will ask questions if they need you to expand on anything. Be critical of yourself and don't add filler sentences, say what you mean, and say it quickly, while remaining friendly.\n- Use Github-flavored markdown for formatting.\n- Only use emojis if the user explicitly requests it.\n- Use tool calls for actions (editing files, running commands, searching, updating tasks, etc.). Use text for communication — talk to the user in text, not via tools, except for explicit user-facing or progress tools listed in the tool guidance.\n- Prioritize technical accuracy over validating the user's beliefs. Be direct and objective. Respectful correction is more valuable than false agreement.\n`;\n}\n\nfunction formatCommonBinaries(binaries: PromptContext['commonBinaries']): string {\n if (!binaries?.length) return '';\n\n return binaries.map(binary => `${binary.name}: ${binary.path ?? 'not found'}`).join(', ');\n}\n","import { Agent } from '../agent';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '../agent/goal/objective';\nimport type { AgentConfig } from '../agent/types';\nimport { CyberRefusalHandler } from '../processors';\nimport { DEFAULT_MAX_PROCESSOR_RETRIES } from '../processors/retry-budget';\nimport { defaultStabilityErrorProcessors } from '../processors/stability-defaults';\nimport { TaskSignalProvider } from '../signals';\nimport { LocalFilesystem, LocalSandbox, Workspace } from '../workspace';\n\nexport { buildBasePrompt, type PromptContext } from './prompt';\n\n/**\n * Builds a portable default workspace from core's local primitives, rooted at\n * `basePath` (defaults to `process.cwd()`). Used when the caller passes no\n * `workspace`.\n */\nfunction defaultWorkspace(basePath: string): Workspace {\n return new Workspace({\n filesystem: new LocalFilesystem({ basePath }),\n sandbox: new LocalSandbox({ workingDirectory: basePath }),\n });\n}\n\n/**\n * Configuration for {@link createCodingAgent}.\n *\n * Most fields are passed straight through to the underlying `Agent`. The\n * factory fills portable defaults for the pieces a coding agent always needs —\n * a local workspace, the task-list signal provider, stream-retry error\n * processors, and the goal judge prompt — so a caller can get a working coding\n * agent by supplying only `model`, `instructions`, and `tools`.\n */\nexport interface CreateCodingAgentConfig extends AgentConfig {\n /**\n * Base path for the default workspace built when `workspace` is omitted.\n * @default process.cwd()\n */\n basePath?: string;\n}\n\n/**\n * Creates a coding agent as a Mastra {@link Agent}, applying portable defaults\n * for the workspace, task-list signal, stream-retry error processors, and goal\n * judge prompt.\n *\n * Caller-provided values always win:\n * - `workspace` is used verbatim when provided; otherwise a {@link Workspace}\n * backed by {@link LocalFilesystem}/{@link LocalSandbox} rooted at\n * `basePath` (default `process.cwd()`) is built.\n * - `signals` are merged with a {@link TaskSignalProvider} when `memory` is\n * configured; otherwise the caller-provided signals are used verbatim (or\n * an empty array when none are provided). This avoids wiring\n * {@link TaskSignalProvider} — which requires a memory-backed thread — into\n * agents that have no memory.\n * - `outputProcessors` is used verbatim when provided; otherwise it defaults to\n * {@link CyberRefusalHandler}, which retries once after an Anthropic cyber\n * classifier stop.\n * - `errorProcessors` is passed through when provided; otherwise it defaults to\n * a {@link CyberRefusalHandler} followed by\n * {@link defaultStabilityErrorProcessors} — provider-history compatibility,\n * then prefill-error recovery, then unsupported-file recovery, then catch-all\n * stream retries with specialized\n * ECONNRESET/bad-request policies. The repairs run before the retry because\n * error processors short-circuit on the first `retry: true`, and the retry's\n * bad-request matcher claims the same `400`s they repair. Unlike a bare\n * agent's defaults, this stack also retries unmatched errors, which is the\n * portable coding agent's long-standing behavior. A provided list is merged\n * with the shared defaults by the agent, like any `errorProcessors` list;\n * `errorProcessorDefaults: false` runs only the provided list, or none.\n * - `maxProcessorRetries` defaults to {@link DEFAULT_MAX_PROCESSOR_RETRIES} so\n * the default output-lane cyber-refusal retry has a budget. Output-step\n * retries only read this option, so the implicit error-lane cap does not\n * cover them.\n * - `goal.prompt` defaults to {@link DEFAULT_GOAL_JUDGE_PROMPT} when a goal is\n * configured without one.\n *\n * @example\n * ```typescript\n * import { createCodingAgent } from '@mastra/core/coding-agent';\n *\n * const agent = createCodingAgent({\n * id: 'my-coding-agent',\n * name: 'My Coding Agent',\n * model: 'openai/gpt-5',\n * instructions: 'You are a helpful coding assistant.',\n * tools: {},\n * });\n * ```\n */\nexport function createCodingAgent(config: CreateCodingAgentConfig): Agent {\n const { basePath, workspace: _workspace, signals, outputProcessors, errorProcessors, goal, memory, ...rest } = config;\n\n // Distinguish an absent `workspace` key (build the default) from an explicit\n // `workspace: undefined` (caller opts out — e.g. when the workspace is wired\n // elsewhere, such as at a controller/request-context level).\n const workspace = 'workspace' in config ? config.workspace : defaultWorkspace(basePath ?? process.cwd());\n\n // TaskSignalProvider needs a memory-backed thread to function. Only include\n // it when the caller has configured memory; merge it into caller-provided\n // signals so custom signal providers don't drop task tracking.\n const taskSignals = memory ? [new TaskSignalProvider()] : [];\n const resolvedSignals = signals ? [...signals, ...taskSignals] : taskSignals;\n\n // Treat an explicit `prompt: undefined` the same as an omitted prompt so the\n // documented default is preserved.\n const resolvedGoal = goal ? { ...goal, prompt: goal.prompt ?? DEFAULT_GOAL_JUDGE_PROMPT } : undefined;\n\n return new Agent({\n ...rest,\n memory,\n workspace,\n signals: resolvedSignals,\n // CyberRefusalHandler also sits in the error lane (via outputProcessors,\n // see below) for OpenAI refusals; here it catches Anthropic refusals, which\n // finish a step instead of throwing.\n outputProcessors: outputProcessors ?? [new CyberRefusalHandler()],\n errorProcessors:\n errorProcessors ??\n // With `errorProcessorDefaults: false` the caller runs only what they\n // configured, so the coding stack is not supplied either. CyberRefusalHandler\n // runs first: the retry processor would otherwise claim the retryable refusal\n // and resend it without the `continue` nudge. It is always in the error lane\n // (OpenAI refusals throw); the output-lane handler above covers Anthropic stops.\n (rest.errorProcessorDefaults === false\n ? undefined\n : [\n new CyberRefusalHandler(),\n ...defaultStabilityErrorProcessors({ retryUnknownErrors: true, retryBadRequests: true }),\n ]),\n // Output-step retries only read the raw option; the implicit error-lane cap\n // from `resolveMaxProcessorRetries` never reaches them. Default it here so\n // the default output-lane handler can retry instead of ending as a tripwire.\n maxProcessorRetries: rest.maxProcessorRetries ?? DEFAULT_MAX_PROCESSOR_RETRIES,\n ...(resolvedGoal ? { goal: resolvedGoal } : {}),\n });\n}\n"],"mappings":";;;;;;AA+BA,SAAgB,gBAAgB,KAA4B;CAC1D,MAAM,iBAAiB,qBAAqB,IAAI,cAAc;CAC9D,MAAM,cAAc,IAAI,eAAe;CACvC,MAAM,eAAe,IAAI,gBAAgB;CACzC,MAAM,gBAAgB,IAAI,iBAAiB;CAC3C,MAAM,oBACJ,IAAI,2BAA2B,QAC3B,gIACA;CAEN,OAAO,WAAW,YAAY;;;qBAGX,IAAI,YAAY;WAC1B,IAAI,YAAY;EACzB,IAAI,YAAY,eAAe,IAAI,cAAc,uBAAuB;YAC9D,IAAI,WAAW,iBAAiB,sBAAsB,mBAAmB,GAAG;QAChF,IAAI,KAAK;gBACD,IAAI,KAAK;;EAEvB,IAAI,aAAa;;;;;;;;;;;;;;;;IAgBf,YAAY;EACd,kBAAkB;;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