@mastra/code-sdk 1.18.0-alpha.1 → 1.18.0-alpha.3

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.
Files changed (50) hide show
  1. package/dist/agents/credential-resolver.d.ts +4 -3
  2. package/dist/agents/credential-resolver.d.ts.map +1 -1
  3. package/dist/agents/credential-resolver.js.map +1 -1
  4. package/dist/agents/instructions.d.ts +6 -2
  5. package/dist/agents/instructions.d.ts.map +1 -1
  6. package/dist/agents/instructions.js +11 -5
  7. package/dist/agents/instructions.js.map +1 -1
  8. package/dist/agents/memory.js +1 -1
  9. package/dist/agents/model.d.ts +25 -1
  10. package/dist/agents/model.d.ts.map +1 -1
  11. package/dist/agents/model.js +53 -1
  12. package/dist/agents/model.js.map +1 -1
  13. package/dist/agents/prompts/index.d.ts +5 -0
  14. package/dist/agents/prompts/index.d.ts.map +1 -1
  15. package/dist/agents/prompts/index.js +5 -2
  16. package/dist/agents/prompts/index.js.map +1 -1
  17. package/dist/agents/prompts/tool-guidance.d.ts +2 -0
  18. package/dist/agents/prompts/tool-guidance.d.ts.map +1 -1
  19. package/dist/agents/prompts/tool-guidance.js +6 -3
  20. package/dist/agents/prompts/tool-guidance.js.map +1 -1
  21. package/dist/agents/tools.d.ts.map +1 -1
  22. package/dist/agents/tools.js +27 -7
  23. package/dist/agents/tools.js.map +1 -1
  24. package/dist/auth/account-routing-context.d.ts +6 -2
  25. package/dist/auth/account-routing-context.d.ts.map +1 -1
  26. package/dist/auth/account-routing-context.js.map +1 -1
  27. package/dist/headless/flags.d.ts.map +1 -1
  28. package/dist/headless/flags.js +6 -0
  29. package/dist/headless/flags.js.map +1 -1
  30. package/dist/headless/run-mc.js +3 -3
  31. package/dist/headless/run-mc.js.map +1 -1
  32. package/dist/headless/types.d.ts +1 -0
  33. package/dist/headless/types.d.ts.map +1 -1
  34. package/dist/headless/types.js.map +1 -1
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +23 -14
  38. package/dist/index.js.map +1 -1
  39. package/dist/onboarding/settings.d.ts.map +1 -1
  40. package/dist/onboarding/settings.js +13 -1
  41. package/dist/onboarding/settings.js.map +1 -1
  42. package/dist/providers/google-vertex-gateway.d.ts +23 -0
  43. package/dist/providers/google-vertex-gateway.d.ts.map +1 -0
  44. package/dist/providers/google-vertex-gateway.js +51 -0
  45. package/dist/providers/google-vertex-gateway.js.map +1 -0
  46. package/dist/providers/google-vertex.d.ts +6 -0
  47. package/dist/providers/google-vertex.d.ts.map +1 -0
  48. package/dist/providers/google-vertex.js +53 -0
  49. package/dist/providers/google-vertex.js.map +1 -0
  50. package/package.json +17 -16
@@ -1,4 +1,5 @@
1
1
  import { loadSettings, resolveLspSetting } from "../../onboarding/settings.js";
2
+ import { resolveProviderWebSearchRoute } from "../model.js";
2
3
  import { buildModePrompt, buildModePromptFn } from "./build.js";
3
4
  import { getLocalPlansRelativeDir } from "../../utils/plans.js";
4
5
  import { planModePrompt } from "./plan.js";
