@mastra/code-sdk 1.18.0-alpha.2 → 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.
- package/dist/agents/credential-resolver.d.ts +4 -3
- package/dist/agents/credential-resolver.d.ts.map +1 -1
- package/dist/agents/credential-resolver.js.map +1 -1
- package/dist/agents/instructions.d.ts +6 -2
- package/dist/agents/instructions.d.ts.map +1 -1
- package/dist/agents/instructions.js +11 -5
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/memory.js +1 -1
- package/dist/agents/model.d.ts +25 -1
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +35 -1
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/prompts/index.d.ts +5 -0
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +5 -2
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/prompts/tool-guidance.d.ts +2 -0
- package/dist/agents/prompts/tool-guidance.d.ts.map +1 -1
- package/dist/agents/prompts/tool-guidance.js +6 -3
- package/dist/agents/prompts/tool-guidance.js.map +1 -1
- package/dist/agents/tools.d.ts.map +1 -1
- package/dist/agents/tools.js +27 -7
- package/dist/agents/tools.js.map +1 -1
- package/dist/auth/account-routing-context.d.ts +6 -2
- package/dist/auth/account-routing-context.d.ts.map +1 -1
- package/dist/auth/account-routing-context.js.map +1 -1
- package/dist/headless/run-mc.js +3 -3
- package/dist/headless/run-mc.js.map +1 -1
- package/dist/headless/types.d.ts +1 -0
- package/dist/headless/types.d.ts.map +1 -1
- package/dist/headless/types.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +13 -1
- package/dist/onboarding/settings.js.map +1 -1
- package/package.json +14 -14
|
@@ -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,KAAI,YAAW,QAAQ,OAAO,CAAC,CAC/B,OAAO,OAAO,CAAC,CACf,KAAK,MAAM;AAChB;;;;;AAMA,SAAgB,gBAAgB,KAA4B;CAC1D,OAAO,mBAAmB,wBAAwB,GAAG,CAAC;AACxD;;;;;AAMA,SAAgB,wBAAwB,KAAqC;CAE3E,MAAM,UAAU,IAAI;CACpB,MAAM,eACJ,eAAe,KACf,aAAa,KACZ,CAAC,CAAC,YAAY,QAAQ,WAAW,YAAY,KA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C7E,MAAM,mBAAmB,MAAM,QAAQ,IAAI,OAAO,gBAAgB,IAC7D,IAAI,MAAM,mBACX,KAAA;CAKJ,MAAM,qBAAqB,IAAI,aAC3B,wBAAwB;EACtB,YAAY,IAAI;EAChB;EACA;EACA,mBAAmB,IAAI,OAAO,sBAAsB;EACpD;EACA,YAAY,IAAI,OAAO,2BAA2B;CACpD,CAAC,IACD,CAAC;CAKL,MAAM,sBAAuC,mBAAmB,KAAK,QAAQ,UAAU;EACrF,MAAM,UAAU,UAAU;EAC1B,MAAM,SAAS,UAAU,mBAAmB,SAAS;EACrD,IAAI,UAAU,wBAAwB,MAAM;EAC5C,IAAI,SAAS,UAAU,GAAG,2BAA2B,MAAM;EAG3D,IAAI,QAAQ,UAAU,QAAQ,QAAQ;EACtC,OAAO;GACL,IAAI,sBAAsB,OAAO,KAAK,GAAG;GACzC,OAAO,GAAG,OAAO,UAAU,WAAW,WAAW,UAAU;GAC3D,QAAQ,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO;GACtE;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"}
|
|
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: 'Mode prompt', detail: ctx.modeId, content: modeSpecific.trim() },\n ].filter(section => Boolean(section.content));\n}\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;AAyBA,SAAgB,mBAAmB,UAAmC;CACpE,OAAO,SACJ,KAAI,YAAW,QAAQ,OAAO,CAAC,CAC/B,OAAO,OAAO,CAAC,CACf,KAAK,MAAM;AAChB;;;;;AAMA,SAAgB,g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AAO;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,
|
|
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)
|
|
85
|
-
|
|
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,+BAAe,IAAI,IAAY;CACtD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAqB,CAAC;CAE5B,SAAS,KAAK;;;;wEAIwD;CAItE,MAAM,YAAsB,C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YAAY,GAAG,SAAS,KAAK,gBAAgB;EAC7D,IAAI,CAAC,OAAO,IAAI,aAAa,GAAG,SAAS,KAAK,iBAAiB;EAC/D,IAAI,SAAS,SAAS,GACpB,SAAS,KAAK;EAClB,SAAS,KAAK,KAAK,EAAE;kEAC2C;CAEhE;CAIA,MAAM,YAAsB,CAAC;CAC7B,MAAM,gBAAgB,CAAC,OAAO,IAAI,aAAa;CAC/C,MAAM,kBAAkB,CAAC,OAAO,IAAI,eAAe;CACnD,MAAM,gBAAgB,CAAC,OAAO,IAAI,YAAY;CAC9C,MAAM,gBAAgB,CAAC,OAAO,IAAI,YAAY;CAC9C,MAAM,oBACJ,iBAAiB,kBACb,2EACA,gBACE,0DACA,kBACE,qEACA;CAEV,IAAI,eACF,UAAU,KAAK;;;;;;EAMjB,kBAAkB;;4FAEwE;CAG1F,IAAI,eACF,UAAU,KAAK;;;wFAGqE;CAGtF,IAAI,iBAAiB;EACnB,MAAM,WAAW,gBACb,yEACA,gBACE,oCACA;EACN,UAAU,KAAK;;;IAGf,UAAU;CACZ;CAEA,IAAI,eACF,UAAU,KAAK;;;;;;;gFAO6D;CAG9E,IAAI,CAAC,OAAO,IAAI,UAAU,GACxB,UAAU,KAAK;;;;;qEAKkD;CAGnE,IAAI,UAAU,SAAS,GACrB,SAAS,KAAK,UAAU,KAAK,IAAI,CAAC;CAKpC,IAAI,WAAW,UAAU,CAAC,OAAO,IAAI,aAAa,GAChD,SAAS,KAAK;;;;;2EAKyD,SAAS,wDAAwD;CAG1I,IAAI,WAAW,QACb,SAAS,KAAK;oEACkD,SAAS;;;;wFAIW;CAKtF,IAAI,QAAQ,iBAAiB,SAAS,CAAC,OAAO,IAAI,UAAU,GAC1D,SAAS,KAAK;;;4EAG0D;CAG1E,OAAO,SAAS,KAAK,IAAI;AAC3B"}
|
|
1
|
+
{"version":3,"file":"tool-guidance.js","names":[],"sources":["../../../src/agents/prompts/tool-guidance.ts"],"sourcesContent":["/**\n * Mode-specific tool behavioral guidance.\n * Generates tool usage instructions that match the actual registered tool names\n * and are scoped to what's available in the current mode.\n */\n\nimport { MC_TOOLS } from '../../tool-names.js';\n\ninterface ToolGuidanceOptions {\n hasWebSearch?: boolean;\n /** `web_extract` is registered (Parallel/Tavily); provider-executed search has no extract tool. */\n hasWebExtract?: boolean;\n hasSubagents?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n const plansDir = options.plansDir ?? '.mastracode/plans';\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read file contents. Don't propose changes to code you haven't seen; reading with shell commands (cat, sed, rg) also works.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Always set \\`description\\` to a 5-10 word summary of what the command does; the user sees it instead of the raw command. Put it first in the arguments, before \\`command\\`, so the user sees it while the rest of the call streams in. Write each one as the next step in a running narrative that can lean on earlier commands (e.g. \"Searching open PRs for failing CI\", then \"Drilling into the first of 15 failures\").\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- Overwriting replaces the whole file, so make sure you know its current contents first.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (options.hasWebExtract && !denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n const purpose =\n webTools.length === 2\n ? 'Search the web / extract page content'\n : webTools[0] === '**web_search**'\n ? 'Search the web'\n : 'Extract page content';\n sections.push(`\n${webTools.join(' / ')} — ${purpose}\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Task management tools (all modes) ---\n\n const taskTools: string[] = [];\n const canUpdateTask = !denied.has('task_update');\n const canCompleteTask = !denied.has('task_complete');\n const canCheckTasks = !denied.has('task_check');\n const canWriteTasks = !denied.has('task_write');\n const patchToolGuidance =\n canUpdateTask && canCompleteTask\n ? '- Prefer task_update or task_complete when changing one existing task.'\n : canUpdateTask\n ? '- Prefer task_update when changing one existing task.'\n : canCompleteTask\n ? '- Prefer task_complete when marking one existing task completed.'\n : '- Use task_write with the full task list when changing existing tasks.';\n\n if (canWriteTasks) {\n taskTools.push(`\n**task_write** — Track tasks for complex multi-step work\n- Use when a task requires 3 or more distinct steps or actions.\n- Use task_write to create the initial task list or replace the whole list after replanning.\n- Each task has: id (stable identifier), content (imperative form), status (pending, in_progress, or completed), activeForm (present continuous form shown during execution).\n- Keep task IDs stable across updates. If you omit IDs, the tool result returns generated IDs.\n${patchToolGuidance}\n- Mark tasks \\`in_progress\\` BEFORE starting work. Only ONE task should be \\`in_progress\\` at a time.\n- Mark tasks \\`completed\\` IMMEDIATELY after finishing each task. Do not batch completions.`);\n }\n\n if (canUpdateTask) {\n taskTools.push(`\n**task_update** — Patch one tracked task by ID\n- Use this for targeted changes to one existing task.\n- Provide the task ID and only the fields that changed: content, status, or activeForm.`);\n }\n\n if (canCompleteTask) {\n const idSource = canCheckTasks\n ? 'Use task_check if you need the current IDs before completing a task.'\n : canWriteTasks\n ? 'Use IDs returned by task_write.'\n : 'Use only task IDs already visible in the current task list.';\n taskTools.push(`\n**task_complete** — Mark one tracked task completed by ID\n- Use this immediately after finishing a tracked task.\n- ${idSource}`);\n }\n\n if (canCheckTasks) {\n taskTools.push(`\n**task_check** — Check completion status of tasks\n- Use this BEFORE finishing tracked work to verify all tasks are completed.\n- Returns a readable status summary plus structured fields: tasks, summary, incompleteTasks, and isError.\n- summary includes total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted.\n- Use summary.allCompleted to decide whether tracked work is complete; if summary.hasTasks is false, no task list is currently tracked.\n- If any tasks remain incomplete, continue working on them.\n- IMPORTANT: Always check task completion before ending work on a complex task.`);\n }\n\n if (!denied.has('ask_user')) {\n taskTools.push(`\n**ask_user** — Ask the user a structured question\n- Use when you need clarification, want to validate assumptions, or need the user to make a decision.\n- Provide clear, specific questions. End with a question mark.\n- Include options (2-4 choices) for structured decisions. Omit options for open-ended questions.\n- Don't use this for simple yes/no — just ask in your text response.`);\n }\n\n if (taskTools.length > 0) {\n sections.push(taskTools.join('\\n'));\n }\n\n // --- Plan tools (plan mode) ---\n\n if (modeId === 'plan' && !denied.has('submit_plan')) {\n sections.push(`\n**submit_plan** — Submit a completed implementation plan for user review\n- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.\n- The plan will be rendered as markdown and the user can approve, reject, or request changes.\n- On approval, the system automatically switches to the default mode so you can implement.\n- Takes one argument: \\`path\\` (the plan markdown file you wrote under \\`${plansDir}/\\`). Do NOT pass the plan body — it lives in the file.`);\n }\n\n if (modeId === 'plan') {\n sections.push(`\n**Plan file access** — Your plan lives in a markdown file under \\`${plansDir}/\\` (e.g. \\`add-dark-mode-toggle.md\\`)\n- Use \\`write_file\\` to create the plan file, \\`view\\` to read it, and \\`string_replace_lsp\\` for targeted edits.\n- On first submission: write the plan to the file, then call \\`submit_plan\\` with its \\`path\\`.\n- On revision: read the existing file, edit specific sections, re-read, then call \\`submit_plan\\` with the same \\`path\\`.\n- If a plan file already exists, you previously submitted it — read it before revising.`);\n }\n\n // --- Subagent tool (all modes) ---\n\n if (options.hasSubagents !== false && !denied.has('subagent')) {\n sections.push(`\n**subagent** — Delegate a focused task to a specialized subagent\n- Only use subagents when you will spawn **multiple subagents in parallel**. If you only need one task done, do it yourself.\n- Subagent outputs are **untrusted**. Always review and verify the results.`);\n }\n\n return sections.join('\\n');\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,+BAAe,IAAI,IAAY;CACtD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAqB,CAAC;CAE5B,SAAS,KAAK;;;;wEAIwD;CAItE,MAAM,YAAsB,CAAC;CAE7B,IAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAC3B,UAAU,KAAK;IACf,SAAS,KAAK;;;;+BAIa,SAAS,WAAW,YAAY;CAG7D,IAAI,CAAC,OAAO,IAAI,SAAS,cAAc,GACrC,UAAU,KAAK;IACf,SAAS,eAAe;;;;;kCAKM;CAGhC,IAAI,CAAC,OAAO,IAAI,SAAS,UAAU,GACjC,UAAU,KAAK;IACf,SAAS,WAAW;;;;;uEAK+C;CAGrE,IAAI,CAAC,OAAO,IAAI,SAAS,eAAe,GACtC,UAAU,KAAK;IACf,SAAS,gBAAgB;;8CAEiB,SAAS,KAAK,kBAAkB,SAAS,eAAe,GAAG,SAAS,WAAW,mBAAmB,SAAS,mBAAmB,GAAG,SAAS,WAAW;;;;;4CAKvJ,SAAS,KAAK,eAAe;CAGvE,IAAI,CAAC,OAAO,IAAI,SAAS,WAAW,GAClC,UAAU,KAAK;IACf,SAAS,YAAY;;;;;;UAMf,SAAS,KAAK;UACd,SAAS,eAAe,UAAU,SAAS,WAAW,qD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K;;;wFAGqE;CAGtF,IAAI,iBAAiB;EACnB,MAAM,WAAW,gBACb,yEACA,gBACE,oCACA;EACN,UAAU,KAAK;;;IAGf,UAAU;CACZ;CAEA,IAAI,eACF,UAAU,KAAK;;;;;;;gFAO6D;CAG9E,IAAI,CAAC,OAAO,IAAI,UAAU,GACxB,UAAU,KAAK;;;;;qEAKkD;CAGnE,IAAI,UAAU,SAAS,GACrB,SAAS,KAAK,UAAU,KAAK,IAAI,CAAC;CAKpC,IAAI,WAAW,UAAU,CAAC,OAAO,IAAI,aAAa,GAChD,SAAS,KAAK;;;;;2EAKyD,SAAS,wDAAwD;CAG1I,IAAI,WAAW,QACb,SAAS,KAAK;oEACkD,SAAS;;;;wFAIW;CAKtF,IAAI,QAAQ,iBAAiB,SAAS,CAAC,OAAO,IAAI,UAAU,GAC1D,SAAS,KAAK;;;4EAG0D;CAG1E,OAAO,SAAS,KAAK,IAAI;AAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/agents/tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,EAA+B,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,KAAK,EACV,uBAAuB,EACvB,yBAAyB,EACzB,sBAAsB,EACtB,uBAAuB,EACvB,8BAA8B,EAC/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/agents/tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC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C,OAAO,EAAE,oBAAoB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAEvF,wBAAgB,eAAe,CAAC,WAAW,CAAC,EAAE,WAAW,EAAE,gBAAgB,CAAC,EAAE,gBAAgB,GAAG,SAAS,GAAG,SAAS,CAoCrH;AAED,KAAK,mBAAmB,GACpB,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,GACpC,CAAC,CAAC,GAAG,EAAE;IACL,cAAc,EAAE,cAAc,CAAC;CAChC,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AAwBhG,wBAAgB,kBAAkB,CAChC,UAAU,CAAC,EAAE,UAAU,EACvB,UAAU,CAAC,EAAE,mBAAmB,EAChC,aAAa,CAAC,EAAE,MAAM,EAAE,EACxB,OAAO,CAAC,EAAE,oBAAoB,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"}
|
package/dist/agents/tools.js
CHANGED
|
@@ -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
|
|
86
|
-
|
|
87
|
-
const
|
|
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) => {
|
package/dist/agents/tools.js.map
CHANGED
|
@@ -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,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,mBAAmB,KAAK;CACxE;CAEA,MAAM,kBAAkB,OAA+B;EACrD,QAAQ,MAAM,KAAK,wBAAwB,EAAA,CAAG,kBAAkB,KAAK;CACvE;CAEA,MAAM,qBAAqB,OAAkC;EAC3D,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AM,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;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,Q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,WAAW,YAAY,SAAS;EACtC,IAAI,UAAU,OAAO,OAAO,OAAO,QAAQ;EAE3C,MAAM,UAAU,kBAAoE;GAClF,IAAI,eACG;SAAA,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,aAAa,GACrD,IAAI,QAAQ,EAAE,QAAQ,QACpB,MAAM,QAAQ;GAAA;GAKpB,IAAI,aACG;SAAA,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,WAAW,GACnD,IAAI,EAAE,QAAQ,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,5 +1,9 @@
|
|
|
1
1
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
2
|
-
|
|
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:
|
|
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;
|
|
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?:
|
|
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"}
|
package/dist/headless/run-mc.js
CHANGED
|
@@ -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 = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-mc.js","names":[],"sources":["../../src/headless/run-mc.ts"],"sourcesContent":["/**\n * Core programmatic runner for MastraCode headless runs.\n *\n * `runMC` is a pure async runner: it takes an already-built `controller` +\n * `session` (from `createMastraCode(...)`), resolves run config, subscribes to\n * the session, applies a {@link ResolutionPolicy} for approvals/suspensions,\n * sends the prompt, and aggregates events into a {@link RunMCResult}.\n *\n * It never touches `process.*` and never calls `process.exit`. The returned\n * {@link MCRun} is async-iterable over controller events and also resolves to a\n * final result via `result`.\n */\nimport { isSessionStartupCancelledError } from '@mastra/core/agent-controller';\nimport type { AgentControllerEvent, Session } from '@mastra/core/agent-controller';\n\nimport { MODEL_FALLBACK_STATE_KEY } from '../auth/account-rotation-processor.js';\nimport { GoalManager } from '../goal-manager.js';\nimport { createGoalReminderSignal } from '../goal-signal.js';\nimport { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from '../onboarding/settings.js';\n\nimport { autoApprovePolicy } from './policy.js';\nimport type { MCRun, ResolutionPolicy, RunMCOptions, RunMCResult, RunMCStatus } from './types.js';\n\nfunction exitCodeForStatus(status: RunMCStatus): number {\n switch (status) {\n case 'completed':\n case 'done':\n return 0;\n case 'timeout':\n return 2;\n default:\n return 1;\n }\n}\n\ninterface MutableResult {\n text: string;\n finishReason?: string;\n usage?: RunMCResult['usage'];\n toolCalls: RunMCResult['toolCalls'];\n toolResults: RunMCResult['toolResults'];\n error?: RunMCResult['error'];\n threadId?: string;\n activeAssistantMessageId?: string;\n}\n\nfunction aggregate(event: AgentControllerEvent, acc: MutableResult): void {\n switch (event.type) {\n case 'message_start':\n if (event.message.role === 'assistant') acc.activeAssistantMessageId = event.message.id;\n break;\n case 'message_update':\n if (event.event.type === 'text-delta' && event.id === acc.activeAssistantMessageId) {\n acc.text += event.event.delta;\n }\n break;\n case 'message_end':\n if (event.id === acc.activeAssistantMessageId) acc.activeAssistantMessageId = undefined;\n break;\n case 'tool_start':\n acc.toolCalls.push({ id: event.toolCallId, name: event.toolName, args: event.args });\n break;\n case 'tool_end': {\n const matching = acc.toolCalls.find(c => c.id === event.toolCallId);\n acc.toolResults.push({\n id: event.toolCallId,\n name: matching?.name ?? '',\n result: event.result,\n isError: event.isError,\n });\n break;\n }\n case 'usage_update':\n acc.usage = {\n inputTokens: event.usage.promptTokens,\n outputTokens: event.usage.completionTokens,\n totalTokens: event.usage.totalTokens,\n };\n break;\n case 'error':\n acc.error = {\n name: event.error.name,\n message: event.error.message,\n stack: event.error.stack,\n };\n break;\n }\n}\n\n/** Resolve a thread by its exact ID. Titles are not unique, so we don't match on them. */\nasync function resolveThread<TState extends Record<string, unknown>>(\n session: Session<TState>,\n threadId: string,\n resourceId?: string,\n): Promise<{ threadId: string } | { error: string }> {\n const threads = await session.thread.list(resourceId ? { allResources: true } : undefined);\n\n const byId = threads.find(thread => thread.id === threadId && (!resourceId || thread.resourceId === resourceId));\n if (byId) return { threadId: byId.id };\n\n return { error: `No thread found with ID \"${threadId}\"` };\n}\n\n/**\n * A simple back-pressured async queue. Events are pushed in; consumers pull via\n * the async iterator. `close()` ends iteration after draining buffered events.\n *\n * Buffered events are bounded by `maxBuffer`: if a consumer never iterates (the\n * result-only path, `await run.result` without `for await (...)`) — or simply\n * falls far behind — the oldest buffered events are dropped instead of growing\n * without limit. The aggregated {@link RunMCResult} is built independently of\n * this queue, so dropping buffered events never affects the final result.\n */\nclass EventQueue<T> {\n #buffer: T[] = [];\n #resolvers: Array<(r: IteratorResult<T>) => void> = [];\n #closed = false;\n readonly #maxBuffer: number;\n\n constructor(maxBuffer = 10_000) {\n this.#maxBuffer = maxBuffer;\n }\n\n push(value: T): void {\n if (this.#closed) return;\n const resolve = this.#resolvers.shift();\n if (resolve) {\n resolve({ value, done: false });\n return;\n }\n this.#buffer.push(value);\n if (this.#buffer.length > this.#maxBuffer) {\n // Bound memory: drop the oldest event once over the cap.\n this.#buffer.shift();\n }\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n for (const resolve of this.#resolvers.splice(0)) {\n resolve({ value: undefined as unknown as T, done: true });\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: (): Promise<IteratorResult<T>> => {\n if (this.#buffer.length > 0) {\n return Promise.resolve({ value: this.#buffer.shift()!, done: false });\n }\n if (this.#closed) {\n return Promise.resolve({ value: undefined as unknown as T, done: true });\n }\n return new Promise<IteratorResult<T>>(resolve => this.#resolvers.push(resolve));\n },\n };\n }\n}\n\n/**\n * Run a headless MastraCode turn. Returns an {@link MCRun} handle that is\n * async-iterable over controller events and resolves to a {@link RunMCResult}.\n */\nexport function runMC<TState extends Record<string, unknown>>(options: RunMCOptions<TState>): MCRun {\n const { controller, session } = options;\n const goal = options.goal;\n const policy: ResolutionPolicy = options.policy ?? autoApprovePolicy;\n\n const queue = new EventQueue<AgentControllerEvent>();\n const acc: MutableResult = { text: '', toolCalls: [], toolResults: [] };\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n let aborted = false;\n let maxTurnsExceeded = false;\n let assistantTurns = 0;\n let activeAssistantMessageId: string | undefined;\n let settled = false;\n let agentStarts = 0;\n let unsubscribe: (() => void) | undefined;\n let resolveResult!: (r: RunMCResult) => void;\n\n const result = new Promise<RunMCResult>(resolve => {\n resolveResult = resolve;\n });\n\n function finish(status: RunMCStatus, data: Partial<RunMCResult> = {}): void {\n if (settled) return;\n settled = true;\n if (timeoutId) clearTimeout(timeoutId);\n unsubscribe?.();\n queue.close();\n resolveResult({\n status,\n text: acc.text,\n finishReason: acc.finishReason,\n usage: acc.usage,\n toolCalls: acc.toolCalls,\n toolResults: acc.toolResults,\n threadId: acc.threadId ?? session.thread.getId() ?? undefined,\n error: acc.error,\n exitCode: exitCodeForStatus(status),\n ...data,\n });\n }\n\n function fail(message: string, name = 'Error'): void {\n if (!acc.error) acc.error = { name, message };\n finish('error');\n }\n\n function failUnresolvedSuspension(toolName?: string): void {\n fail(`Run ended with an unresolved ${toolName ? `${toolName} suspension` : 'tool suspension'}.`);\n }\n\n /**\n * Ask the policy for the next parked tool. The session starts a fresh\n * run for it, so this run stays open until that run ends. Returns false when\n * nothing is left to resume.\n */\n function resumeNextSuspension(): boolean {\n const next = session.displayState.get().pendingSuspensions.values().next();\n if (next.done) return false;\n const { toolCallId, toolName } = next.value;\n let outcome: ReturnType<ResolutionPolicy['onSuspension']>;\n try {\n outcome = policy.onSuspension({ type: 'tool_suspended', ...next.value });\n } catch (err) {\n fail(`Resolution policy failed: ${(err as Error).message}`);\n return true;\n }\n if ('abort' in outcome) {\n abort();\n // This run has already ended suspended, so no further agent_end is due.\n finish('aborted');\n return true;\n }\n const { resumeData } = outcome;\n // The session clears the ending run's state right after emitting\n // agent_end, so resume on a later task, as an interactive client would.\n setTimeout(() => {\n if (settled) return;\n if (timedOut) return finish('timeout');\n if (aborted) return finish('aborted');\n const startsBeforeResume = agentStarts;\n session.respondToToolSuspension({ toolCallId, resumeData }).then(\n () => {\n // The session returns without starting a run when the suspension is\n // no longer parked; nothing else would end this run then.\n if (!settled && agentStarts === startsBeforeResume) failUnresolvedSuspension(toolName);\n },\n (err: unknown) => fail(`Failed to resume ${toolName}: ${(err as Error).message}`),\n );\n }, 0);\n return true;\n }\n\n function abort(): void {\n if (settled) return;\n aborted = true;\n session.abort();\n }\n\n if (options.signal) {\n if (options.signal.aborted) {\n // Defer so the caller can attach iteration / result handlers first.\n queueMicrotask(() => abort());\n } else {\n options.signal.addEventListener('abort', () => abort(), { once: true });\n }\n }\n\n function armTimeout(): void {\n if (!options.timeoutMs || settled) return;\n if (timeoutId) clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n timedOut = true;\n session.abort();\n if (goal) finish('timeout');\n }, options.timeoutMs);\n }\n\n // Kick off the run asynchronously so the MCRun handle is returned synchronously.\n void (async () => {\n armTimeout();\n\n // --- Subscribe ---\n unsubscribe = session.subscribe(event => {\n if (settled) return;\n if (event.type === 'agent_start') agentStarts += 1;\n if (goal) armTimeout();\n\n if (event.type === 'tool_approval_required') {\n let decision: 'approve' | 'deny';\n try {\n decision = policy.onToolApproval(event);\n } catch (err) {\n fail(`Resolution policy failed: ${(err as Error).message}`);\n return;\n }\n session.respondToToolApproval({\n decision: decision === 'approve' ? 'approve' : 'decline',\n toolCallId: event.toolCallId,\n });\n queue.push(event);\n return;\n }\n\n if (event.type === 'message_start' && event.message.role === 'assistant') {\n activeAssistantMessageId = event.message.id;\n }\n\n aggregate(event, acc);\n queue.push(event);\n\n if (event.type === 'error' && goal) {\n finish('error');\n return;\n }\n\n // Count agentic turns (one assistant response = one turn). When the cap is\n // reached, abort the run; agent_end then resolves as 'max_turns'.\n if (event.type === 'message_end' && event.id === activeAssistantMessageId && options.maxTurns !== undefined) {\n activeAssistantMessageId = undefined;\n assistantTurns += 1;\n if (assistantTurns >= options.maxTurns && !maxTurnsExceeded) {\n maxTurnsExceeded = true;\n abort();\n }\n }\n\n if (event.type === 'goal_evaluation' && goal && !event.payload.pending) {\n if (event.payload.status === 'done' || event.payload.status === 'paused') {\n finish(event.payload.status, {\n objective: goal.objective,\n goalEvent: event,\n reason: event.payload.reason ?? event.payload.results?.[0]?.reason,\n iterations: event.payload.iteration,\n maxRuns: event.payload.maxRuns,\n });\n }\n return;\n }\n\n if (event.type === 'agent_end') {\n acc.finishReason = event.reason;\n // A suspended run is parked, not finished: nothing more arrives until a\n // parked tool is answered, including goal evaluations.\n if (event.reason === 'suspended' && !timedOut && !aborted) {\n if (!resumeNextSuspension()) failUnresolvedSuspension();\n return;\n }\n // Goal evaluations can arrive after the agent stream ends, so goal runs\n // remain active until a terminal goal_evaluation is emitted.\n if (goal) return;\n if (timedOut) {\n finish('timeout');\n } else if (event.reason === 'error') {\n finish('error');\n } else if (maxTurnsExceeded && event.reason !== 'complete') {\n // The cap forced an abort while the agent still had work to do.\n finish('max_turns');\n } else if ((event.reason === 'aborted' || aborted) && !maxTurnsExceeded) {\n finish('aborted');\n } else {\n finish('completed');\n }\n }\n });\n\n // --- Thread resolution (read-only) ---\n const thread = options.thread;\n const targetResourceId = options.resourceId ?? session.identity.getResourceId();\n let restoredThreadId: string | undefined;\n try {\n if (thread?.id) {\n const resolved = await resolveThread(session, thread.id, targetResourceId);\n if ('error' in resolved) return fail(resolved.error);\n restoredThreadId = resolved.threadId;\n } else if (thread?.continueLatest) {\n const threads = await session.thread.list(targetResourceId ? { allResources: true } : undefined);\n const resourceThreads = targetResourceId\n ? threads.filter(candidate => candidate.resourceId === targetResourceId)\n : threads;\n if (resourceThreads.length > 0) {\n restoredThreadId = [...resourceThreads].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0]!.id;\n }\n }\n } catch (err) {\n return fail(`Failed to resolve thread: ${(err as Error).message}`);\n }\n\n // --- Config validation (read-only) ---\n const restoredThreadSelection = Boolean(restoredThreadId || thread?.clone);\n const modeIdForModel = options.mode ?? (options.modeDefaults ? session.mode.get() : undefined);\n const configuredDefaultModelId = modeIdForModel ? options.modeDefaults?.[modeIdForModel] : undefined;\n // A pack's model is not resolved here: a resumed thread restores its\n // persisted mode during thread selection, and the pack selection depends\n // on that mode. It is resolved and validated during config application.\n const modelIdToApply = options.pack\n ? options.model\n : (options.model ?? (options.mode || !restoredThreadSelection ? configuredDefaultModelId : undefined));\n // Where modelIdToApply came from, so validation errors name the right source.\n const modelSource = options.model ? 'flag' : 'mode';\n try {\n if (options.mode && !controller.listModes().some(mode => mode.id === options.mode)) {\n return fail(`Unknown mode: \"${options.mode}\"`);\n }\n\n if (modelIdToApply) {\n const available = await controller.listAvailableModels();\n const match = available.find(model => model.id === modelIdToApply);\n if (!match) {\n if (modelSource === 'flag') return fail(`Unknown model: \"${modelIdToApply}\"`);\n return fail(`Unknown model \"${modelIdToApply}\" configured for mode \"${modeIdForModel}\"`);\n }\n if (!match.hasApiKey) {\n const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : '';\n if (modelSource === 'flag') return fail(`Model \"${modelIdToApply}\" has no API key configured.${keyHint}`);\n return fail(`Model \"${modelIdToApply}\" (mode: ${modeIdForModel}) has no API key configured.${keyHint}`);\n }\n }\n } catch (err) {\n return fail(`Failed to resolve run config: ${(err as Error).message}`);\n }\n\n // --- Resource id ---\n try {\n if (options.resourceId) {\n await controller.setResourceId(session, { resourceId: options.resourceId });\n }\n } catch (err) {\n return fail(`Failed to set resource id: ${(err as Error).message}`);\n }\n\n // --- Thread selection ---\n try {\n if (restoredThreadId) {\n await session.thread.switch({ threadId: restoredThreadId });\n } else if (!thread?.clone) {\n await session.thread.create();\n }\n } catch (err) {\n return fail(`Failed to select thread: ${(err as Error).message}`);\n }\n\n // --- Clone ---\n if (thread?.clone) {\n try {\n await session.thread.clone();\n } catch (err) {\n return fail(`Failed to clone thread: ${(err as Error).message}`);\n }\n }\n\n // --- Config application ---\n try {\n if (options.mode) {\n await session.mode.switch({ modeId: options.mode });\n }\n let packModelId: string | undefined;\n if (options.pack) {\n // Resolve the selection against the mode in effect now — thread\n // selection above may have restored a resumed thread's persisted mode.\n const packModeId = options.mode ?? session.mode.get();\n const packSelection = options.pack.resolve(packModeId);\n if (!packSelection) {\n return fail(`Model pack \"${options.pack.id}\" has no model for ${packModeId} mode`);\n }\n const available = await controller.listAvailableModels();\n const match = available.find(model => model.id === packSelection.modelId);\n if (!match) {\n return fail(`Unknown model \"${packSelection.modelId}\" from pack \"${options.pack.id}\"`);\n }\n if (!match.hasApiKey) {\n const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : '';\n return fail(\n `Model \"${packSelection.modelId}\" (pack: ${options.pack.id}) has no API key configured.${keyHint}`,\n );\n }\n packModelId = packSelection.modelId;\n // Mirror /models → Activate on the session: sticky thread pack id,\n // subagent models, and the fallback route. Clears any pending fallback\n // from a continued thread so the pack's own route starts clean.\n await session.thread.setSetting({ key: THREAD_ACTIVE_MODEL_PACK_ID_KEY, value: options.pack.id });\n await session.thread.setSetting({ key: MODEL_FALLBACK_STATE_KEY, value: undefined });\n for (const [agentType, modelId] of Object.entries(packSelection.subagentModels ?? {})) {\n await session.subagents.model.set({ modelId, agentType });\n }\n await session.state.set({\n modelRoute: packSelection.modelRoute,\n [MODEL_FALLBACK_STATE_KEY]: null,\n } as unknown as Partial<TState>);\n }\n const sessionModelId = modelIdToApply ?? packModelId;\n if (sessionModelId) {\n await session.model.switch(sessionModelId);\n }\n // Persist the pack activation (global default) only once the pack has\n // fully taken effect on the session — a failed model switch above must\n // not leave the global default changed.\n options.pack?.onApplied?.();\n if (options.thinkingLevel) {\n await session.state.set({ thinkingLevel: options.thinkingLevel } as unknown as Partial<TState>);\n }\n } catch (err) {\n return fail(`Failed to apply run config: ${(err as Error).message}`);\n }\n\n // --- Title ---\n if (options.title) {\n try {\n await session.thread.rename({ title: options.title });\n } catch (err) {\n return fail(`Failed to set thread title: ${(err as Error).message}`);\n }\n }\n\n // --- Start ---\n try {\n if (goal) {\n const threadId = session.thread.getId();\n if (!threadId || !(await session.thread.getById({ threadId }))) {\n await session.thread.create();\n }\n\n const goalManager = goal.goalManager ?? new GoalManager();\n const state = {\n controller,\n session,\n goalManager,\n pendingNewThread: false,\n } as any;\n const objective = await goalManager.setGoal(state, goal.objective, goal.judgeModelId, goal.maxRuns);\n if (!objective) return fail('Failed to set goal.');\n\n const agent = controller.getCurrentAgent(session);\n const persisted = await agent.getObjective({ threadId: session.thread.getId()! });\n if (!persisted || persisted.id !== objective.id) {\n return fail('Failed to persist goal objective before sending goal signal.');\n }\n\n await goalManager.saveToThread(state);\n if (!settled) await session.sendSignal(createGoalReminderSignal(objective)).accepted;\n } else {\n if (!options.prompt) return fail('A prompt or goal is required.');\n await session.sendMessage({ content: options.prompt });\n }\n } catch (err) {\n if (\n isSessionStartupCancelledError(err) ||\n (err instanceof Error && err.name === 'AbortError' && (aborted || timedOut || options.signal?.aborted))\n ) {\n return finish(timedOut ? 'timeout' : maxTurnsExceeded ? 'max_turns' : 'aborted');\n }\n return fail(`Failed to start run: ${(err as Error).message}`);\n }\n })();\n\n return {\n result,\n abort,\n [Symbol.asyncIterator](): AsyncIterator<AgentControllerEvent> {\n return queue[Symbol.asyncIterator]();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,SAAS,kBAAkB,QAA6B;CACtD,QAAQ,QAAR;EACE,KAAK;EACL,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAaA,SAAS,UAAU,OAA6B,KAA0B;CACxE,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,IAAI,MAAM,QAAQ,SAAS,aAAa,IAAI,2BAA2B,MAAM,QAAQ;GACrF;EACF,KAAK;GACH,IAAI,MAAM,MAAM,SAAS,gBAAgB,MAAM,OAAO,IAAI,0BACxD,IAAI,QAAQ,MAAM,MAAM;GAE1B;EACF,KAAK;GACH,IAAI,MAAM,OAAO,IAAI,0BAA0B,IAAI,2BAA2B,KAAA;GAC9E;EACF,KAAK;GACH,IAAI,UAAU,KAAK;IAAE,IAAI,MAAM;IAAY,MAAM,MAAM;IA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KAAK;GACZ,IACE,+BAA+B,GAAG,KACjC,eAAe,SAAS,IAAI,SAAS,iBAAiB,WAAW,YAAY,QAAQ,QAAQ,UAE9F,OAAO,OAAO,WAAW,YAAY,mBAAmB,cAAc,SAAS;GAEjF,OAAO,KAAK,wBAAyB,IAAc,SAAS;EAC9D;CACF,EAAA,CAAG;CAEH,OAAO;EACL;EACA;EACA,CAAC,OAAO,iBAAsD;GAC5D,OAAO,MAAM,OAAO,cAAc,CAAC;EACrC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"run-mc.js","names":[],"sources":["../../src/headless/run-mc.ts"],"sourcesContent":["/**\n * Core programmatic runner for MastraCode headless runs.\n *\n * `runMC` is a pure async runner: it takes an already-built `controller` +\n * `session` (from `createMastraCode(...)`), resolves run config, subscribes to\n * the session, applies a {@link ResolutionPolicy} for approvals/suspensions,\n * sends the prompt, and aggregates events into a {@link RunMCResult}.\n *\n * It never touches `process.*` and never calls `process.exit`. The returned\n * {@link MCRun} is async-iterable over controller events and also resolves to a\n * final result via `result`.\n */\nimport { isSessionStartupCancelledError } from '@mastra/core/agent-controller';\nimport type { AgentControllerEvent, Session } from '@mastra/core/agent-controller';\n\nimport { MODEL_FALLBACK_STATE_KEY } from '../auth/account-rotation-processor.js';\nimport { GoalManager } from '../goal-manager.js';\nimport { createGoalReminderSignal } from '../goal-signal.js';\nimport { THREAD_ACTIVE_MODEL_PACK_ID_KEY } from '../onboarding/settings.js';\n\nimport { autoApprovePolicy } from './policy.js';\nimport type { MCRun, ResolutionPolicy, RunMCOptions, RunMCResult, RunMCStatus } from './types.js';\n\nfunction exitCodeForStatus(status: RunMCStatus): number {\n switch (status) {\n case 'completed':\n case 'done':\n return 0;\n case 'timeout':\n return 2;\n default:\n return 1;\n }\n}\n\ninterface MutableResult {\n text: string;\n finishReason?: string;\n usage?: RunMCResult['usage'];\n toolCalls: RunMCResult['toolCalls'];\n toolResults: RunMCResult['toolResults'];\n error?: RunMCResult['error'];\n threadId?: string;\n activeAssistantMessageId?: string;\n}\n\nfunction aggregate(event: AgentControllerEvent, acc: MutableResult): void {\n switch (event.type) {\n case 'message_start':\n if (event.message.role === 'assistant') acc.activeAssistantMessageId = event.message.id;\n break;\n case 'message_update':\n if (event.event.type === 'text-delta' && event.id === acc.activeAssistantMessageId) {\n acc.text += event.event.delta;\n }\n break;\n case 'message_end':\n if (event.id === acc.activeAssistantMessageId) acc.activeAssistantMessageId = undefined;\n break;\n case 'tool_start':\n acc.toolCalls.push({ id: event.toolCallId, name: event.toolName, args: event.args });\n break;\n case 'tool_end': {\n const matching = acc.toolCalls.find(c => c.id === event.toolCallId);\n acc.toolResults.push({\n id: event.toolCallId,\n name: matching?.name ?? '',\n result: event.result,\n isError: event.isError,\n });\n break;\n }\n case 'usage_update':\n acc.usage = {\n inputTokens: (acc.usage?.inputTokens ?? 0) + event.usage.promptTokens,\n outputTokens: (acc.usage?.outputTokens ?? 0) + event.usage.completionTokens,\n totalTokens: (acc.usage?.totalTokens ?? 0) + event.usage.totalTokens,\n };\n break;\n case 'error':\n acc.error = {\n name: event.error.name,\n message: event.error.message,\n stack: event.error.stack,\n };\n break;\n }\n}\n\n/** Resolve a thread by its exact ID. Titles are not unique, so we don't match on them. */\nasync function resolveThread<TState extends Record<string, unknown>>(\n session: Session<TState>,\n threadId: string,\n resourceId?: string,\n): Promise<{ threadId: string } | { error: string }> {\n const threads = await session.thread.list(resourceId ? { allResources: true } : undefined);\n\n const byId = threads.find(thread => thread.id === threadId && (!resourceId || thread.resourceId === resourceId));\n if (byId) return { threadId: byId.id };\n\n return { error: `No thread found with ID \"${threadId}\"` };\n}\n\n/**\n * A simple back-pressured async queue. Events are pushed in; consumers pull via\n * the async iterator. `close()` ends iteration after draining buffered events.\n *\n * Buffered events are bounded by `maxBuffer`: if a consumer never iterates (the\n * result-only path, `await run.result` without `for await (...)`) — or simply\n * falls far behind — the oldest buffered events are dropped instead of growing\n * without limit. The aggregated {@link RunMCResult} is built independently of\n * this queue, so dropping buffered events never affects the final result.\n */\nclass EventQueue<T> {\n #buffer: T[] = [];\n #resolvers: Array<(r: IteratorResult<T>) => void> = [];\n #closed = false;\n readonly #maxBuffer: number;\n\n constructor(maxBuffer = 10_000) {\n this.#maxBuffer = maxBuffer;\n }\n\n push(value: T): void {\n if (this.#closed) return;\n const resolve = this.#resolvers.shift();\n if (resolve) {\n resolve({ value, done: false });\n return;\n }\n this.#buffer.push(value);\n if (this.#buffer.length > this.#maxBuffer) {\n // Bound memory: drop the oldest event once over the cap.\n this.#buffer.shift();\n }\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n for (const resolve of this.#resolvers.splice(0)) {\n resolve({ value: undefined as unknown as T, done: true });\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: (): Promise<IteratorResult<T>> => {\n if (this.#buffer.length > 0) {\n return Promise.resolve({ value: this.#buffer.shift()!, done: false });\n }\n if (this.#closed) {\n return Promise.resolve({ value: undefined as unknown as T, done: true });\n }\n return new Promise<IteratorResult<T>>(resolve => this.#resolvers.push(resolve));\n },\n };\n }\n}\n\n/**\n * Run a headless MastraCode turn. Returns an {@link MCRun} handle that is\n * async-iterable over controller events and resolves to a {@link RunMCResult}.\n */\nexport function runMC<TState extends Record<string, unknown>>(options: RunMCOptions<TState>): MCRun {\n const { controller, session } = options;\n const goal = options.goal;\n const policy: ResolutionPolicy = options.policy ?? autoApprovePolicy;\n\n const queue = new EventQueue<AgentControllerEvent>();\n const acc: MutableResult = { text: '', toolCalls: [], toolResults: [] };\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n let aborted = false;\n let maxTurnsExceeded = false;\n let assistantTurns = 0;\n let activeAssistantMessageId: string | undefined;\n let settled = false;\n let agentStarts = 0;\n let unsubscribe: (() => void) | undefined;\n let resolveResult!: (r: RunMCResult) => void;\n\n const result = new Promise<RunMCResult>(resolve => {\n resolveResult = resolve;\n });\n\n function finish(status: RunMCStatus, data: Partial<RunMCResult> = {}): void {\n if (settled) return;\n settled = true;\n if (timeoutId) clearTimeout(timeoutId);\n unsubscribe?.();\n queue.close();\n resolveResult({\n status,\n text: acc.text,\n finishReason: acc.finishReason,\n usage: acc.usage,\n toolCalls: acc.toolCalls,\n toolResults: acc.toolResults,\n threadId: acc.threadId ?? session.thread.getId() ?? undefined,\n error: acc.error,\n exitCode: exitCodeForStatus(status),\n ...data,\n });\n }\n\n function fail(message: string, name = 'Error'): void {\n if (!acc.error) acc.error = { name, message };\n finish('error');\n }\n\n function failUnresolvedSuspension(toolName?: string): void {\n fail(`Run ended with an unresolved ${toolName ? `${toolName} suspension` : 'tool suspension'}.`);\n }\n\n /**\n * Ask the policy for the next parked tool. The session starts a fresh\n * run for it, so this run stays open until that run ends. Returns false when\n * nothing is left to resume.\n */\n function resumeNextSuspension(): boolean {\n const next = session.displayState.get().pendingSuspensions.values().next();\n if (next.done) return false;\n const { toolCallId, toolName } = next.value;\n let outcome: ReturnType<ResolutionPolicy['onSuspension']>;\n try {\n outcome = policy.onSuspension({ type: 'tool_suspended', ...next.value });\n } catch (err) {\n fail(`Resolution policy failed: ${(err as Error).message}`);\n return true;\n }\n if ('abort' in outcome) {\n abort();\n // This run has already ended suspended, so no further agent_end is due.\n finish('aborted');\n return true;\n }\n const { resumeData } = outcome;\n // The session clears the ending run's state right after emitting\n // agent_end, so resume on a later task, as an interactive client would.\n setTimeout(() => {\n if (settled) return;\n if (timedOut) return finish('timeout');\n if (aborted) return finish('aborted');\n const startsBeforeResume = agentStarts;\n session.respondToToolSuspension({ toolCallId, resumeData }).then(\n () => {\n // The session returns without starting a run when the suspension is\n // no longer parked; nothing else would end this run then.\n if (!settled && agentStarts === startsBeforeResume) failUnresolvedSuspension(toolName);\n },\n (err: unknown) => fail(`Failed to resume ${toolName}: ${(err as Error).message}`),\n );\n }, 0);\n return true;\n }\n\n function abort(): void {\n if (settled) return;\n aborted = true;\n session.abort();\n }\n\n if (options.signal) {\n if (options.signal.aborted) {\n // Defer so the caller can attach iteration / result handlers first.\n queueMicrotask(() => abort());\n } else {\n options.signal.addEventListener('abort', () => abort(), { once: true });\n }\n }\n\n function armTimeout(): void {\n if (!options.timeoutMs || settled) return;\n if (timeoutId) clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n timedOut = true;\n session.abort();\n if (goal) finish('timeout');\n }, options.timeoutMs);\n }\n\n // Kick off the run asynchronously so the MCRun handle is returned synchronously.\n void (async () => {\n armTimeout();\n\n // --- Subscribe ---\n unsubscribe = session.subscribe(event => {\n if (settled) return;\n if (event.type === 'agent_start') agentStarts += 1;\n if (goal) armTimeout();\n\n if (event.type === 'tool_approval_required') {\n let decision: 'approve' | 'deny';\n try {\n decision = policy.onToolApproval(event);\n } catch (err) {\n fail(`Resolution policy failed: ${(err as Error).message}`);\n return;\n }\n session.respondToToolApproval({\n decision: decision === 'approve' ? 'approve' : 'decline',\n toolCallId: event.toolCallId,\n });\n queue.push(event);\n return;\n }\n\n if (event.type === 'message_start' && event.message.role === 'assistant') {\n activeAssistantMessageId = event.message.id;\n }\n\n aggregate(event, acc);\n queue.push(event);\n\n if (event.type === 'error' && goal) {\n finish('error');\n return;\n }\n\n // Count agentic turns (one assistant response = one turn). When the cap is\n // reached, abort the run; agent_end then resolves as 'max_turns'.\n if (event.type === 'message_end' && event.id === activeAssistantMessageId && options.maxTurns !== undefined) {\n activeAssistantMessageId = undefined;\n assistantTurns += 1;\n if (assistantTurns >= options.maxTurns && !maxTurnsExceeded) {\n maxTurnsExceeded = true;\n abort();\n }\n }\n\n if (event.type === 'goal_evaluation' && goal && !event.payload.pending) {\n if (event.payload.status === 'done' || event.payload.status === 'paused') {\n finish(event.payload.status, {\n objective: goal.objective,\n goalEvent: event,\n reason: event.payload.reason ?? event.payload.results?.[0]?.reason,\n iterations: event.payload.iteration,\n maxRuns: event.payload.maxRuns,\n });\n }\n return;\n }\n\n if (event.type === 'agent_end') {\n acc.finishReason = event.reason;\n // A suspended run is parked, not finished: nothing more arrives until a\n // parked tool is answered, including goal evaluations.\n if (event.reason === 'suspended' && !timedOut && !aborted) {\n if (!resumeNextSuspension()) failUnresolvedSuspension();\n return;\n }\n // Goal evaluations can arrive after the agent stream ends, so goal runs\n // remain active until a terminal goal_evaluation is emitted.\n if (goal) return;\n if (timedOut) {\n finish('timeout');\n } else if (event.reason === 'error') {\n finish('error');\n } else if (maxTurnsExceeded && event.reason !== 'complete') {\n // The cap forced an abort while the agent still had work to do.\n finish('max_turns');\n } else if ((event.reason === 'aborted' || aborted) && !maxTurnsExceeded) {\n finish('aborted');\n } else {\n finish('completed');\n }\n }\n });\n\n // --- Thread resolution (read-only) ---\n const thread = options.thread;\n const targetResourceId = options.resourceId ?? session.identity.getResourceId();\n let restoredThreadId: string | undefined;\n try {\n if (thread?.id) {\n const resolved = await resolveThread(session, thread.id, targetResourceId);\n if ('error' in resolved) return fail(resolved.error);\n restoredThreadId = resolved.threadId;\n } else if (thread?.continueLatest) {\n const threads = await session.thread.list(targetResourceId ? { allResources: true } : undefined);\n const resourceThreads = targetResourceId\n ? threads.filter(candidate => candidate.resourceId === targetResourceId)\n : threads;\n if (resourceThreads.length > 0) {\n restoredThreadId = [...resourceThreads].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0]!.id;\n }\n }\n } catch (err) {\n return fail(`Failed to resolve thread: ${(err as Error).message}`);\n }\n\n // --- Config validation (read-only) ---\n const restoredThreadSelection = Boolean(restoredThreadId || thread?.clone);\n const modeIdForModel = options.mode ?? (options.modeDefaults ? session.mode.get() : undefined);\n const configuredDefaultModelId = modeIdForModel ? options.modeDefaults?.[modeIdForModel] : undefined;\n // A pack's model is not resolved here: a resumed thread restores its\n // persisted mode during thread selection, and the pack selection depends\n // on that mode. It is resolved and validated during config application.\n const modelIdToApply = options.pack\n ? options.model\n : (options.model ?? (options.mode || !restoredThreadSelection ? configuredDefaultModelId : undefined));\n // Where modelIdToApply came from, so validation errors name the right source.\n const modelSource = options.model ? 'flag' : 'mode';\n try {\n if (options.mode && !controller.listModes().some(mode => mode.id === options.mode)) {\n return fail(`Unknown mode: \"${options.mode}\"`);\n }\n\n if (modelIdToApply) {\n const available = await controller.listAvailableModels();\n const match = available.find(model => model.id === modelIdToApply);\n if (!match) {\n if (modelSource === 'flag') return fail(`Unknown model: \"${modelIdToApply}\"`);\n return fail(`Unknown model \"${modelIdToApply}\" configured for mode \"${modeIdForModel}\"`);\n }\n if (!match.hasApiKey) {\n const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : '';\n if (modelSource === 'flag') return fail(`Model \"${modelIdToApply}\" has no API key configured.${keyHint}`);\n return fail(`Model \"${modelIdToApply}\" (mode: ${modeIdForModel}) has no API key configured.${keyHint}`);\n }\n }\n } catch (err) {\n return fail(`Failed to resolve run config: ${(err as Error).message}`);\n }\n\n // --- Resource id ---\n try {\n if (options.resourceId) {\n await controller.setResourceId(session, { resourceId: options.resourceId });\n }\n } catch (err) {\n return fail(`Failed to set resource id: ${(err as Error).message}`);\n }\n\n // --- Thread selection ---\n try {\n if (restoredThreadId) {\n await session.thread.switch({ threadId: restoredThreadId });\n } else if (!thread?.clone) {\n await session.thread.create();\n }\n } catch (err) {\n return fail(`Failed to select thread: ${(err as Error).message}`);\n }\n\n // --- Clone ---\n if (thread?.clone) {\n try {\n await session.thread.clone();\n } catch (err) {\n return fail(`Failed to clone thread: ${(err as Error).message}`);\n }\n }\n\n // --- Config application ---\n try {\n if (options.mode) {\n await session.mode.switch({ modeId: options.mode });\n }\n let packModelId: string | undefined;\n if (options.pack) {\n // Resolve the selection against the mode in effect now — thread\n // selection above may have restored a resumed thread's persisted mode.\n const packModeId = options.mode ?? session.mode.get();\n const packSelection = options.pack.resolve(packModeId);\n if (!packSelection) {\n return fail(`Model pack \"${options.pack.id}\" has no model for ${packModeId} mode`);\n }\n const available = await controller.listAvailableModels();\n const match = available.find(model => model.id === packSelection.modelId);\n if (!match) {\n return fail(`Unknown model \"${packSelection.modelId}\" from pack \"${options.pack.id}\"`);\n }\n if (!match.hasApiKey) {\n const keyHint = match.apiKeyEnvVar ? ` Set ${match.apiKeyEnvVar} to use this model.` : '';\n return fail(\n `Model \"${packSelection.modelId}\" (pack: ${options.pack.id}) has no API key configured.${keyHint}`,\n );\n }\n packModelId = packSelection.modelId;\n // Mirror /models → Activate on the session: sticky thread pack id,\n // subagent models, and the fallback route. Clears any pending fallback\n // from a continued thread so the pack's own route starts clean.\n await session.thread.setSetting({ key: THREAD_ACTIVE_MODEL_PACK_ID_KEY, value: options.pack.id });\n await session.thread.setSetting({ key: MODEL_FALLBACK_STATE_KEY, value: undefined });\n for (const [agentType, modelId] of Object.entries(packSelection.subagentModels ?? {})) {\n await session.subagents.model.set({ modelId, agentType });\n }\n await session.state.set({\n modelRoute: packSelection.modelRoute,\n [MODEL_FALLBACK_STATE_KEY]: null,\n } as unknown as Partial<TState>);\n }\n const sessionModelId = modelIdToApply ?? packModelId;\n if (sessionModelId) {\n await session.model.switch(sessionModelId);\n }\n // Persist the pack activation (global default) only once the pack has\n // fully taken effect on the session — a failed model switch above must\n // not leave the global default changed.\n options.pack?.onApplied?.();\n if (options.thinkingLevel) {\n await session.state.set({ thinkingLevel: options.thinkingLevel } as unknown as Partial<TState>);\n }\n } catch (err) {\n return fail(`Failed to apply run config: ${(err as Error).message}`);\n }\n\n // --- Title ---\n if (options.title) {\n try {\n await session.thread.rename({ title: options.title });\n } catch (err) {\n return fail(`Failed to set thread title: ${(err as Error).message}`);\n }\n }\n\n // --- Start ---\n try {\n if (goal) {\n const threadId = session.thread.getId();\n if (!threadId || !(await session.thread.getById({ threadId }))) {\n await session.thread.create();\n }\n\n const goalManager = goal.goalManager ?? new GoalManager();\n const state = {\n controller,\n session,\n goalManager,\n pendingNewThread: false,\n } as any;\n const objective = await goalManager.setGoal(state, goal.objective, goal.judgeModelId, goal.maxRuns);\n if (!objective) return fail('Failed to set goal.');\n\n const agent = controller.getCurrentAgent(session);\n const persisted = await agent.getObjective({ threadId: session.thread.getId()! });\n if (!persisted || persisted.id !== objective.id) {\n return fail('Failed to persist goal objective before sending goal signal.');\n }\n\n await goalManager.saveToThread(state);\n if (!settled) await session.sendSignal(createGoalReminderSignal(objective)).accepted;\n } else {\n if (!options.prompt) return fail('A prompt or goal is required.');\n await session.sendMessage({ content: options.prompt });\n }\n } catch (err) {\n if (\n isSessionStartupCancelledError(err) ||\n (err instanceof Error && err.name === 'AbortError' && (aborted || timedOut || options.signal?.aborted))\n ) {\n return finish(timedOut ? 'timeout' : maxTurnsExceeded ? 'max_turns' : 'aborted');\n }\n return fail(`Failed to start run: ${(err as Error).message}`);\n }\n })();\n\n return {\n result,\n abort,\n [Symbol.asyncIterator](): AsyncIterator<AgentControllerEvent> {\n return queue[Symbol.asyncIterator]();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,SAAS,kBAAkB,QAA6B;CACtD,QAAQ,QAAR;EACE,KAAK;EACL,KAAK,QACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAaA,SAAS,UAAU,OAA6B,KAA0B;CACxE,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,IAAI,MAAM,QAAQ,SAAS,aAAa,IAAI,2BAA2B,MAAM,QAAQ;GACrF;EACF,KAAK;GACH,IAAI,MAAM,MAAM,SAAS,gBAAgB,MAAM,OAAO,IAAI,0BACxD,IAAI,QAAQ,MAAM,MAAM;GAE1B;EACF,KAAK;GACH,IAAI,MAAM,OAAO,IAAI,0BAA0B,IAAI,2BAA2B,KAAA;GAC9E;EACF,KAAK;GACH,IAAI,UAAU,KAAK;IAAE,IAAI,MAAM;IAAY,MAAM,MAAM;IAAU,MAAM,MAAM;GAAK,CAAC;GACnF;EACF,KAAK,YAAY;GACf,MAAM,WAAW,IAAI,UAAU,MAAK,MAAK,EAAE,OAAO,MAAM,UAAU;GAClE,IAAI,YAAY,KAAK;IACnB,IAAI,MAAM;IACV,MAAM,UAAU,QAAQ;IACxB,QAAQ,MAAM;IACd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AAmB,cAAc,SAAS;GAEjF,OAAO,KAAK,wBAAyB,IAAc,SAAS;EAC9D;CACF,EAAA,CAAG;CAEH,OAAO;EACL;EACA;EACA,CAAC,OAAO,iBAAsD;GAC5D,OAAO,MAAM,OAAO,cAAc,CAAC;EACrC;CACF;AACF"}
|
package/dist/headless/types.d.ts
CHANGED
|
@@ -149,6 +149,7 @@ export interface RunMCResult {
|
|
|
149
149
|
maxRuns?: number;
|
|
150
150
|
/** Underlying finish reason from `agent_end`, when the run finished normally. */
|
|
151
151
|
finishReason?: string;
|
|
152
|
+
/** Cumulative token usage for this run, summed from per-step usage events. */
|
|
152
153
|
usage?: RunMCUsage;
|
|
153
154
|
toolCalls: RunMCToolCall[];
|
|
154
155
|
toolResults: RunMCToolResult[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/headless/types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAEpG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAEtE,MAAM,MAAM,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;AAChD,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;AAEhF,eAAO,MAAM,WAAW,YAAI,OAAO,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAC9D,eAAO,MAAM,qBAAqB,YAAI,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAU,CAAC;AAE/F;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,MAAM,CAAC;AAC7C,eAAO,M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