@@ -32,18 +33,20 @@ function buildFullPrompt(ctx) {
32
33
  * these, so the two can never disagree about what the model receives.
33
34
  */
34
35
  function buildFullPromptSections(ctx) {
35
- const modelId = ctx.modelId;
36
- const hasWebSearch = hasParallelKey() || hasTavilyKey() || !!modelId && (modelId.startsWith("anthropic/") || modelId.startsWith("openai/"));
36
+ const hasWebExtract = hasParallelKey() || hasTavilyKey();
37
+ const hasWebSearch = hasWebExtract || resolveProviderWebSearchRoute(ctx.modelId, { requestContext: ctx.requestContext }) !== void 0;
37
38
  const deniedTools = /* @__PURE__ */ new Set();
38
39
  const permRules = ctx.state?.permissionRules;
39
40
  if (permRules?.tools) {
40
41
  for (const [name, policy] of Object.entries(permRules.tools)) if (policy === "deny") deniedTools.add(name);
41
42
  }
42
43
  for (const name of ctx.disabledBuiltinTools ?? []) deniedTools.add(name);
44
+ for (const name of ctx.disabledTools ?? []) deniedTools.add(name);
43
45
  if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);
44
46
  const factoryProjectId = typeof ctx.state?.factoryProjectId === "string" ? ctx.state.factoryProjectId : void 0;
45
47
  const toolGuidance = buildToolGuidance(ctx.modeId, {
46
48
  hasWebSearch,
49
+ hasWebExtract,
47
50
  hasSubagents: ctx.hasSubagents,
48
51
  deniedTools,
49
52
  plansDir: getLocalPlansRelativeDir({ factoryProjectId })
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport { loadSettings, resolveLspSetting } from '../../onboarding/settings.js';\nimport { MC_TOOLS } from '../../tool-names.js';\nimport { hasParallelKey, hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport { loadSessionInstructions, formatInstructionSource, AGENT_INSTRUCTIONS_HEADING } from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n hostInstructions?: string;\n /** Controller built-in tools removed via `disableBuiltinTools`; treated as denied. */\n disabledBuiltinTools?: readonly string[];\n /** Resolved in `buildFullPromptSections`; false when `submit_plan` is denied or disabled. */\n submitPlanAvailable?: boolean;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * One labeled piece of the assembled system prompt.\n *\n * The system prompt is a single string by the time it reaches the model, which\n * makes it impossible to say which configuration source is responsible for\n * which share of the context window. Building it as labeled sections and\n * joining them at the end keeps that attribution available to the `/context`\n * audit while guaranteeing the audit measures the exact text that is sent —\n * a parallel \"describe the prompt\" path would drift and report numbers for a\n * prompt that is no longer assembled this way.\n */\nexport interface PromptSection {\n /** Stable identifier, unique within a single build. */\n id: string;\n /** Human-readable label for display. */\n label: string;\n /** Optional provenance (e.g. the instruction file path). */\n detail?: string;\n /** The exact text contributed to the prompt. */\n content: string;\n}\n\n/** Join prompt sections into the final system prompt string. */\nexport function joinPromptSections(sections: PromptSection[]): string {\n return sections\n .map(section => section.content)\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n return joinPromptSections(buildFullPromptSections(ctx));\n}\n\n/**\n * Build the system prompt as labeled sections. `buildFullPrompt` is the join of\n * these, so the two can never disagree about what the model receives.\n */\nexport function buildFullPromptSections(ctx: PromptContext): PromptSection[] {\n // Determine whether web search tools are available\n const modelId = ctx.modelId;\n const hasWebSearch =\n hasParallelKey() ||\n hasTavilyKey() ||\n (!!modelId && (modelId.startsWith('anthropic/') || modelId.startsWith('openai/')));\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // Disabled built-ins are never registered, so they are denied for guidance too.\n for (const name of ctx.disabledBuiltinTools ?? []) deniedTools.add(name);\n\n // LSP is opt-in — when it is off the tool is never registered, so its\n // guidance must not be advertised either.\n if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);\n\n // Build mode-aware tool guidance\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const toolGuidance = buildToolGuidance(ctx.modeId, {\n hasWebSearch,\n hasSubagents: ctx.hasSubagents,\n deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir || '(no workspace attached)',\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n coAuthorName: ctx.coAuthorName,\n coAuthorEmail: ctx.coAuthorEmail,\n activePlan: ctx.state?.activePlan,\n hasSubagents: ctx.hasSubagents !== false && !deniedTools.has('subagent'),\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific =\n (typeof entry === 'function' ? entry({ ...ctx, submitPlanAvailable: !deniedTools.has('submit_plan') }) : entry) ??\n '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files.\n // Untrusted checkouts (e.g. a PR branch under review) never read\n // project-scope files off the working tree: their AGENTS.md is\n // attacker-writable and would otherwise land in the system prompt as\n // trusted configuration. When the session carries a trusted base ref, the\n // project instructions are served from that ref instead (`git show`);\n // without one, project-scope files are skipped entirely. Home-directory\n // (global) instructions belong to whoever owns the machine, so hosts that\n // run sessions for someone else opt out of them entirely.\n // A host booting several checkouts under one working directory names them\n // as `instructionRoots`, so each checkout's own files load.\n const configDir = ctx.state?.configDir as string | undefined;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const instructionRoots = Array.isArray(ctx.state?.instructionRoots)\n ? (ctx.state.instructionRoots as string[])\n : undefined;\n // No working directory means a hosted session with no project attached:\n // load NO instruction files at all — project locations would resolve\n // against the server's own cwd, and global locations against the server's\n // homedir. Neither belongs in a hosted session's prompt.\n const instructionSources = ctx.workingDir\n ? loadSessionInstructions({\n workingDir: ctx.workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout: ctx.state?.untrustedCheckout === true,\n baseRef,\n skipGlobal: ctx.state?.skipGlobalInstructions === true,\n })\n : [];\n // Emitted per source so each AGENTS.md/CLAUDE.md can be costed individually.\n // The heading rides on the first source's section, which is exactly how\n // `formatAgentInstructions` lays the block out, so joining the sections\n // reproduces its output byte for byte.\n const instructionSections: PromptSection[] = instructionSources.map((source, index) => {\n const isFirst = index === 0;\n const isLast = index === instructionSources.length - 1;\n let content = formatInstructionSource(source);\n if (isFirst) content = `${AGENT_INSTRUCTIONS_HEADING}\\n\\n${content}`;\n // The block as a whole used to be trimmed, which only ever affected the\n // trailing whitespace of the final source's content.\n if (isLast) content = content.trimEnd();\n return {\n id: `agent-instructions:${source.path}:${index}`,\n label: `${source.scope === 'global' ? 'Global' : 'Project'} instructions`,\n detail: source.ref ? `${source.path} (at ref ${source.ref})` : source.path,\n content,\n };\n });\n\n const hostInstructions = ctx.hostInstructions?.trim() ?? '';\n\n return [\n { id: 'base-prompt', label: 'Base system prompt', content: base },\n { id: 'host-instructions', label: 'Host instructions', content: hostInstructions },\n ...instructionSections,\n { id: 'model-prompt', label: 'Model-specific prompt', detail: ctx.modelId, content: modelSpecific.trim() },\n { id: 'mode-prompt', label: 'Mode prompt', detail: ctx.modeId, content: modeSpecific.trim() },\n ].filter(section => Boolean(section.content));\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;AAyBA,SAAgB,mBAAmB,UAAmC;CACpE,OAAO,SACJ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zG;GAAE,IAAI;GAAe,OAAO;GAAe,QAAQ,IAAI;GAAQ,SAAS,aAAa,KAAK;EAAE;CAC9F,CAAC,CAAC,QAAO,YAAW,QAAQ,QAAQ,OAAO,CAAC;AAC9C"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport type { RequestContextReader } from '../../auth/account-routing-context.js';\nimport { loadSettings, resolveLspSetting } from '../../onboarding/settings.js';\nimport { MC_TOOLS } from '../../tool-names.js';\nimport { hasParallelKey, hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport { resolveProviderWebSearchRoute } from '../model.js';\nimport { loadSessionInstructions, formatInstructionSource, AGENT_INSTRUCTIONS_HEADING } from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n hostInstructions?: string;\n /** Request whose credentials decide the model's transport, and so its web search tool. */\n requestContext?: RequestContextReader;\n /** Controller built-in tools removed via `disableBuiltinTools`; treated as denied. */\n disabledBuiltinTools?: readonly string[];\n /** Agent tools removed via `disabledTools` (e.g. `web_search`); treated as denied. */\n disabledTools?: readonly string[];\n /** Resolved in `buildFullPromptSections`; false when `submit_plan` is denied or disabled. */\n submitPlanAvailable?: boolean;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * One labeled piece of the assembled system prompt.\n *\n * The system prompt is a single string by the time it reaches the model, which\n * makes it impossible to say which configuration source is responsible for\n * which share of the context window. Building it as labeled sections and\n * joining them at the end keeps that attribution available to the `/context`\n * audit while guaranteeing the audit measures the exact text that is sent —\n * a parallel \"describe the prompt\" path would drift and report numbers for a\n * prompt that is no longer assembled this way.\n */\nexport interface PromptSection {\n /** Stable identifier, unique within a single build. */\n id: string;\n /** Human-readable label for display. */\n label: string;\n /** Optional provenance (e.g. the instruction file path). */\n detail?: string;\n /** The exact text contributed to the prompt. */\n content: string;\n}\n\n/** Join prompt sections into the final system prompt string. */\nexport function joinPromptSections(sections: PromptSection[]): string {\n return sections\n .map(section => section.content)\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n return joinPromptSections(buildFullPromptSections(ctx));\n}\n\n/**\n * Build the system prompt as labeled sections. `buildFullPrompt` is the join of\n * these, so the two can never disagree about what the model receives.\n */\nexport function buildFullPromptSections(ctx: PromptContext): PromptSection[] {\n // Determine whether web search tools are available\n // Parallel/Tavily register web_search and web_extract; provider search registers only web_search.\n const hasWebExtract = hasParallelKey() || hasTavilyKey();\n const hasWebSearch =\n hasWebExtract || resolveProviderWebSearchRoute(ctx.modelId, { requestContext: ctx.requestContext }) !== undefined;\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // Disabled built-ins are never registered, so they are denied for guidance too.\n for (const name of ctx.disabledBuiltinTools ?? []) deniedTools.add(name);\n // `createDynamicTools` drops disabled agent tools (such as web_search), so omit their guidance too.\n for (const name of ctx.disabledTools ?? []) deniedTools.add(name);\n\n // LSP is opt-in — when it is off the tool is never registered, so its\n // guidance must not be advertised either.\n if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);\n\n // Build mode-aware tool guidance\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const toolGuidance = buildToolGuidance(ctx.modeId, {\n hasWebSearch,\n hasWebExtract,\n hasSubagents: ctx.hasSubagents,\n deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir || '(no workspace attached)',\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n coAuthorName: ctx.coAuthorName,\n coAuthorEmail: ctx.coAuthorEmail,\n activePlan: ctx.state?.activePlan,\n hasSubagents: ctx.hasSubagents !== false && !deniedTools.has('subagent'),\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific =\n (typeof entry === 'function' ? entry({ ...ctx, submitPlanAvailable: !deniedTools.has('submit_plan') }) : entry) ??\n '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files.\n // Untrusted checkouts (e.g. a PR branch under review) never read\n // project-scope files off the working tree: their AGENTS.md is\n // attacker-writable and would otherwise land in the system prompt as\n // trusted configuration. When the session carries a trusted base ref, the\n // project instructions are served from that ref instead (`git show`);\n // without one, project-scope files are skipped entirely. Home-directory\n // (global) instructions belong to whoever owns the machine, so hosts that\n // run sessions for someone else opt out of them entirely.\n // A host booting several checkouts under one working directory names them\n // as `instructionRoots`, so each checkout's own files load.\n const configDir = ctx.state?.configDir as string | undefined;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const instructionRoots = Array.isArray(ctx.state?.instructionRoots)\n ? (ctx.state.instructionRoots as string[])\n : undefined;\n // No working directory means a hosted session with no project attached:\n // load NO instruction files at all — project locations would resolve\n // against the server's own cwd, and global locations against the server's\n // homedir. Neither belongs in a hosted session's prompt.\n const instructionSources = ctx.workingDir\n ? loadSessionInstructions({\n workingDir: ctx.workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout: ctx.state?.untrustedCheckout === true,\n baseRef,\n skipGlobal: ctx.state?.skipGlobalInstructions === true,\n })\n : [];\n // Emitted per source so each AGENTS.md/CLAUDE.md can be costed individually.\n // The heading rides on the first source's section, which is exactly how\n // `formatAgentInstructions` lays the block out, so joining the sections\n // reproduces its output byte for byte.\n const instructionSections: PromptSection[] = instructionSources.map((source, index) => {\n const isFirst = index === 0;\n const isLast = index === instructionSources.length - 1;\n let content = formatInstructionSource(source);\n if (isFirst) content = `${AGENT_INSTRUCTIONS_HEADING}\\n\\n${content}`;\n // The block as a whole used to be trimmed, which only ever affected the\n // trailing whitespace of the final source's content.\n if (isLast) content = content.trimEnd();\n return {\n id: `agent-instructions:${source.path}:${index}`,\n label: `${source.scope === 'global' ? 'Global' : 'Project'} instructions`,\n detail: source.ref ? `${source.path} (at ref ${source.ref})` : source.path,\n content,\n };\n });\n\n const hostInstructions = ctx.hostInstructions?.trim() ?? '';\n\n return [\n { id: 'base-prompt', label: 'Base system prompt', content: base },\n { id: 'host-instructions', label: 'Host instructions', content: hostInstructions },\n ...instructionSections,\n { id: 'model-prompt', label: 'Model-specific prompt', detail: ctx.modelId, content: modelSpecific.trim() },\n { id: 'mode-prompt', label: 'M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tE;EACF;CACF,CAAC;CAED,MAAM,mBAAmB,IAAI,kBAAkB,KAAK,KAAK;CAEzD,OAAO;EACL;GAAE,IAAI;GAAe,OAAO;GAAsB,SAAS;EAAK;EAChE;GAAE,IAAI;GAAqB,OAAO;GAAqB,SAAS;EAAiB;EACjF,GAAG;EACH;GAAE,IAAI;GAAgB,OAAO;GAAyB,QAAQ,IAAI;GAAS,SAAS,cAAc,KAAK;EAAE;EACzG;GAAE,IAAI;GAAe,OAAO;GAAe,QAAQ,IAAI;GAAQ,SAAS,aAAa,KAAK;EAAE;CAC9F,CAAC,CAAC,QAAO,YAAW,QAAQ,QAAQ,OAAO,CAAC;AAC9C"}
@@ -5,6 +5,8 @@
5
5
  */
6
6
  interface ToolGuidanceOptions {
7
7
  hasWebSearch?: boolean;
8
+ /** `web_extract` is registered (Parallel/Tavily); provider-executed search has no extract tool. */
9
+ hasWebExtract?: boolean;
8
10
  hasSubagents?: boolean;
9
11
  /** Tool names that have been denied — omit their guidance sections. */
10
12
  deniedTools?: Set<string>;
@@ -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,uEAAuE;IACvE,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,MAAM,CAgO3F"}
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,mGAAmG;IACnG,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uEAAuE;IACvE,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,MAAM,CAsO3F"}
@@ -80,10 +80,13 @@ You have access to the following tools. Use the RIGHT tool for the job:`);
80
80
  if (options.hasWebSearch) {
81
81
  const webTools = [];
82
82
  if (!denied.has("web_search")) webTools.push("**web_search**");
83
- if (!denied.has("web_extract")) webTools.push("**web_extract**");
84
- if (webTools.length > 0) sections.push(`
85
- ${webTools.join(" / ")} — Search the web / extract page content
83
+ if (options.hasWebExtract && !denied.has("web_extract")) webTools.push("**web_extract**");
84
+ if (webTools.length > 0) {
85
+ const purpose = webTools.length === 2 ? "Search the web / extract page content" : webTools[0] === "**web_search**" ? "Search the web" : "Extract page content";
86
+ sections.push(`
87
+ ${webTools.join(" / ")} — ${purpose}
86
88
  - Use for looking up documentation, error messages, package APIs.`);
89
+ }
87
90
  }
88
91
  const taskTools = [];
89
92
  const canUpdateTask = !denied.has("task_update");
@@ -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 /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const plansDir = options.plansDir ?? '.mastracode/plans';\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read file contents. Don't propose changes to code you haven't seen; reading with shell commands (cat, sed, rg) also works.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Always set \\`description\\` to a 5-10 word summary of what the command does; the user sees it instead of the raw command. Put it first in the arguments, before \\`command\\`, so the user sees it while the rest of the call streams in. Write each one as the next step in a running narrative that can lean on earlier commands (e.g. \"Searching open PRs for failing CI\", then \"Drilling into the first of 15 failures\").\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- Overwriting replaces the whole file, so make sure you know its current contents first.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (!denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n sections.push(`\n${webTools.join(' / ')} — Search the web / extract page content\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Task management tools (all modes) ---\n\n const taskTools: string[] = [];\n const canUpdateTask = !denied.has('task_update');\n const canCompleteTask = !denied.has('task_complete');\n const canCheckTasks = !denied.has('task_check');\n const canWriteTasks = !denied.has('task_write');\n const patchToolGuidance =\n canUpdateTask && canCompleteTask\n ? '- Prefer task_update or task_complete when changing one existing task.'\n : canUpdateTask\n ? '- Prefer task_update when changing one existing task.'\n : canCompleteTask\n ? '- Prefer task_complete when marking one existing task completed.'\n : '- Use task_write with the full task list when changing existing tasks.';\n\n if (canWriteTasks) {\n taskTools.push(`\n**task_write** — Track tasks for complex multi-step work\n- Use when a task requires 3 or more distinct steps or actions.\n- Use task_write to create the initial task list or replace the whole list after replanning.\n- Each task has: id (stable identifier), content (imperative form), status (pending, in_progress, or completed), activeForm (present continuous form shown during execution).\n- Keep task IDs stable across updates. If you omit IDs, the tool result returns generated IDs.\n${patchToolGuidance}\n- Mark tasks \\`in_progress\\` BEFORE starting work. Only ONE task should be \\`in_progress\\` at a time.\n- Mark tasks \\`completed\\` IMMEDIATELY after finishing each task. Do not batch completions.`);\n }\n\n if (canUpdateTask) {\n taskTools.push(`\n**task_update** — Patch one tracked task by ID\n- Use this for targeted changes to one existing task.\n- Provide the task ID and only the fields that changed: content, status, or activeForm.`);\n }\n\n if (canCompleteTask) {\n const idSource = canCheckTasks\n ? 'Use task_check if you need the current IDs before completing a task.'\n : canWriteTasks\n ? 'Use IDs returned by task_write.'\n : 'Use only task IDs already visible in the current task list.';\n taskTools.push(`\n**task_complete** — Mark one tracked task completed by ID\n- Use this immediately after finishing a tracked task.\n- ${idSource}`);\n }\n\n if (canCheckTasks) {\n taskTools.push(`\n**task_check** — Check completion status of tasks\n- Use this BEFORE finishing tracked work to verify all tasks are completed.\n- Returns a readable status summary plus structured fields: tasks, summary, incompleteTasks, and isError.\n- summary includes total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted.\n- Use summary.allCompleted to decide whether tracked work is complete; if summary.hasTasks is false, no task list is currently tracked.\n- If any tasks remain incomplete, continue working on them.\n- IMPORTANT: Always check task completion before ending work on a complex task.`);\n }\n\n if (!denied.has('ask_user')) {\n taskTools.push(`\n**ask_user** — Ask the user a structured question\n- Use when you need clarification, want to validate assumptions, or need the user to make a decision.\n- Provide clear, specific questions. End with a question mark.\n- Include options (2-4 choices) for structured decisions. Omit options for open-ended questions.\n- Don't use this for simple yes/no — just ask in your text response.`);\n }\n\n if (taskTools.length > 0) {\n sections.push(taskTools.join('\\n'));\n }\n\n // --- Plan tools (plan mode) ---\n\n if (modeId === 'plan' && !denied.has('submit_plan')) {\n sections.push(`\n**submit_plan** — Submit a completed implementation plan for user review\n- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.\n- The plan will be rendered as markdown and the user can approve, reject, or request changes.\n- On approval, the system automatically switches to the default mode so you can implement.\n- Takes one argument: \\`path\\` (the plan markdown file you wrote under \\`${plansDir}/\\`). Do NOT pass the plan body — it lives in the file.`);\n }\n\n if (modeId === 'plan') {\n sections.push(`\n**Plan file access** — Your plan lives in a markdown file under \\`${plansDir}/\\` (e.g. \\`add-dark-mode-toggle.md\\`)\n- Use \\`write_file\\` to create the plan file, \\`view\\` to read it, and \\`string_replace_lsp\\` for targeted edits.\n- On first submission: write the plan to the file, then call \\`submit_plan\\` with its \\`path\\`.\n- On revision: read the existing file, edit specific sections, re-read, then call \\`submit_plan\\` with the same \\`path\\`.\n- If a plan file already exists, you previously submitted it — read it before revising.`);\n }\n\n // --- Subagent tool (all modes) ---\n\n if (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":";;;;;;;AAiBA,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,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AAK,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 /** `web_extract` is registered (Parallel/Tavily); provider-executed search has no extract tool. */\n hasWebExtract?: boolean;\n hasSubagents?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const plansDir = options.plansDir ?? '.mastracode/plans';\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read file contents. Don't propose changes to code you haven't seen; reading with shell commands (cat, sed, rg) also works.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Always set \\`description\\` to a 5-10 word summary of what the command does; the user sees it instead of the raw command. Put it first in the arguments, before \\`command\\`, so the user sees it while the rest of the call streams in. Write each one as the next step in a running narrative that can lean on earlier commands (e.g. \"Searching open PRs for failing CI\", then \"Drilling into the first of 15 failures\").\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- Overwriting replaces the whole file, so make sure you know its current contents first.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (options.hasWebExtract && !denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n const purpose =\n webTools.length === 2\n ? 'Search the web / extract page content'\n : webTools[0] === '**web_search**'\n ? 'Search the web'\n : 'Extract page content';\n sections.push(`\n${webTools.join(' / ')} — ${purpose}\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Task management tools (all modes) ---\n\n const taskTools: string[] = [];\n const canUpdateTask = !denied.has('task_update');\n const canCompleteTask = !denied.has('task_complete');\n const canCheckTasks = !denied.has('task_check');\n const canWriteTasks = !denied.has('task_write');\n const patchToolGuidance =\n canUpdateTask && canCompleteTask\n ? '- Prefer task_update or task_complete when changing one existing task.'\n : canUpdateTask\n ? '- Prefer task_update when changing one existing task.'\n : canCompleteTask\n ? '- Prefer task_complete when marking one existing task completed.'\n : '- Use task_write with the full task list when changing existing tasks.';\n\n if (canWriteTasks) {\n taskTools.push(`\n**task_write** — Track tasks for complex multi-step work\n- Use when a task requires 3 or more distinct steps or actions.\n- Use task_write to create the initial task list or replace the whole list after replanning.\n- Each task has: id (stable identifier), content (imperative form), status (pending, in_progress, or completed), activeForm (present continuous form shown during execution).\n- Keep task IDs stable across updates. If you omit IDs, the tool result returns generated IDs.\n${patchToolGuidance}\n- Mark tasks \\`in_progress\\` BEFORE starting work. Only ONE task should be \\`in_progress\\` at a time.\n- Mark tasks \\`completed\\` IMMEDIATELY after finishing each task. Do not batch completions.`);\n }\n\n if (canUpdateTask) {\n taskTools.push(`\n**task_update** — Patch one tracked task by ID\n- Use this for targeted changes to one existing task.\n- Provide the task ID and only the fields that changed: content, status, or activeForm.`);\n }\n\n if (canCompleteTask) {\n const idSource = canCheckTasks\n ? 'Use task_check if you need the current IDs before completing a task.'\n : canWriteTasks\n ? 'Use IDs returned by task_write.'\n : 'Use only task IDs already visible in the current task list.';\n taskTools.push(`\n**task_complete** — Mark one tracked task completed by ID\n- Use this immediately after finishing a tracked task.\n- ${idSource}`);\n }\n\n if (canCheckTasks) {\n taskTools.push(`\n**task_check** — Check completion status of tasks\n- Use this BEFORE finishing tracked work to verify all tasks are completed.\n- Returns a readable status summary plus structured fields: tasks, summary, incompleteTasks, and isError.\n- summary includes total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted.\n- Use summary.allCompleted to decide whether tracked work is complete; if summary.hasTasks is false, no task list is currently tracked.\n- If any tasks remain incomplete, continue working on them.\n- IMPORTANT: Always check task completion before ending work on a complex task.`);\n }\n\n if (!denied.has('ask_user')) {\n taskTools.push(`\n**ask_user** — Ask the user a structured question\n- Use when you need clarification, want to validate assumptions, or need the user to make a decision.\n- Provide clear, specific questions. End with a question mark.\n- Include options (2-4 choices) for structured decisions. Omit options for open-ended questions.\n- Don't use this for simple yes/no — just ask in your text response.`);\n }\n\n if (taskTools.length > 0) {\n sections.push(taskTools.join('\\n'));\n }\n\n // --- Plan tools (plan mode) ---\n\n if (modeId === 'plan' && !denied.has('submit_plan')) {\n sections.push(`\n**submit_plan** — Submit a completed implementation plan for user review\n- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.\n- The plan will be rendered as markdown and the user can approve, reject, or request changes.\n- On approval, the system automatically switches to the default mode so you can implement.\n- Takes one argument: \\`path\\` (the plan markdown file you wrote under \\`${plansDir}/\\`). Do NOT pass the plan body — it lives in the file.`);\n }\n\n if (modeId === 'plan') {\n sections.push(`\n**Plan file access** — Your plan lives in a markdown file under \\`${plansDir}/\\` (e.g. \\`add-dark-mode-toggle.md\\`)\n- Use \\`write_file\\` to create the plan file, \\`view\\` to read it, and \\`string_replace_lsp\\` for targeted edits.\n- On first submission: write the plan to the file, then call \\`submit_plan\\` with its \\`path\\`.\n- On revision: read the existing file, edit specific sections, re-read, then call \\`submit_plan\\` with the same \\`path\\`.\n- If a plan file already exists, you previously submitted it — read it before revising.`);\n }\n\n // --- Subagent tool (all modes) ---\n\n if (options.hasSubagents !== false && !denied.has('subagent')) {\n sections.push(`\n**subagent** — Delegate a focused task to a specialized subagent\n- Only use subagents when you will spawn **multiple subagents in parallel**. If you only need one task done, do it yourself.\n- Subagent outputs are **untrusted**. Always review and verify the results.`);\n }\n\n return sections.join('\\n');\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,+BAAe,IAAI,IAAY;CACtD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAqB,CAAC;CAE5B,SAAS,KAAK;;;;wEAIwD;CAItE,MAAM,YAAsB,CAAC;CAE7B,IAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAC3B,UAAU,KAAK;IACf,SAAS,KAAK;;;;+BAIa,SAAS,WAAW,YAAY;CAG7D,IAAI,CAAC,OAAO,IAAI,SAAS,cAAc,GACrC,UAAU,KAAK;IACf,SAAS,eAAe;;;;;kCAKM;CAGhC,IAAI,CAAC,OAAO,IAAI,SAAS,UAAU,GACjC,UAAU,KAAK;IACf,SAAS,WAAW;;;;;uEAK+C;CAGrE,IAAI,CAAC,OAAO,IAAI,SAAS,eAAe,GACtC,UAAU,KAAK;IACf,SAAS,gBAAgB;;8CAEiB,SAAS,KAAK,kBAAkB,SAAS,eAAe,GAAG,SAAS,WAAW,mBAAmB,SAAS,mBAAmB,GAAG,SAAS,WAAW;;;;;4CAKvJ,SAAS,KAAK,eAAe;CAGvE,IAAI,CAAC,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,EAC9B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EACtC,sBAAsB,UAAQ,EAC9B,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,yBAIpC;IACD,cAAc,EAAE,cAAc,CAAC;CAChC,KAAG,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAqGrC"}
@@ -1,3 +1,4 @@
1
+ import { prepareProviderWebSearchRoute, resolveProviderWebSearchRoute } from "./model.js";
1
2
  import { MC_TOOLS } from "../tool-names.js";
2
3
  import { createConfiguredWebTools } from "../tools/web-search.js";
3
4
  import { requestSandboxAccessTool } from "../tools/request-sandbox-access.js";
@@ -9,6 +10,7 @@ import { listWorkflowsTool } from "../tools/workflows/list-workflows.js";
9
10
  import { runWorkflowTool } from "../tools/workflows/run-workflow.js";
10
11
  import { WORKFLOW_MANAGEMENT_TOOL_IDS } from "../tools/workflows/tool-ids.js";
11
12
  import { createOpenAI } from "@ai-sdk/openai";
13
+ import { jsonSchema } from "ai";
12
14
  import { NotificationsStorage, createNotificationInboxTool } from "@mastra/core/notifications";
13
15
  import { createAnthropic } from "@ai-sdk/anthropic";
14
16
  // src/agents/tools.ts
@@ -78,13 +80,34 @@ function createToolHooks(hookManager, postToolObserver) {
78
80
  }
79
81
  };
80
82
  }
83
+ /**
84
+ * The provider-executed search tool for a route. The Mastra gateway's OpenRouter
85
+ * chat endpoint takes `openrouter:web_search` (the OpenRouter provider sends a
86
+ * provider tool `openrouter.web_search` with that type), as Mastra's own
87
+ * templates use against the gateway.
88
+ */
89
+ function createProviderWebSearchTool(route) {
90
+ switch (route) {
91
+ case "anthropic": return createAnthropic({}).tools.webSearch_20250305();
92
+ case "openai": return createOpenAI({}).tools.webSearch();
93
+ case "mastra-gateway": return {
94
+ type: "provider",
95
+ id: "openrouter.web_search",
96
+ args: {},
97
+ inputSchema: jsonSchema({
98
+ type: "object",
99
+ properties: {}
100
+ })
101
+ };
102
+ }
103
+ }
81
104
  function createDynamicTools(mcpManager, extraTools, disabledTools, storage, pluginTools, backgroundToolsEnabled = false, builtinTools) {
82
105
  return function getDynamicTools({ requestContext }) {
83
106
  const ctx = requestContext.get("controller");
84
107
  const state = ctx?.getState();
85
- const modelId = ctx?.session?.modelId;
86
- const isAnthropicModel = modelId?.startsWith("anthropic/");
87
- const isOpenAIModel = modelId?.startsWith("openai/");
108
+ const preparing = prepareProviderWebSearchRoute(ctx?.session?.modelId, { requestContext });
109
+ if (preparing) return preparing.then(() => getDynamicTools({ requestContext }));
110
+ const webSearchRoute = resolveProviderWebSearchRoute(ctx?.session?.modelId, { requestContext });
88
111
  const tools = {
89
112
  request_access: requestSandboxAccessTool,
90
113
  [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,
@@ -96,10 +119,7 @@ function createDynamicTools(mcpManager, extraTools, disabledTools, storage, plug
96
119
  if (builtinTools) Object.assign(tools, builtinTools);
97
120
  if (storage) tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({ storage: new LazyNotificationsStorage(storage) });
98
121
  const configuredWebTools = createConfiguredWebTools();
99
- if (!configuredWebTools) {
100
- if (isAnthropicModel) tools.web_search = createAnthropic({}).tools.webSearch_20250305();
101
- else if (isOpenAIModel) tools.web_search = createOpenAI({}).tools.webSearch();
102
- }
122
+ if (!configuredWebTools && webSearchRoute) tools.web_search = createProviderWebSearchTool(webSearchRoute);
103
123
  const mcpTools = mcpManager?.getTools();
104
124
  if (mcpTools) Object.assign(tools, mcpTools);
105
125
  const finish = (resolvedExtra) => {
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../src/agents/tools.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n UpdateNotificationsStatusInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createConfiguredWebTools, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nfunction configurePluginTool(tool: ToolLike, backgroundToolsEnabled: boolean): ToolLike {\n if (backgroundToolsEnabled || !tool.background) return tool;\n return { ...tool, background: { ...tool.background, enabled: false } };\n}\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n override async updateNotificationsStatus(input: UpdateNotificationsStatusInput) {\n return (await this.getNotificationsStorage()).updateNotificationsStatus(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n backgroundToolsEnabled = false,\n builtinTools?: Record<string, ToolLike>,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): ToolsInput | Promise<ToolsInput> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n const modelId = ctx?.session?.modelId;\n const isAnthropicModel = modelId?.startsWith('anthropic/');\n const isOpenAIModel = modelId?.startsWith('openai/');\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n // Opt-in built-ins (e.g. the experimental schedule tools).\n if (builtinTools) Object.assign(tools, builtinTools);\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n // Async only when a Tavily/Parallel key is set; otherwise the tool list stays synchronous.\n const configuredWebTools = createConfiguredWebTools();\n if (!configuredWebTools) {\n if (isAnthropicModel) {\n const anthropic = createAnthropic({});\n tools.web_search = anthropic.tools.webSearch_20250305();\n } else if (isOpenAIModel) {\n const openai = createOpenAI({});\n tools.web_search = openai.tools.webSearch();\n }\n }\n\n const mcpTools = mcpManager?.getTools();\n if (mcpTools) Object.assign(tools, mcpTools);\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = configurePluginTool(tool, backgroundToolsEnabled);\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools as ToolsInput;\n };\n\n const resolveExtra = (): ToolsInput | Promise<ToolsInput> => {\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.resolve(resolved).then(finish);\n }\n return finish(resolved as Record<string, ToolLike | undefined>);\n }\n return finish(extraTools);\n };\n\n if (configuredWebTools) {\n return configuredWebTools.then(webTools => {\n // MCP tools keep precedence over the web tools, as when both were assigned in order.\n Object.assign(tools, webTools, mcpTools);\n return resolveExtra();\n });\n }\n\n return resolveExtra();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,SAAS,oBAAoB,MAAgB,wBAA2C;CACtF,IAAI,0BAA0B,CAAC,KAAK,YAAY,OAAO;CACvD,OAAO;EAAE,GAAG;EAAM,YAAY;GAAE,GAAG,KAAK;GAAY,SAAS;EAAM;CAAE;AACvE;AAEA,IAAa,2BAAb,cAA8C,qBAAqB;CACpC;CAA7B,YAAY,SAAgD;EAC1D,MAAM;EADqB,KAAA,UAAA;CAE7B;CAEA,MAAc,0BAAyD;EACrE,MAAM,gBAAgB,MAAM,KAAK,QAAQ,SAAS,eAAe;EACjE,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,4DAA4D;EAE9E,OAAO;CACT;CAEA,MAAM,mBAAmB,OAAgC;EACvD,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AQ,QACZ,MAAM,QAAQ,oBAAoB,MAAM,sBAAsB;GAAA;GAMpE,IAAI,eAAe,QACjB,KAAK,MAAM,YAAY,eACrB,OAAO,MAAM;GAKjB,MAAM,kBAAkB,OAAO;GAC/B,IAAI,iBAAiB,OACd;SAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,gBAAgB,KAAK,GAC/D,IAAI,WAAW,QACb,OAAO,MAAM;GAAA;GAKnB,OAAO;EACT;EAEA,MAAM,qBAAuD;GAC3D,IAAI,OAAO,eAAe,YAAY;IACpC,MAAM,WAAW,WAAW,EAAE,eAAe,CAAC;IAE9C,IAAI,YAAY,OAAQ,SAAkC,SAAS,YACjE,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,KAAK,MAAM;IAE9C,OAAO,OAAO,QAAgD;GAChE;GACA,OAAO,OAAO,UAAU;EAC1B;EAEA,IAAI,oBACF,OAAO,mBAAmB,MAAK,aAAY;GAEzC,OAAO,OAAO,OAAO,UAAU,QAAQ;GACvC,OAAO,aAAa;EACtB,CAAC;EAGH,OAAO,aAAa;CACtB;AACF"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../src/agents/tools.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n UpdateNotificationsStatusInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport { jsonSchema } from 'ai';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createConfiguredWebTools, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\nimport { prepareProviderWebSearchRoute, resolveProviderWebSearchRoute } from './model.js';\nimport type { ProviderWebSearchRoute } from './model.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nfunction configurePluginTool(tool: ToolLike, backgroundToolsEnabled: boolean): ToolLike {\n if (backgroundToolsEnabled || !tool.background) return tool;\n return { ...tool, background: { ...tool.background, enabled: false } };\n}\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n override async updateNotificationsStatus(input: UpdateNotificationsStatusInput) {\n return (await this.getNotificationsStorage()).updateNotificationsStatus(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\n/**\n * The provider-executed search tool for a route. The Mastra gateway's OpenRouter\n * chat endpoint takes `openrouter:web_search` (the OpenRouter provider sends a\n * provider tool `openrouter.web_search` with that type), as Mastra's own\n * templates use against the gateway.\n */\nfunction createProviderWebSearchTool(route: ProviderWebSearchRoute): ToolLike {\n switch (route) {\n case 'anthropic':\n return createAnthropic({}).tools.webSearch_20250305();\n case 'openai':\n return createOpenAI({}).tools.webSearch();\n case 'mastra-gateway':\n return {\n type: 'provider',\n id: 'openrouter.web_search',\n args: {},\n inputSchema: jsonSchema({ type: 'object', properties: {} }),\n } as unknown as ToolLike;\n }\n}\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n backgroundToolsEnabled = false,\n builtinTools?: Record<string, ToolLike>,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): ToolsInput | Promise<ToolsInput> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n // In deployed Factory, the search route reads tenant credentials; prepare them first if needed.\n const preparing = prepareProviderWebSearchRoute(ctx?.session?.modelId, { requestContext });\n if (preparing) return preparing.then(() => getDynamicTools({ requestContext }));\n const webSearchRoute = resolveProviderWebSearchRoute(ctx?.session?.modelId, { requestContext });\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n // Opt-in built-ins (e.g. the experimental schedule tools).\n if (builtinTools) Object.assign(tools, builtinTools);\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n // Async only when a Tavily/Parallel key is set; otherwise the tool list stays synchronous.\n const configuredWebTools = createConfiguredWebTools();\n if (!configuredWebTools && webSearchRoute) {\n tools.web_search = createProviderWebSearchTool(webSearchRoute);\n }\n\n const mcpTools = mcpManager?.getTools();\n if (mcpTools) Object.assign(tools, mcpTools);\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = configurePluginTool(tool, backgroundToolsEnabled);\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools as ToolsInput;\n };\n\n const resolveExtra = (): ToolsInput | Promise<ToolsInput> => {\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.resolve(resolved).then(finish);\n }\n return finish(resolved as Record<string, ToolLike | undefined>);\n }\n return finish(extraTools);\n };\n\n if (configuredWebTools) {\n return configuredWebTools.then(webTools => {\n // MCP tools keep precedence over the web tools, as when both were assigned in order.\n Object.assign(tools, webTools, mcpTools);\n return resolveExtra();\n });\n }\n\n return resolveExtra();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmCA,SAAS,oBAAoB,MAAgB,wBAA2C;CACtF,IAAI,0BAA0B,CAAC,KAAK,YAAY,OAAO;CACvD,OAAO;EAAE,GAAG;EAAM,YAAY;GAAE,GAAG,KAAK;GAAY,SAAS;EAAM;CAAE;AACvE;AAEA,IAAa,2BAAb,cAA8C,qBAAqB;CACpC;CAA7B,YAAY,SAAgD;EAC1D,MAAM;EADqB,KAAA,UAAA;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equestAccountSelection(requestContext: RequestContext | undefined, providerId: string): string | undefined;
2
+ /** The read-only view of a request context that credential and account lookups need. */
3
+ export type RequestContextReader = {
4
+ get(key: string): unknown;
5
+ };
6
+ export declare function getRequestAccountSelection(requestContext: RequestContextReader | undefined, providerId: string): string | undefined;
3
7
  export declare function setRequestAccountSelection(requestContext: RequestContext | undefined, providerId: string, accountInstanceId: string): void;
4
8
  /**
5
9
  * Record that routing found no usable account for this provider on this
@@ -9,5 +13,5 @@ export declare function setRequestAccountSelection(requestContext: RequestContex
9
13
  */
10
14
  export declare function markRequestAccountRoutingExhausted(requestContext: RequestContext | undefined, providerId: string): void;
11
15
  /** Whether routing already rejected every account for this provider on this request. */
12
- export declare function isRequestAccountRoutingExhausted(requestContext: RequestContext | undefined, providerId: string): boolean;
16
+ export declare function isRequestAccountRoutingExhausted(requestContext: RequestContextReader | undefined, providerId: string): boolean;
13
17
  //# sourceMappingURL=account-routing-context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"account-routing-context.d.ts","sourceRoot":"","sources":["../../src/auth/account-routing-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAWnE,wBAAgB,0BAA0B,CAAC,cAAc,EAAE,cAAc,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,sBAExG;AAED,wBAAgB,0BAA0B,CACxC,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,EAClB,iBAAiB,EAAE,MAAM,GACxB,IAAI,CAMN;AASD;;;;;GAKG;AACH,wBAAgB,kCAAkC,CAChD,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,GACjB,IAAI,CAKN;AAED,wFAAwF;AACxF,wBAAgB,gCAAgC,CAC9C,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,GACjB,OAAO,CAET"}
1
+ {"version":3,"file":"account-routing-context.d.ts","sourceRoot":"","sources":["../../src/auth/account-routing-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,wFAAwF;AACxF,MAAM,MAAM,oBAAoB,GAAG;IAAE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAC;AAWjE,wBAAgB,0BAA0B,CAAC,cAAc,EAAE,oBAAoB,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,sBAE9G;AAED,wBAAgB,0BAA0B,CACxC,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,EAClB,iBAAiB,EAAE,MAAM,GACxB,IAAI,CAMN;AASD;;;;;GAKG;AACH,wBAAgB,kCAAkC,CAChD,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,UAAU,EAAE,MAAM,GACjB,IAAI,CAKN;AAED,wFAAwF;AACxF,wBAAgB,gCAAgC,CAC9C,cAAc,EAAE,oBAAoB,GAAG,SAAS,EAChD,UAAU,EAAE,MAAM,GACjB,OAAO,CAET"}
@@ -1 +1 @@
1
- {"version":3,"file":"account-routing-context.js","names":[],"sources":["../../src/auth/account-routing-context.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\n\nconst ACCOUNT_ROUTING_SELECTIONS_KEY = 'mastracodeAccountRoutingSelections';\n\ntype AccountRoutingSelections = Record<string, string>;\n\nfunction getSelections(requestContext?: RequestContext): AccountRoutingSelections | undefined {\n const value = requestContext?.get(ACCOUNT_ROUTING_SELECTIONS_KEY);\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as AccountRoutingSelections) : undefined;\n}\n\nexport function getRequestAccountSelection(requestContext: RequestContext | undefined, providerId: string) {\n return getSelections(requestContext)?.[providerId];\n}\n\nexport function setRequestAccountSelection(\n requestContext: RequestContext | undefined,\n providerId: string,\n accountInstanceId: string,\n): void {\n if (!requestContext || typeof requestContext.set !== 'function') return;\n requestContext.set(ACCOUNT_ROUTING_SELECTIONS_KEY, {\n ...getSelections(requestContext),\n [providerId]: accountInstanceId,\n });\n}\n\nconst ACCOUNT_ROUTING_EXHAUSTED_KEY = 'mastracodeAccountRoutingExhaustedProviders';\n\nfunction getExhaustedProviders(requestContext?: RequestContext): string[] {\n const value = requestContext?.get(ACCOUNT_ROUTING_EXHAUSTED_KEY);\n return Array.isArray(value) ? (value as string[]) : [];\n}\n\n/**\n * Record that routing found no usable account for this provider on this\n * request. Kept separate from the account selection: a sentinel *id* would be\n * handed to credential lookup, where an unknown id makes `get()` fall back to\n * the provider's active account — the very account routing just rejected.\n */\nexport function markRequestAccountRoutingExhausted(\n requestContext: RequestContext | undefined,\n providerId: string,\n): void {\n if (!requestContext || typeof requestContext.set !== 'function') return;\n const exhausted = getExhaustedProviders(requestContext);\n if (exhausted.includes(providerId)) return;\n requestContext.set(ACCOUNT_ROUTING_EXHAUSTED_KEY, [...exhausted, providerId]);\n}\n\n/** Whether routing already rejected every account for this provider on this request. */\nexport function isRequestAccountRoutingExhausted(\n requestContext: RequestContext | undefined,\n providerId: string,\n): boolean {\n return getExhaustedProviders(requestContext).includes(providerId);\n}\n"],"mappings":";AAEA,MAAM,iCAAiC;AAIvC,SAAS,cAAc,gBAAuE;CAC5F,MAAM,QAAQ,gBAAgB,IAAI,8BAA8B;CAChE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAqC,KAAA;AAC7G;AAEA,SAAgB,2BAA2B,gBAA4C,YAAoB;CACzG,OAAO,cAAc,cAAc,CAAC,GAAG;AACzC;AAEA,SAAgB,2BACd,gBACA,YACA,mBACM;CACN,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY;CACjE,eAAe,IAAI,gCAAgC;EACjD,GAAG,cAAc,cAAc;GAC9B,aAAa;CAChB,CAAC;AACH;AAEA,MAAM,gCAAgC;AAEtC,SAAS,sBAAsB,gBAA2C;CACxE,MAAM,QAAQ,gBAAgB,IAAI,6BAA6B;CAC/D,OAAO,MAAM,QAAQ,KAAK,IAAK,QAAqB,CAAC;AACvD;;;;;;;AAQA,SAAgB,mCACd,gBACA,YACM;CACN,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY;CACjE,MAAM,YAAY,sBAAsB,cAAc;CACtD,IAAI,UAAU,SAAS,UAAU,GAAG;CACpC,eAAe,IAAI,+BAA+B,CAAC,GAAG,WAAW,UAAU,CAAC;AAC9E;;AAGA,SAAgB,iCACd,gBACA,YACS;CACT,OAAO,sBAAsB,cAAc,CAAC,CAAC,SAAS,UAAU;AAClE"}
1
+ {"version":3,"file":"account-routing-context.js","names":[],"sources":["../../src/auth/account-routing-context.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\n\n/** The read-only view of a request context that credential and account lookups need. */\nexport type RequestContextReader = { get(key: string): unknown };\n\nconst ACCOUNT_ROUTING_SELECTIONS_KEY = 'mastracodeAccountRoutingSelections';\n\ntype AccountRoutingSelections = Record<string, string>;\n\nfunction getSelections(requestContext?: RequestContextReader): AccountRoutingSelections | undefined {\n const value = requestContext?.get(ACCOUNT_ROUTING_SELECTIONS_KEY);\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as AccountRoutingSelections) : undefined;\n}\n\nexport function getRequestAccountSelection(requestContext: RequestContextReader | undefined, providerId: string) {\n return getSelections(requestContext)?.[providerId];\n}\n\nexport function setRequestAccountSelection(\n requestContext: RequestContext | undefined,\n providerId: string,\n accountInstanceId: string,\n): void {\n if (!requestContext || typeof requestContext.set !== 'function') return;\n requestContext.set(ACCOUNT_ROUTING_SELECTIONS_KEY, {\n ...getSelections(requestContext),\n [providerId]: accountInstanceId,\n });\n}\n\nconst ACCOUNT_ROUTING_EXHAUSTED_KEY = 'mastracodeAccountRoutingExhaustedProviders';\n\nfunction getExhaustedProviders(requestContext?: RequestContextReader): string[] {\n const value = requestContext?.get(ACCOUNT_ROUTING_EXHAUSTED_KEY);\n return Array.isArray(value) ? (value as string[]) : [];\n}\n\n/**\n * Record that routing found no usable account for this provider on this\n * request. Kept separate from the account selection: a sentinel *id* would be\n * handed to credential lookup, where an unknown id makes `get()` fall back to\n * the provider's active account — the very account routing just rejected.\n */\nexport function markRequestAccountRoutingExhausted(\n requestContext: RequestContext | undefined,\n providerId: string,\n): void {\n if (!requestContext || typeof requestContext.set !== 'function') return;\n const exhausted = getExhaustedProviders(requestContext);\n if (exhausted.includes(providerId)) return;\n requestContext.set(ACCOUNT_ROUTING_EXHAUSTED_KEY, [...exhausted, providerId]);\n}\n\n/** Whether routing already rejected every account for this provider on this request. */\nexport function isRequestAccountRoutingExhausted(\n requestContext: RequestContextReader | undefined,\n providerId: string,\n): boolean {\n return getExhaustedProviders(requestContext).includes(providerId);\n}\n"],"mappings":";AAKA,MAAM,iCAAiC;AAIvC,SAAS,cAAc,gBAA6E;CAClG,MAAM,QAAQ,gBAAgB,IAAI,8BAA8B;CAChE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAqC,KAAA;AAC7G;AAEA,SAAgB,2BAA2B,gBAAkD,YAAoB;CAC/G,OAAO,cAAc,cAAc,CAAC,GAAG;AACzC;AAEA,SAAgB,2BACd,gBACA,YACA,mBACM;CACN,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY;CACjE,eAAe,IAAI,gCAAgC;EACjD,GAAG,cAAc,cAAc;GAC9B,aAAa;CAChB,CAAC;AACH;AAEA,MAAM,gCAAgC;AAEtC,SAAS,sBAAsB,gBAAiD;CAC9E,MAAM,QAAQ,gBAAgB,IAAI,6BAA6B;CAC/D,OAAO,MAAM,QAAQ,KAAK,IAAK,QAAqB,CAAC;AACvD;;;;;;;AAQA,SAAgB,mCACd,gBACA,YACM;CACN,IAAI,CAAC,kBAAkB,OAAO,eAAe,QAAQ,YAAY;CACjE,MAAM,YAAY,sBAAsB,cAAc;CACtD,IAAI,UAAU,SAAS,UAAU,GAAG;CACpC,eAAe,IAAI,+BAA+B,CAAC,GAAG,WAAW,UAAU,CAAC;AAC9E;;AAGA,SAAgB,iCACd,gBACA,YACS;CACT,OAAO,sBAAsB,cAAc,CAAC,CAAC,SAAS,UAAU;AAClE"}
@@ -1 +1 @@
1
- {"version":3,"file":"flags.d.ts","sourceRoot":"","sources":["../../src/headless/flags.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,aAAa,YAAI,OAAO,EAAE,MAAM,EAAE,OAAO,CAAU,CAAC;AA6BjE;;;;;GAKG;AACH,MAAM,WAAW,QAAQ;IACvB,+CAA+C;IAC/C,GAAG,EAAE,MAAM,CAAC;IACZ,gEAAgE;IAChE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,sFAAsF;IACtF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+FAA+F;IAC/F,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;IAClC,+DAA+D;IAC/D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gEAAgE;IAChE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACzB;AAED,eAAO,MAAM,KAAK,EAAE,QAAQ,EA+I3B,CAAC;AAEF,4DAA4D;AAC5D,wBAAgB,qBAAqB;UACG,QAAQ,GAAG,SAAS;YAAU,MAAM;cAAY,OAAO;GAM9F;AAED,2FAA2F;AAC3F,wBAAgB,eAAe,IAAI,MAAM,CAmBxC"}
1
+ {"version":3,"file":"flags.d.ts","sourceRoot":"","sources":["../../src/headless/flags.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,aAAa,YAAI,OAAO,EAAE,MAAM,EAAE,OAAO,CAAU,CAAC;AA6BjE;;;;;GAKG;AACH,MAAM,WAAW,QAAQ;IACvB,+CAA+C;IAC/C,GAAG,EAAE,MAAM,CAAC;IACZ,gEAAgE;IAChE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,sFAAsF;IACtF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+FAA+F;IAC/F,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;IAClC,+DAA+D;IAC/D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gEAAgE;IAChE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACzB;AAED,eAAO,MAAM,KAAK,EAAE,QAAQ,EAqJ3B,CAAC;AAEF,4DAA4D;AAC5D,wBAAgB,qBAAqB;UACG,QAAQ,GAAG,SAAS;YAAU,MAAM;cAAY,OAAO;GAM9F;AAED,2FAA2F;AAC3F,wBAAgB,eAAe,IAAI,MAAM,CAmBxC"}
@@ -169,6 +169,12 @@ const FLAGS = [
169
169
  short: "h",
170
170
  type: "boolean",
171
171
  help: "Show this help and exit"
172
+ },
173
+ {
174
+ key: "version",
175
+ short: "v",
176
+ type: "boolean",
177
+ help: "Print the Mastra Code version and exit"
172
178
  }
173
179
  ];
174
180
  /** `parseArgs` option config derived from {@link FLAGS}. */
@@ -1 +1 @@
1
- {"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ' (omits display_state_changed UI snapshots)',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id); wins over --pack for the active mode',\n },\n {\n key: 'pack',\n type: 'string',\n field: 'pack',\n coerce: validate.string,\n placeholder: '<id>',\n help: [\n 'Model pack to activate (like /models → Activate): a builtin pack id',\n '(anthropic, openai, github-copilot) or a saved custom pack, by',\n '\"custom:<name>\" or its bare name. Sets the pack for every mode and',\n 'becomes the global default pack. --model overrides it for the active mode.',\n ],\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,I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O,CAAC,KAAK,IAAI;EAG/D,OAAO,CAAC,GAFS,MAAM,OAAO,KAAK,IAAI,MAAM,MAE9B,GADF,MAAM,MAAM,CAAC,CAAC,CAAC,KAAI,SAAQ,GAAG,IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
1
+ {"version":3,"file":"flags.js","names":[],"sources":["../../src/headless/flags.ts"],"sourcesContent":["/**\n * Declarative flag specification for the headless CLI.\n *\n * A single table is the source of truth for three things that previously drifted\n * apart in `cli.ts`:\n * 1. the `node:util` `parseArgs` option config,\n * 2. per-flag value coercion + validation, and\n * 3. the `--help` usage text.\n *\n * Adding a flag means adding one row here; parsing, validation, and the usage\n * listing all follow automatically.\n */\nimport type { OutputMode } from './cli.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\nimport { VALID_MODES, VALID_PERMISSION_MODES, VALID_THINKING_LEVELS } from './types.js';\n\nexport const VALID_OUTPUTS = ['human', 'json', 'jsonl'] as const;\n\n/** Reusable validators. Each throws a descriptive Error or returns the typed value. */\nconst validate = {\n /** Restrict to a fixed set of string literals. */\n enum<T extends string>(flag: string, allowed: readonly T[]) {\n return (raw: string): T => {\n if (!(allowed as readonly string[]).includes(raw)) {\n throw new Error(`${flag} must be one of: ${allowed.join(', ')}`);\n }\n return raw as T;\n };\n },\n /** Require a positive (>0) integer. */\n positiveInt(flag: string) {\n return (raw: string): number => {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${flag} must be a positive integer`);\n }\n return parsed;\n };\n },\n /** Pass a string through unchanged. */\n string(raw: string): string {\n return raw;\n },\n};\n\n/**\n * One CLI flag. `key` is the long name (e.g. `output`); `field` is the\n * {@link import('./cli.js').HeadlessArgs} property it populates. `coerce`\n * converts the raw string and validates it. Boolean flags omit `coerce` and set\n * `field` to `true` when present.\n */\nexport interface FlagSpec {\n /** Long flag name without the leading `--`. */\n key: string;\n /** Single-character alias (without the leading `-`), if any. */\n short?: string;\n /** Whether the flag takes a value (`string`) or is a switch (`boolean`). */\n type: 'string' | 'boolean';\n /** Target field on `HeadlessArgs`. Omit for flags handled out-of-band (e.g. help). */\n field?: string;\n /** Coerce/validate a string value. Required for `type: 'string'` flags that map to a field. */\n coerce?: (raw: string) => unknown;\n /** `<...>` value placeholder shown in usage, e.g. `<text>`. */\n placeholder?: string;\n /** One-line (or multi-line) help description shown in usage. */\n help: string | string[];\n}\n\nexport const FLAGS: FlagSpec[] = [\n {\n key: 'prompt',\n short: 'p',\n type: 'string',\n field: 'prompt',\n coerce: validate.string,\n placeholder: '<text>',\n help: 'The task to execute (required, or pipe via stdin)',\n },\n {\n key: 'continue',\n short: 'c',\n type: 'boolean',\n field: 'continue_',\n help: 'Resume the most recent thread instead of creating a new one',\n },\n {\n key: 'thread',\n short: 't',\n type: 'string',\n field: 'thread',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Resume a specific thread by ID',\n },\n {\n key: 'title',\n type: 'string',\n field: 'title',\n coerce: validate.string,\n placeholder: '<title>',\n help: 'Set or rename the thread title',\n },\n {\n key: 'clone-thread',\n type: 'boolean',\n field: 'cloneThread',\n help: 'Clone the current thread before running (work on a copy)',\n },\n {\n key: 'resource-id',\n type: 'string',\n field: 'resourceId',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Set the resource ID for thread scoping',\n },\n {\n key: 'timeout',\n type: 'string',\n field: 'timeout',\n coerce: validate.positiveInt('--timeout'),\n placeholder: '<seconds>',\n help: 'Exit with code 2 if not complete within timeout',\n },\n {\n key: 'max-turns',\n type: 'string',\n field: 'maxTurns',\n coerce: validate.positiveInt('--max-turns'),\n placeholder: '<n>',\n help: 'Abort after N agentic turns (exit code 1)',\n },\n {\n key: 'permission-mode',\n type: 'string',\n field: 'permissionMode',\n coerce: validate.enum<PermissionMode>('--permission-mode', VALID_PERMISSION_MODES),\n placeholder: '<mode>',\n help: [\n 'How tool approvals/suspensions resolve:',\n ' auto approve everything (default)',\n ' deny refuse approvals, abort on suspension',\n ],\n },\n {\n key: 'output',\n short: 'o',\n type: 'string',\n field: 'output',\n coerce: validate.enum<OutputMode>('--output', VALID_OUTPUTS),\n placeholder: '<mode>',\n help: [\n 'Output mode: \"human\" (default), \"json\", or \"jsonl\"',\n ' human streaming text to stdout, activity to stderr',\n ' json single final JSON object (text, usage, tools)',\n ' jsonl newline-delimited JSON event stream',\n ' (omits display_state_changed UI snapshots)',\n ],\n },\n {\n key: 'model',\n short: 'm',\n type: 'string',\n field: 'model',\n coerce: validate.string,\n placeholder: '<id>',\n help: 'Model override (e.g., a provider/model id); wins over --pack for the active mode',\n },\n {\n key: 'pack',\n type: 'string',\n field: 'pack',\n coerce: validate.string,\n placeholder: '<id>',\n help: [\n 'Model pack to activate (like /models → Activate): a builtin pack id',\n '(anthropic, openai, github-copilot) or a saved custom pack, by',\n '\"custom:<name>\" or its bare name. Sets the pack for every mode and',\n 'becomes the global default pack. --model overrides it for the active mode.',\n ],\n },\n {\n key: 'mode',\n type: 'string',\n field: 'mode',\n coerce: validate.enum<RunMode>('--mode', VALID_MODES),\n placeholder: '{build|plan|fast}',\n help: 'Execution mode — defaults to \"build\" if omitted',\n },\n {\n key: 'thinking-level',\n type: 'string',\n field: 'thinkingLevel',\n coerce: validate.enum<ThinkingLevel>('--thinking-level', VALID_THINKING_LEVELS),\n placeholder: '<level>',\n help: 'Thinking level: off, low, medium, high, xhigh, max',\n },\n {\n key: 'settings',\n type: 'string',\n field: 'settings',\n coerce: validate.string,\n placeholder: '<path>',\n help: 'Path to settings.json file (default: global settings)',\n },\n {\n key: 'help',\n short: 'h',\n type: 'boolean',\n help: 'Show this help and exit',\n },\n {\n key: 'version',\n short: 'v',\n type: 'boolean',\n help: 'Print the Mastra Code version and exit',\n },\n];\n\n/** `parseArgs` option config derived from {@link FLAGS}. */\nexport function buildParseArgsOptions() {\n const options: Record<string, { type: 'string' | 'boolean'; short?: string; default?: boolean }> = {};\n for (const flag of FLAGS) {\n options[flag.key] = flag.type === 'boolean' ? { type: 'boolean', default: false } : { type: 'string' };\n if (flag.short) options[flag.key]!.short = flag.short;\n }\n return options;\n}\n\n/** Render the aligned `--flag description` block of the usage text from {@link FLAGS}. */\nexport function renderFlagUsage(): string {\n const left = (flag: FlagSpec): string => {\n const long = `--${flag.key}`;\n const short = flag.short ? `, -${flag.short}` : '';\n const value = flag.placeholder ? ` ${flag.placeholder}` : '';\n return ` ${long}${short}${value}`;\n };\n\n const rows = FLAGS.map(flag => ({ flag, label: left(flag) }));\n const width = Math.max(...rows.map(r => r.label.length)) + 2;\n\n return rows\n .map(({ flag, label }) => {\n const lines = Array.isArray(flag.help) ? flag.help : [flag.help];\n const first = `${label.padEnd(width)}${lines[0]}`;\n const rest = lines.slice(1).map(line => `${' '.repeat(width)}${line}`);\n return [first, ...rest].join('\\n');\n })\n .join('\\n');\n}\n"],"mappings":";;AAgBA,MAAa,gBAAgB;CAAC;CAAS;CAAQ;AAAO;;AAGtD,MAAM,WAAW;;CAEf,KAAuB,MAAc,SAAuB;EAC1D,QAAQ,QAAmB;GACzB,IAAI,CAAE,QAA8B,SAAS,GAAG,GAC9C,MAAM,IAAI,MAAM,GAAG,KAAK,mBAAmB,QAAQ,KAAK,IAAI,GAAG;GAEjE,OAAO;EACT;CACF;;CAEA,YAAY,MAAc;EACxB,QAAQ,QAAwB;GAC9B,MAAM,SAAS,OAAO,GAAG;GACzB,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;GAEtD,OAAO;EACT;CACF;;CAEA,OAAO,KAAqB;EAC1B,OAAO;CACT;AACF;AAyBA,MAAa,QAAoB;CAC/B;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,OAAO;EACP,M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O;EACP,QAAQ,SAAS;EACjB,aAAa;EACb,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,MAAM;CACR;CACA;EACE,KAAK;EACL,OAAO;EACP,MAAM;EACN,MAAM;CACR;AACF;;AAGA,SAAgB,wBAAwB;CACtC,MAAM,UAA6F,CAAC;CACpG,KAAK,MAAM,QAAQ,OAAO;EACxB,QAAQ,KAAK,OAAO,KAAK,SAAS,YAAY;GAAE,MAAM;GAAW,SAAS;EAAM,IAAI,EAAE,MAAM,SAAS;EACrG,IAAI,KAAK,OAAO,QAAQ,KAAK,IAAI,CAAE,QAAQ,KAAK;CAClD;CACA,OAAO;AACT;;AAGA,SAAgB,kBAA0B;CACxC,MAAM,QAAQ,SAA2B;EAIvC,OAAO,KAAK,KAHM,KAAK,QACT,KAAK,QAAQ,MAAM,KAAK,UAAU,KAClC,KAAK,cAAc,IAAI,KAAK,gBAAgB;CAE5D;CAEA,MAAM,OAAO,MAAM,KAAI,UAAS;EAAE;EAAM,OAAO,KAAK,IAAI;CAAE,EAAE;CAC5D,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,KAAI,MAAK,EAAE,MAAM,MAAM,CAAC,IAAI;CAE3D,OAAO,KACJ,KAAK,EAAE,MAAM,YAAY;EACxB,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;EAG/D,OAAO,CAAC,GAFS,MAAM,OAAO,KAAK,IAAI,MAAM,MAE9B,GADF,MAAM,MAAM,CAAC,CAAC,CAAC,KAAI,SAAQ,GAAG,IAAI,OAAO,KAAK,IAAI,MAC1C,CAAC,CAAC,CAAC,KAAK,IAAI;CACnC,CAAC,CAAC,CACD,KAAK,IAAI;AACd"}
@@ -55,9 +55,9 @@ function aggregate(event, acc) {
55
55
  }
56
56
  case "usage_update":
57
57
  acc.usage = {
58
- inputTokens: event.usage.promptTokens,
59
- outputTokens: event.usage.completionTokens,
60
- totalTokens: event.usage.totalTokens
58
+ inputTokens: (acc.usage?.inputTokens ?? 0) + event.usage.promptTokens,
59
+ outputTokens: (acc.usage?.outputTokens ?? 0) + event.usage.completionTokens,
60
+ totalTokens: (acc.usage?.totalTokens ?? 0) + event.usage.totalTokens
61
61
  };
62
62
  break;
63
63
  case "error": acc.error = {