@mastra/code-sdk 1.4.1-alpha.2 → 1.5.0-alpha.7
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/CHANGELOG.md +72 -0
- package/dist/agents/context-audit.d.ts +84 -0
- package/dist/agents/context-audit.d.ts.map +1 -0
- package/dist/agents/context-audit.js +118 -0
- package/dist/agents/context-audit.js.map +1 -0
- package/dist/agents/instructions.d.ts +12 -1
- package/dist/agents/instructions.d.ts.map +1 -1
- package/dist/agents/instructions.js +23 -5
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/model.d.ts +11 -4
- package/dist/agents/model.d.ts.map +1 -1
- package/dist/agents/model.js +2 -1
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/prompts/agent-instructions.d.ts +9 -0
- package/dist/agents/prompts/agent-instructions.d.ts.map +1 -1
- package/dist/agents/prompts/agent-instructions.js +14 -4
- package/dist/agents/prompts/agent-instructions.js.map +1 -1
- package/dist/agents/prompts/index.d.ts +28 -0
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +49 -7
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/tools.js +1 -1
- package/dist/agents/workspace.d.ts.map +1 -1
- package/dist/agents/workspace.js +12 -9
- package/dist/agents/workspace.js.map +1 -1
- package/dist/onboarding/settings.d.ts +9 -7
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +27 -25
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/providers/openai-codex.d.ts +3 -4
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +1 -9
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/schema.d.ts +4 -3
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -8
- package/dist/schema.js.map +1 -1
- package/dist/thinking.d.ts +33 -0
- package/dist/thinking.d.ts.map +1 -0
- package/dist/thinking.js +58 -0
- package/dist/thinking.js.map +1 -0
- package/dist/workflows/register-primitives.js +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, normalize, relative, sep } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n /** Git ref the content was read from, when not read off the working tree. */\n ref?: string;\n}\n\n/**\n * Reads project-scope instruction files. The default implementation reads the\n * working tree via `fs`; alternative readers can serve content from another\n * source (e.g. a trusted git ref) while keeping working-tree paths as the\n * addressing scheme.\n */\nexport interface InstructionFileReader {\n exists(path: string): boolean;\n read(path: string): string;\n /** Git ref backing this reader, recorded on the loaded sources. */\n ref?: string;\n}\n\nconst fsInstructionReader: InstructionFileReader = {\n exists: path => existsSync(path),\n read: path => readFileSync(path, 'utf-8'),\n};\n\n/**\n * Create a reader that serves instruction files from a git ref instead of the\n * working tree. Paths are still addressed as working-tree paths under\n * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted\n * checkout (e.g. a PR branch under review) cannot influence what is loaded.\n * Tries `origin/<ref>` first (remote truth), then the local ref. Any git\n * failure (missing ref, missing file, no repo) reports the file as absent.\n */\nexport function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader {\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, path);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (rel === null) return null;\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'show', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n } catch {\n // Ref or file missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n ref,\n exists: path => show(path) !== null,\n read: path => {\n const content = show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\n/**\n * Reader for the reactive reminder channel (AgentsMDInjector) that serves\n * paths under `projectPath` from a trusted git ref. Paths outside the project\n * fall back to the operator machine's filesystem (those are trusted); paths\n * inside the project are only ever resolved against the ref, never the\n * working tree, so an untrusted checkout cannot feed content in.\n */\nexport function createGitRefReminderReader(\n projectPath: string,\n ref: string,\n): {\n pathExists: (path: string) => boolean;\n isDirectory: (path: string) => boolean;\n readFile: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, normalize(path));\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'cat-file', '-t', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n } catch {\n // Ref or object missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n pathExists: path => {\n const rel = toRelative(path);\n if (rel === null) return existsSync(path);\n return objectType(rel) !== null;\n },\n isDirectory: path => {\n const rel = toRelative(path);\n if (rel === null) {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n }\n return objectType(rel) === 'tree';\n },\n readFile: path => {\n const rel = toRelative(path);\n if (rel === null) return readFileSync(path, 'utf-8');\n return gitReader.read(path);\n },\n };\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string, reader: InstructionFileReader = fsInstructionReader): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (reader.exists(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n *\n * `projectReader` controls where project-scope content comes from (defaults to\n * the working tree). Global instructions read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath, projectReader);\n if (filePath) {\n try {\n const content = projectReader.read(filePath).trim();\n if (content) {\n sources.push({\n path: filePath,\n content,\n scope: 'project',\n ...(projectReader.ref ? { ref: projectReader.ref } : {}),\n });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader?: InstructionFileReader,\n): string[] {\n return loadAgentInstructions(projectPath, configDirName, projectReader).map(source => normalize(source.path));\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(source => {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n const origin = source.ref ? `${source.path} (at ref ${source.ref})` : source.path;\n return `<!-- ${label} instructions from ${origin} -->\\n${source.content}`;\n });\n\n return `\\n# Agent Instructions\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;AACF;AAEA,MAAM,mBAAmB;CAAC;CAAW;CAAe;CAAkB;AAAoB;AAuB1F,MAAM,sBAA6C;CACjD,SAAQ,SAAQ,WAAW,IAAI;CAC/B,OAAM,SAAQ,aAAa,MAAM,OAAO;AAC1C;;;;;;;;;AAUA,SAAgB,8BAA8B,aAAqB,KAAoC;CACrG,MAAM,cAAc,SAAgC;EAClD,MAAM,MAAM,SAAS,aAAa,IAAI;EACtC,IAAI,CAAC,OAAO,IAAI,WAAW,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;EAC5D,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;CAChC;CACA,MAAM,QAAQ,SAAgC;EAC5C,MAAM,MAAM,WAAW,IAAI;EAC3B,IAAI,QAAQ,MAAM,OAAO;EACzB,KAAK,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UAAU,cAAc,KAAK,QAAQ,CAAC,CAAC,KAAK;GAClD,IAAI,SAAS;IACX,QAAQ,KAAK;KACX,MAAM;KACN;KACA,OAAO;KACP,GAAI,cAAc,MAAM,EAAE,KAAK,cAAc,IAAI,IAAI,CAAC;IACxD,CAAC;IACD;GACF;EACF,QAAQ,CAER;CAEJ;CAEA,OAAO;AACT;AAEA,SAAgB,oCACd,aACA,gBAAgB,oBAChB,eACU;CACV,OAAO,sBAAsB,aAAa,eAAe,aAAa,CAAC,CAAC,KAAI,WAAU,UAAU,OAAO,IAAI,CAAC;AAC9G;;;;AAKA,SAAgB,wBAAwB,SAAsC;CAC5E,IAAI,QAAQ,WAAW,GAAG,OAAO;CAQjC,OAAO,6BANU,QAAQ,KAAI,WAAU;EAGrC,OAAO,QAFO,OAAO,UAAU,WAAW,WAAW,UAEhC,qBADN,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO,KAC5B,QAAQ,OAAO;CAClE,CAE2C,CAAC,CAAC,KAAK,MAAM,EAAE;AAC5D"}
|
|
1
|
+
{"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, normalize, relative, sep } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n /** Git ref the content was read from, when not read off the working tree. */\n ref?: string;\n}\n\n/**\n * Reads project-scope instruction files. The default implementation reads the\n * working tree via `fs`; alternative readers can serve content from another\n * source (e.g. a trusted git ref) while keeping working-tree paths as the\n * addressing scheme.\n */\nexport interface InstructionFileReader {\n exists(path: string): boolean;\n read(path: string): string;\n /** Git ref backing this reader, recorded on the loaded sources. */\n ref?: string;\n}\n\nconst fsInstructionReader: InstructionFileReader = {\n exists: path => existsSync(path),\n read: path => readFileSync(path, 'utf-8'),\n};\n\n/**\n * Create a reader that serves instruction files from a git ref instead of the\n * working tree. Paths are still addressed as working-tree paths under\n * `projectPath`; content comes from `git show <ref>:<relpath>` so an untrusted\n * checkout (e.g. a PR branch under review) cannot influence what is loaded.\n * Tries `origin/<ref>` first (remote truth), then the local ref. Any git\n * failure (missing ref, missing file, no repo) reports the file as absent.\n */\nexport function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader {\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, path);\n if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (rel === null) return null;\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'show', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n } catch {\n // Ref or file missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n ref,\n exists: path => show(path) !== null,\n read: path => {\n const content = show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\n/**\n * Reader for the reactive reminder channel (AgentsMDInjector) that serves\n * paths under `projectPath` from a trusted git ref. Paths outside the project\n * fall back to the operator machine's filesystem (those are trusted); paths\n * inside the project are only ever resolved against the ref, never the\n * working tree, so an untrusted checkout cannot feed content in.\n */\nexport function createGitRefReminderReader(\n projectPath: string,\n ref: string,\n): {\n pathExists: (path: string) => boolean;\n isDirectory: (path: string) => boolean;\n readFile: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = (path: string): string | null => {\n const rel = relative(projectPath, normalize(path));\n if (rel.startsWith('..') || isAbsolute(rel)) return null;\n return rel.split(sep).join('/');\n };\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n for (const candidate of [`origin/${ref}`, ref]) {\n try {\n return execFileSync('git', ['-C', projectPath, 'cat-file', '-t', `${candidate}:${rel}`], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n } catch {\n // Ref or object missing at this candidate — try the next one.\n }\n }\n return null;\n };\n return {\n pathExists: path => {\n const rel = toRelative(path);\n if (rel === null) return existsSync(path);\n return objectType(rel) !== null;\n },\n isDirectory: path => {\n const rel = toRelative(path);\n if (rel === null) {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n }\n return objectType(rel) === 'tree';\n },\n readFile: path => {\n const rel = toRelative(path);\n if (rel === null) return readFileSync(path, 'utf-8');\n return gitReader.read(path);\n },\n };\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string, reader: InstructionFileReader = fsInstructionReader): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (reader.exists(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n *\n * `projectReader` controls where project-scope content comes from (defaults to\n * the working tree). Global instructions read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath, projectReader);\n if (filePath) {\n try {\n const content = projectReader.read(filePath).trim();\n if (content) {\n sources.push({\n path: filePath,\n content,\n scope: 'project',\n ...(projectReader.ref ? { ref: projectReader.ref } : {}),\n });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader?: InstructionFileReader,\n): string[] {\n return loadAgentInstructions(projectPath, configDirName, projectReader).map(source => normalize(source.path));\n}\n\n/** Heading the agent-instructions block is introduced by in the system prompt. */\nexport const AGENT_INSTRUCTIONS_HEADING = '# Agent Instructions';\n\n/**\n * Format a single instruction source as it appears in the system prompt.\n *\n * Exported so callers that attribute prompt cost per source (the `/context`\n * audit) measure the exact block that is sent rather than reconstructing it.\n */\nexport function formatInstructionSource(source: InstructionSource): string {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n const origin = source.ref ? `${source.path} (at ref ${source.ref})` : source.path;\n return `<!-- ${label} instructions from ${origin} -->\\n${source.content}`;\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(formatInstructionSource);\n\n return `\\n${AGENT_INSTRUCTIONS_HEADING}\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;AACF;AAEA,MAAM,mBAAmB;CAAC;CAAW;CAAe;CAAkB;AAAoB;AAuB1F,MAAM,sBAA6C;CACjD,SAAQ,SAAQ,WAAW,IAAI;CAC/B,OAAM,SAAQ,aAAa,MAAM,OAAO;AAC1C;;;;;;;;;AAUA,SAAgB,8BAA8B,aAAqB,KAAoC;CACrG,MAAM,cAAc,SAAgC;EAClD,MAAM,MAAM,SAAS,aAAa,IAAI;EACtC,IAAI,CAAC,OAAO,IAAI,WAAW,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;EAC5D,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;CAChC;CACA,MAAM,QAAQ,SAAgC;EAC5C,MAAM,MAAM,WAAW,IAAI;EAC3B,IAAI,QAAQ,MAAM,OAAO;EACzB,KAAK,MAAM,aAAa,CAAC,UAAU,OAAO,GAAG,GAC3C,IAAI;GACF,OAAO,aAAa,OAAO;IAAC;IAAM;IAAa;IAAQ,GAAG,UAAU,GAAG;GAAK,GAAG;IAC7E,UAAU;IACV,OAAO;KAAC;KAAU;KAAQ;IAAQ;IAClC,WAAW,OAAO;GACpB,CAAC;EACH,QAAQ,CAER;EAEF,OAAO;CACT;CACA,OAAO;EACL;EACA,SAAQ,SAAQ,KAAK,IAAI,MAAM;EAC/B,OAAM,SAAQ;GACZ,MAAM,UAAU,KAAK,IAAI;GACzB,IAAI,YAAY,MAAM,MAAM,IAAI,MAAM,oBAAoB,IAAI,IAAI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B,wBAAwB,QAAmC;CAGzE,OAAO,QAFO,OAAO,UAAU,WAAW,WAAW,UAEhC,qBADN,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO,KAC5B,QAAQ,OAAO;AAClE;;;;AAKA,SAAgB,wBAAwB,SAAsC;CAC5E,IAAI,QAAQ,WAAW,GAAG,OAAO;CAEjC,MAAM,WAAW,QAAQ,IAAI,uBAAuB;CAEpD,OAAO,KAAK,2BAA2B,MAAM,SAAS,KAAK,MAAM,EAAE;AACrE"}
|
|
@@ -11,9 +11,37 @@ export interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {
|
|
|
11
11
|
currentDate: string;
|
|
12
12
|
workingDir: string;
|
|
13
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* One labeled piece of the assembled system prompt.
|
|
16
|
+
*
|
|
17
|
+
* The system prompt is a single string by the time it reaches the model, which
|
|
18
|
+
* makes it impossible to say which configuration source is responsible for
|
|
19
|
+
* which share of the context window. Building it as labeled sections and
|
|
20
|
+
* joining them at the end keeps that attribution available to the `/context`
|
|
21
|
+
* audit while guaranteeing the audit measures the exact text that is sent —
|
|
22
|
+
* a parallel "describe the prompt" path would drift and report numbers for a
|
|
23
|
+
* prompt that is no longer assembled this way.
|
|
24
|
+
*/
|
|
25
|
+
export interface PromptSection {
|
|
26
|
+
/** Stable identifier, unique within a single build. */
|
|
27
|
+
id: string;
|
|
28
|
+
/** Human-readable label for display. */
|
|
29
|
+
label: string;
|
|
30
|
+
/** Optional provenance (e.g. the instruction file path). */
|
|
31
|
+
detail?: string;
|
|
32
|
+
/** The exact text contributed to the prompt. */
|
|
33
|
+
content: string;
|
|
34
|
+
}
|
|
35
|
+
/** Join prompt sections into the final system prompt string. */
|
|
36
|
+
export declare function joinPromptSections(sections: PromptSection[]): string;
|
|
14
37
|
/**
|
|
15
38
|
* Build the full system prompt for a given mode and context.
|
|
16
39
|
* Combines the base prompt with mode-specific instructions.
|
|
17
40
|
*/
|
|
18
41
|
export declare function buildFullPrompt(ctx: PromptContext): string;
|
|
42
|
+
/**
|
|
43
|
+
* Build the system prompt as labeled sections. `buildFullPrompt` is the join of
|
|
44
|
+
* these, so the two can never disagree about what the model receives.
|
|
45
|
+
*/
|
|
46
|
+
export declare function buildFullPromptSections(ctx: PromptContext): PromptSection[];
|
|
19
47
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAkBpF,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAQD;;;;;;;;;;GAUG;AACH,MAAM,WAAW,aAAa;IAC5B,uDAAuD;IACvD,EAAE,EAAE,MAAM,CAAC;IACX,wCAAwC;IACxC,KAAK,EAAE,MAAM,CAAC;IACd,4DAA4D;IAC5D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,MAAM,CAKpE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAE1D;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,aAAa,GAAG,aAAa,EAAE,CAmG3E"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { loadSettings, resolveLspSetting } from "../../onboarding/settings.js";
|
|
1
2
|
import { buildModePrompt, buildModePromptFn } from "./build.js";
|
|
2
3
|
import { getLocalPlansRelativeDir } from "../../utils/plans.js";
|
|
3
4
|
import { planModePrompt } from "./plan.js";
|
|
4
5
|
import { fastModePrompt } from "./fast.js";
|
|
6
|
+
import { MC_TOOLS } from "../../tool-names.js";
|
|
5
7
|
import { hasTavilyKey } from "../../tools/web-search.js";
|
|
6
8
|
import "../../tools/index.js";
|
|
7
|
-
import { createGitRefInstructionReader,
|
|
9
|
+
import { AGENT_INSTRUCTIONS_HEADING, createGitRefInstructionReader, formatInstructionSource, loadAgentInstructions } from "./agent-instructions.js";
|
|
8
10
|
import { modelSpecificPrompts } from "./model.js";
|
|
9
11
|
import { buildToolGuidance } from "./tool-guidance.js";
|
|
10
12
|
import { buildBasePrompt } from "@mastra/core/coding-agent";
|
|
@@ -14,11 +16,22 @@ const modePrompts = {
|
|
|
14
16
|
plan: planModePrompt,
|
|
15
17
|
fast: fastModePrompt
|
|
16
18
|
};
|
|
19
|
+
/** Join prompt sections into the final system prompt string. */
|
|
20
|
+
function joinPromptSections(sections) {
|
|
21
|
+
return sections.map((section) => section.content).filter(Boolean).join("\n\n");
|
|
22
|
+
}
|
|
17
23
|
/**
|
|
18
24
|
* Build the full system prompt for a given mode and context.
|
|
19
25
|
* Combines the base prompt with mode-specific instructions.
|
|
20
26
|
*/
|
|
21
27
|
function buildFullPrompt(ctx) {
|
|
28
|
+
return joinPromptSections(buildFullPromptSections(ctx));
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Build the system prompt as labeled sections. `buildFullPrompt` is the join of
|
|
32
|
+
* these, so the two can never disagree about what the model receives.
|
|
33
|
+
*/
|
|
34
|
+
function buildFullPromptSections(ctx) {
|
|
22
35
|
const modelId = ctx.modelId;
|
|
23
36
|
const hasWebSearch = hasTavilyKey() || !!modelId && modelId.startsWith("anthropic/");
|
|
24
37
|
const deniedTools = /* @__PURE__ */ new Set();
|
|
@@ -26,6 +39,7 @@ function buildFullPrompt(ctx) {
|
|
|
26
39
|
if (permRules?.tools) {
|
|
27
40
|
for (const [name, policy] of Object.entries(permRules.tools)) if (policy === "deny") deniedTools.add(name);
|
|
28
41
|
}
|
|
42
|
+
if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);
|
|
29
43
|
const factoryProjectId = typeof ctx.state?.factoryProjectId === "string" ? ctx.state.factoryProjectId : void 0;
|
|
30
44
|
const toolGuidance = buildToolGuidance(ctx.modeId, {
|
|
31
45
|
hasWebSearch,
|
|
@@ -55,14 +69,42 @@ function buildFullPrompt(ctx) {
|
|
|
55
69
|
exists: () => false,
|
|
56
70
|
read: () => ""
|
|
57
71
|
} : void 0;
|
|
72
|
+
const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader, { skipGlobal: skipGlobalInstructions });
|
|
73
|
+
const instructionSections = instructionSources.map((source, index) => {
|
|
74
|
+
const isFirst = index === 0;
|
|
75
|
+
const isLast = index === instructionSources.length - 1;
|
|
76
|
+
let content = formatInstructionSource(source);
|
|
77
|
+
if (isFirst) content = `${AGENT_INSTRUCTIONS_HEADING}\n\n${content}`;
|
|
78
|
+
if (isLast) content = content.trimEnd();
|
|
79
|
+
return {
|
|
80
|
+
id: `agent-instructions:${source.path}:${index}`,
|
|
81
|
+
label: `${source.scope === "global" ? "Global" : "Project"} instructions`,
|
|
82
|
+
detail: source.ref ? `${source.path} (at ref ${source.ref})` : source.path,
|
|
83
|
+
content
|
|
84
|
+
};
|
|
85
|
+
});
|
|
58
86
|
return [
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
87
|
+
{
|
|
88
|
+
id: "base-prompt",
|
|
89
|
+
label: "Base system prompt",
|
|
90
|
+
content: base
|
|
91
|
+
},
|
|
92
|
+
...instructionSections,
|
|
93
|
+
{
|
|
94
|
+
id: "model-prompt",
|
|
95
|
+
label: "Model-specific prompt",
|
|
96
|
+
detail: ctx.modelId,
|
|
97
|
+
content: modelSpecific.trim()
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
id: "mode-prompt",
|
|
101
|
+
label: "Mode prompt",
|
|
102
|
+
detail: ctx.modeId,
|
|
103
|
+
content: modeSpecific.trim()
|
|
104
|
+
}
|
|
105
|
+
].filter((section) => Boolean(section.content));
|
|
64
106
|
}
|
|
65
107
|
//#endregion
|
|
66
|
-
export { buildFullPrompt, buildModePrompt, buildModePromptFn, fastModePrompt, planModePrompt };
|
|
108
|
+
export { buildFullPrompt, buildFullPromptSections, buildModePrompt, buildModePromptFn, fastModePrompt, joinPromptSections, planModePrompt };
|
|
67
109
|
|
|
68
110
|
//# sourceMappingURL=index.js.map
|
|
@@ -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 { hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport { loadAgentInstructions, formatAgentInstructions, createGitRefInstructionReader } 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 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 * 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 // Determine whether web search tools are available\n const modelId = ctx.modelId;\n const hasWebSearch = hasTavilyKey() || (!!modelId && modelId.startsWith('anthropic/'));\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 // 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 deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir,\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 activePlan: ctx.state?.activePlan,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific = (typeof entry === 'function' ? entry(ctx) : entry) ?? '';\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 const configDir = ctx.state?.configDir as string | undefined;\n const untrustedCheckout = ctx.state?.untrustedCheckout === true;\n const skipGlobalInstructions = ctx.state?.skipGlobalInstructions === true;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const projectReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(ctx.workingDir, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader, {\n skipGlobal: skipGlobalInstructions,\n });\n const instructionsSection = formatAgentInstructions(instructionSources);\n\n const sections = [base, instructionsSection.trim(), modelSpecific.trim(), modeSpecific.trim()].filter(Boolean);\n\n return sections.join('\\n\\n');\n}\n"],"mappings":";;;;;;;;;;;AA2BA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;;;;AAMA,SAAgB,gBAAgB,KAA4B;CAE1D,MAAM,UAAU,IAAI;CACpB,MAAM,eAAe,aAAa,KAAM,CAAC,CAAC,WAAW,QAAQ,WAAW,YAAY;CAGpF,MAAM,8BAAc,IAAI,IAAY;CACpC,MAAM,YAAY,IA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|
+
{"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 { hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport {\n loadAgentInstructions,\n formatInstructionSource,\n createGitRefInstructionReader,\n AGENT_INSTRUCTIONS_HEADING,\n} 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 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 = hasTavilyKey() || (!!modelId && modelId.startsWith('anthropic/'));\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 // 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 deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir,\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 activePlan: ctx.state?.activePlan,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific = (typeof entry === 'function' ? entry(ctx) : entry) ?? '';\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 const configDir = ctx.state?.configDir as string | undefined;\n const untrustedCheckout = ctx.state?.untrustedCheckout === true;\n const skipGlobalInstructions = ctx.state?.skipGlobalInstructions === true;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const projectReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(ctx.workingDir, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const instructionSources = loadAgentInstructions(ctx.workingDir, configDir, projectReader, {\n skipGlobal: skipGlobalInstructions,\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 return [\n { id: 'base-prompt', label: 'Base system prompt', content: base },\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,eAAe,aAAa,KAAM,CAAC,CAAC,WAAW,QAAQ,WAAW,YAAY;CAGpF,MAAM,8BAAc,IAAI,IAAY;CACpC,MAAM,YAAY,IAAI,OAAO;CAC7B,IAAI,WAAW,OACR;OAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,UAAU,KAAK,GACzD,IAAI,WAAW,QAAQ,YAAY,IAAI,IAAI;CAAA;CAM/C,IAAI,kBAAkB,aAAa,CAAC,CAAC,GAAG,MAAM,OAAO,YAAY,IAAI,SAAS,WAAW;CAGzF,MAAM,mBAAmB,OAAO,IAAI,OAAO,qBAAqB,WAAW,IAAI,MAAM,mBAAmB,KAAA;CACxG,MAAM,eAAe,kBAAkB,IAAI,QAAQ;EACjD;EACA;EACA,UAAU,yBAAyB,EAAE,iBAAiB,CAAC;CACzD,CAAC;CAgBD,MAAM,OAAO,gBAAgB;EAZ3B,aAAa,IAAI;EACjB,aAAa,IAAI,eAAe;EAChC,WAAW,IAAI;EACf,UAAU,QAAQ;EAClB,gBAAgB,IAAI;EACpB,MAAM,IAAI;EACV,MAAM,IAA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AQ,SAAS,aAAa,KAAK;EAAE;CAC9F,CAAC,CAAC,QAAO,YAAW,QAAQ,QAAQ,OAAO,CAAC;AAC9C"}
|
package/dist/agents/tools.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createWebExtractTool, createWebSearchTool, hasTavilyKey } from "../tools/web-search.js";
|
|
2
1
|
import { MC_TOOLS } from "../tool-names.js";
|
|
2
|
+
import { createWebExtractTool, createWebSearchTool, hasTavilyKey } from "../tools/web-search.js";
|
|
3
3
|
import { requestSandboxAccessTool } from "../tools/request-sandbox-access.js";
|
|
4
4
|
import "../tools/index.js";
|
|
5
5
|
import { createWorkflowTool } from "../tools/workflows/create-workflow.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../../src/agents/workspace.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AACxG,OAAO,KAAK,EAAa,WAAW,EAAE,MAAM,wBAAwB,CAAC;AA0GrE,wBAAgB,eAAe,CAC7B,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,SAAe,EACtB,gBAAgB,GAAE,MAAM,EAAO,GAC9B,MAAM,EAAE,CA0BV;AAED,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,EAAE,EAAE,MAAM,CAAC;IACX,uFAAuF;IACvF,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6EAA6E;IAC7E,YAAY,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC;CACpF;AA4FD,wB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AAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
|
package/dist/agents/workspace.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../constants.js";
|
|
2
|
-
import { loadSettings } from "../onboarding/settings.js";
|
|
2
|
+
import { loadSettings, resolveLspSetting } from "../onboarding/settings.js";
|
|
3
3
|
import { getPlansDir } from "../utils/plans.js";
|
|
4
4
|
import { isPathWithinRoot } from "../utils/path-security.js";
|
|
5
5
|
import { SandboxFilesystem } from "./sandbox-filesystem.js";
|
|
@@ -198,14 +198,17 @@ async function getDynamicWorkspace({ requestContext, mastra, skillExtension }) {
|
|
|
198
198
|
existing.setToolsConfig(workspaceTools);
|
|
199
199
|
return existing;
|
|
200
200
|
}
|
|
201
|
-
const userLsp = loadSettings().lsp
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
201
|
+
const userLsp = resolveLspSetting(loadSettings().lsp);
|
|
202
|
+
let lspConfig = false;
|
|
203
|
+
if (userLsp !== false) {
|
|
204
|
+
const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
205
|
+
lspConfig = {
|
|
206
|
+
maxOpenClients: 4,
|
|
207
|
+
...userLsp,
|
|
208
|
+
packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath),
|
|
209
|
+
searchPaths: [mcModulePath, ...userLsp.searchPaths ?? []]
|
|
210
|
+
};
|
|
211
|
+
}
|
|
209
212
|
const filesystem = new LocalFilesystem({
|
|
210
213
|
basePath: projectPath,
|
|
211
214
|
allowedPaths
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\nimport { SandboxFilesystem } from './sandbox-filesystem.js';\nimport { reattachProjectSandbox } from './sandbox-reattach.js';\nimport { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\n/**\n * Build (or reuse) a sandbox-backed Workspace for a linked project repository. The sandbox\n * is reattached by its persisted provider id and a `SandboxFilesystem` is layered\n * over the in-sandbox checkout so file tools and command tools share one VM.\n */\nasync function getSandboxWorkspace({\n projectRepositoryId,\n sandboxId,\n workdir,\n worktreePath,\n configDir,\n mastra,\n skillExtension,\n actingUserId,\n}: {\n projectRepositoryId: string;\n sandboxId: string;\n workdir: string;\n worktreePath?: string;\n configDir: string;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n actingUserId?: string;\n}): Promise<Workspace> {\n // Bind the workspace to the active worktree when one is set, so file tools and\n // command tools operate inside the feature branch's working tree rather than\n // the base checkout. Falls back to the repo root when no worktree is active.\n const boundWorkdir = worktreePath || workdir;\n\n // Include the sandbox id, worktree path, and acting user in the reuse key: a\n // new sandbox, different worktree, or different caller must each get a fresh\n // Workspace/ProcessManager instead of reusing one bound to stale resources or\n // another user's PlatformSandbox credentials.\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const actingUserScope = actingUserId ? `-user-${encodeURIComponent(actingUserId)}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-repository-${projectRepositoryId}-${sandboxId}-${boundWorkdir}${extensionId}${actingUserScope}`;\n\n // Reuse the existing remote workspace if already registered (preserves the\n // reattached sandbox + ProcessManager state across re-opens).\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const sandbox = await reattachProjectSandbox(sandboxId, { actingUserId });\n const filesystem = new SandboxFilesystem({ sandbox, workdir: boundWorkdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Sandbox Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: skillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n const user = requestContext.get('user') as { workosId?: unknown; id?: unknown } | undefined;\n const actingUserId =\n typeof user?.workosId === 'string' ? user.workosId : typeof user?.id === 'string' ? user.id : undefined;\n\n // Repository-backed project: the repo lives inside a remote sandbox, not on\n // the server host. Reattach to the already-provisioned + materialized sandbox\n // and build a sandbox-backed Workspace. Optional embedders may add read-only\n // skill roots while project skills remain sandbox-backed.\n if (state?.projectRepositoryId && state.sandboxId && state.sandboxWorkdir) {\n return getSandboxWorkspace({\n projectRepositoryId: state.projectRepositoryId,\n sandboxId: state.sandboxId,\n workdir: state.sandboxWorkdir,\n worktreePath: state.worktreePath,\n configDir: state.configDir ?? DEFAULT_CONFIG_DIR,\n mastra,\n skillExtension,\n actingUserId,\n });\n }\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = MASTRACODE_WORKSPACE_TOOLS;\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n const userLsp = loadSettings().lsp ?? {};\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n const lspConfig: LSPConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GAEF,IAAI,CAAC,iBADiB,GAAG,aAAa,SACJ,GAAG,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;GACvB,KAAK,IAAI,QAAQ;GACjB,MAAM,KAAK,SAAS;EACtB;EAEA,IAAI,CAAC,iBAAiB;EAEtB,IAAI;GACF,MAAM,UAAU,GAAG,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC;GACjE,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,eAAe,GACvB,IAAI;IACF,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;IAChD,MAAM,WAAW,GAAG,aAAa,QAAQ;IACzC,IAAI,mBAAmB,CAAC,iBAAiB,UAAU,eAAe,GAAG;IAErE,IADa,GAAG,SAAS,QAClB,CAAC,CAAC,YAAY,GAAG;KACtB,MAAM,aAAa,KAA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AC,GAAG,IAAI;CACvE,MAAM,YAAuB;EAC3B,gBAAgB;EAChB,GAAG;EACH,eAAe,QAAQ,iBAAiB,oBAAoB,WAAW;EACvE,aAAa,CAAC,cAAc,GAAI,QAAQ,eAAe,CAAC,CAAE;CAC5D;CAGA,MAAM,aAAa,IAAI,gBAAgB;EACrC,UAAU;EACV;CACF,CAAC;CACD,OAAO,IAAI,UAAU;EACnB,IAAI;EACJ,MAAM;EACN;EACA,SAAS,IAAI,aAAa;GACxB,kBAAkB;GAClB,KAAK,gBAAgB;EACvB,CAAC;EACD,OAAO;EACP,QAAQ;EACR,GAAI,iBAAiB,EAAE,aAAa,eAAe,aAAa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
|
|
1
|
+
{"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\nimport { SandboxFilesystem } from './sandbox-filesystem.js';\nimport { reattachProjectSandbox } from './sandbox-reattach.js';\nimport { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\n/**\n * Build (or reuse) a sandbox-backed Workspace for a linked project repository. The sandbox\n * is reattached by its persisted provider id and a `SandboxFilesystem` is layered\n * over the in-sandbox checkout so file tools and command tools share one VM.\n */\nasync function getSandboxWorkspace({\n projectRepositoryId,\n sandboxId,\n workdir,\n worktreePath,\n configDir,\n mastra,\n skillExtension,\n actingUserId,\n}: {\n projectRepositoryId: string;\n sandboxId: string;\n workdir: string;\n worktreePath?: string;\n configDir: string;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n actingUserId?: string;\n}): Promise<Workspace> {\n // Bind the workspace to the active worktree when one is set, so file tools and\n // command tools operate inside the feature branch's working tree rather than\n // the base checkout. Falls back to the repo root when no worktree is active.\n const boundWorkdir = worktreePath || workdir;\n\n // Include the sandbox id, worktree path, and acting user in the reuse key: a\n // new sandbox, different worktree, or different caller must each get a fresh\n // Workspace/ProcessManager instead of reusing one bound to stale resources or\n // another user's PlatformSandbox credentials.\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const actingUserScope = actingUserId ? `-user-${encodeURIComponent(actingUserId)}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-repository-${projectRepositoryId}-${sandboxId}-${boundWorkdir}${extensionId}${actingUserScope}`;\n\n // Reuse the existing remote workspace if already registered (preserves the\n // reattached sandbox + ProcessManager state across re-opens).\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const sandbox = await reattachProjectSandbox(sandboxId, { actingUserId });\n const filesystem = new SandboxFilesystem({ sandbox, workdir: boundWorkdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Sandbox Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: skillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n const user = requestContext.get('user') as { workosId?: unknown; id?: unknown } | undefined;\n const actingUserId =\n typeof user?.workosId === 'string' ? user.workosId : typeof user?.id === 'string' ? user.id : undefined;\n\n // Repository-backed project: the repo lives inside a remote sandbox, not on\n // the server host. Reattach to the already-provisioned + materialized sandbox\n // and build a sandbox-backed Workspace. Optional embedders may add read-only\n // skill roots while project skills remain sandbox-backed.\n if (state?.projectRepositoryId && state.sandboxId && state.sandboxWorkdir) {\n return getSandboxWorkspace({\n projectRepositoryId: state.projectRepositoryId,\n sandboxId: state.sandboxId,\n workdir: state.sandboxWorkdir,\n worktreePath: state.worktreePath,\n configDir: state.configDir ?? DEFAULT_CONFIG_DIR,\n mastra,\n skillExtension,\n actingUserId,\n });\n }\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = MASTRACODE_WORKSPACE_TOOLS;\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];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,QAAQ,iBAAiB,oBAAoB,WAAW;GACvE,aAAa,CAAC,cAAc,GAAI,QAAQ,eAAe,CAAC,CAAE;EAC5D;CACF;CAGA,MAAM,aAAa,IAAI,gBAAgB;EACrC,UAAU;EACV;CACF,CAAC;CACD,OAAO,IAAI,UAAU;EACnB,IAAI;EACJ,MAAM;EACN;EACA,SAAS,IAAI,aAAa;GACxB,kBAAkB;GAClB,KAAK,gBAAgB;EACvB,CAAC;EACD,OAAO;EACP,QAAQ;EACR,GAAI,iBAAiB,EAAE,aAAa,eAAe,aAAa,YAAY,iBAAiB,EAAE,IAAI,CAAC;EACpG,KAAK;CACP,CAAC;AACH;;;;;;;;;AAUA,eAAsB,kBAAkB,EACtC,gBACA,UAIkC;CAClC,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,oBAAoB;GAAE;GAAgB;EAAO,CAAC;CAClE,QAAQ;EACN;CACF;CAEA,MAAM,WAAW,MAAM,qBAAqB,WAAW;EAAE;EAAgB;CAAU,CAAC;CACpF,MAAM,WAAuB,CAAC;CAC9B,KAAK,MAAM,QAAQ,2BACjB,IAAI,SAAS,OAAO,SAAS,QAAQ,SAAS;CAEhD,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,IAAI,WAAW,KAAA;AACvD"}
|
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type { MastraBrowser } from '@mastra/core/browser';
|
|
7
7
|
import type { LSPConfig } from '@mastra/core/workspace';
|
|
8
|
+
import type { ThinkingLevelSetting, ThinkingLevelSource } from '../thinking.js';
|
|
9
|
+
export { isThinkingLevelSetting, THINKING_LEVEL_VALUES } from '../thinking.js';
|
|
10
|
+
export type { ThinkingLevelSetting, ThinkingLevelSource } from '../thinking.js';
|
|
8
11
|
/** A saved custom pack — user-defined model selections for each mode. */
|
|
9
12
|
export interface CustomPack {
|
|
10
13
|
name: string;
|
|
@@ -54,8 +57,6 @@ export declare const MASTRA_GATEWAY_DEFAULT_URL = "https://gateway-api.mastra.ai
|
|
|
54
57
|
export declare const MEMORY_GATEWAY_PROVIDER = "mastra-gateway";
|
|
55
58
|
/** @deprecated Renamed to {@link MASTRA_GATEWAY_DEFAULT_URL}. */
|
|
56
59
|
export declare const MEMORY_GATEWAY_DEFAULT_URL = "https://gateway-api.mastra.ai";
|
|
57
|
-
/** Valid persisted thinking level values. */
|
|
58
|
-
export type ThinkingLevelSetting = 'off' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
59
60
|
/** Browser provider type. */
|
|
60
61
|
export type BrowserProvider = 'stagehand' | 'agent-browser';
|
|
61
62
|
/** Direct TUI `!` shell passthrough mode. */
|
|
@@ -258,7 +259,7 @@ export interface GlobalSettings {
|
|
|
258
259
|
memoryGateway: {
|
|
259
260
|
baseUrl?: string;
|
|
260
261
|
};
|
|
261
|
-
lsp?: LSPConfig;
|
|
262
|
+
lsp?: boolean | LSPConfig;
|
|
262
263
|
browser: BrowserSettings;
|
|
263
264
|
shellPassthrough: ShellPassthroughSettings;
|
|
264
265
|
voice: VoiceSettings;
|
|
@@ -295,8 +296,6 @@ export declare const OBSERVABILITY_AUTH_PREFIX = "observability:";
|
|
|
295
296
|
export declare const STORAGE_DEFAULTS: StorageSettings;
|
|
296
297
|
/** Default STT engine: on-device macOS recognizer where available, else cloud. */
|
|
297
298
|
export declare function defaultVoiceEngine(): VoiceEngine;
|
|
298
|
-
export declare const THINKING_LEVEL_VALUES: ThinkingLevelSetting[];
|
|
299
|
-
export declare function isThinkingLevelSetting(value: unknown): value is ThinkingLevelSetting;
|
|
300
299
|
export declare function getSettingsPath(): string;
|
|
301
300
|
export declare function getCustomProviderId(name: string): string;
|
|
302
301
|
export declare function toCustomProviderModelId(providerName: string, modelName: string): string;
|
|
@@ -312,6 +311,11 @@ export declare function toCustomProviderModelId(providerName: string, modelName:
|
|
|
312
311
|
*/
|
|
313
312
|
export declare function stripMastraCodeCustomProviderPrefix(modelId: string, customProviders: Array<Pick<CustomProviderSetting, 'name'>>): string;
|
|
314
313
|
export declare function parseCustomProviders(rawProviders: unknown): CustomProviderSetting[];
|
|
314
|
+
/**
|
|
315
|
+
* Resolve the effective LSP config. LSP is opt-in: `false` and an absent
|
|
316
|
+
* setting both mean disabled, `true` means enabled with defaults.
|
|
317
|
+
*/
|
|
318
|
+
export declare function resolveLspSetting(lsp: boolean | LSPConfig | undefined): LSPConfig | false;
|
|
315
319
|
export declare function migrateLegacyVariedPack(settings: GlobalSettings): boolean;
|
|
316
320
|
export declare function loadSettings(filePath?: string): GlobalSettings;
|
|
317
321
|
export declare const THREAD_ACTIVE_MODEL_PACK_ID_KEY = "activeModelPackId";
|
|
@@ -346,8 +350,6 @@ export declare function resolveModelDefaults(settings: GlobalSettings, builtinPa
|
|
|
346
350
|
id: string;
|
|
347
351
|
models: Record<string, string>;
|
|
348
352
|
}>): Record<string, string>;
|
|
349
|
-
/** Where a resolved default thinking level came from. */
|
|
350
|
-
export type ThinkingLevelSource = 'mode-default' | 'global';
|
|
351
353
|
/**
|
|
352
354
|
* Resolve the default reasoning-effort level for a mode.
|
|
353
355
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../../src/onboarding/settings.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../../src/onboarding/settings.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAQxD,OAAO,KAAK,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAChF,OAAO,EAAE,sBAAsB,EAAE,qB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AED;;;GAGG;AACH,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,cAAc,EAAE,eAAe,GAC9B,eAAe,GAAG,SAAS,CAS7B;AAMD;;;;GAIG;AACH,wBAAsB,yBAAyB,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CA4E7G"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getAppDataDir } from "../utils/project.js";
|
|
2
2
|
import { AuthStorage } from "../auth/storage.js";
|
|
3
|
+
import { THINKING_LEVEL_VALUES, isThinkingLevelSetting, resolveDefaultThinkingLevel as resolveDefaultThinkingLevel$1 } from "../thinking.js";
|
|
3
4
|
import { buildCodexStagehandFetch, createCodexMiddleware } from "../providers/openai-codex.js";
|
|
4
5
|
import { DEFAULT_STT_PROVIDER, resolveSTTModel } from "../voice/stt-registry.js";
|
|
5
6
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
@@ -117,7 +118,7 @@ const DEFAULTS = {
|
|
|
117
118
|
modelUseCounts: {},
|
|
118
119
|
updateDismissedVersion: null,
|
|
119
120
|
memoryGateway: {},
|
|
120
|
-
lsp:
|
|
121
|
+
lsp: false,
|
|
121
122
|
browser: {
|
|
122
123
|
enabled: false,
|
|
123
124
|
provider: "stagehand",
|
|
@@ -144,14 +145,6 @@ const DEFAULTS = {
|
|
|
144
145
|
localTracing: false
|
|
145
146
|
}
|
|
146
147
|
};
|
|
147
|
-
const THINKING_LEVEL_VALUES = [
|
|
148
|
-
"off",
|
|
149
|
-
"low",
|
|
150
|
-
"medium",
|
|
151
|
-
"high",
|
|
152
|
-
"xhigh",
|
|
153
|
-
"max"
|
|
154
|
-
];
|
|
155
148
|
const QUIET_MODE_MAX_TOOL_PREVIEW_LINES_MAX = 8;
|
|
156
149
|
const loadedSignalSettings = /* @__PURE__ */ new WeakMap();
|
|
157
150
|
function cloneSignalSettings(signals) {
|
|
@@ -165,10 +158,7 @@ function signalSettingsEqual(left, right) {
|
|
|
165
158
|
return left.unixSocketPubSub === right.unixSocketPubSub && left.experimentalGithubSignals === right.experimentalGithubSignals;
|
|
166
159
|
}
|
|
167
160
|
function parseThinkingLevel(value) {
|
|
168
|
-
return
|
|
169
|
-
}
|
|
170
|
-
function isThinkingLevelSetting(value) {
|
|
171
|
-
return typeof value === "string" && THINKING_LEVEL_VALUES.includes(value);
|
|
161
|
+
return isThinkingLevelSetting(value) ? value : DEFAULTS.preferences.thinkingLevel;
|
|
172
162
|
}
|
|
173
163
|
function parseModeThinkingDefaults(value) {
|
|
174
164
|
if (!value || typeof value !== "object") return {};
|
|
@@ -310,6 +300,23 @@ function parseStoredViewport(raw) {
|
|
|
310
300
|
return { ...VIEWPORT_PRESETS.desktop };
|
|
311
301
|
}
|
|
312
302
|
/**
|
|
303
|
+
* Validate the `lsp` setting from JSON. Accepts both the boolean opt-in/opt-out
|
|
304
|
+
* form and the full LSPConfig object; anything else is treated as unset.
|
|
305
|
+
*/
|
|
306
|
+
function parseLspSettings(raw) {
|
|
307
|
+
if (typeof raw === "boolean") return raw;
|
|
308
|
+
if (raw && typeof raw === "object") return raw;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Resolve the effective LSP config. LSP is opt-in: `false` and an absent
|
|
312
|
+
* setting both mean disabled, `true` means enabled with defaults.
|
|
313
|
+
*/
|
|
314
|
+
function resolveLspSetting(lsp) {
|
|
315
|
+
if (lsp === true) return {};
|
|
316
|
+
if (!lsp) return false;
|
|
317
|
+
return lsp;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
313
320
|
* Deep-merge and validate browser settings from JSON.
|
|
314
321
|
* Explicitly validates types to handle malformed settings.json gracefully.
|
|
315
322
|
*/
|
|
@@ -434,7 +441,7 @@ function migrateFromAuth(settingsPath) {
|
|
|
434
441
|
modelUseCounts: raw.modelUseCounts && typeof raw.modelUseCounts === "object" ? raw.modelUseCounts : {},
|
|
435
442
|
updateDismissedVersion: typeof raw.updateDismissedVersion === "string" ? raw.updateDismissedVersion : null,
|
|
436
443
|
memoryGateway: raw.memoryGateway && typeof raw.memoryGateway === "object" ? raw.memoryGateway : {},
|
|
437
|
-
lsp: raw.lsp
|
|
444
|
+
lsp: parseLspSettings(raw.lsp),
|
|
438
445
|
browser: parseBrowserSettings(raw.browser),
|
|
439
446
|
shellPassthrough: parseShellPassthroughSettings(raw.shellPassthrough),
|
|
440
447
|
voice: parseVoiceSettings(raw.voice),
|
|
@@ -526,7 +533,7 @@ function loadSettings(filePath = getSettingsPath()) {
|
|
|
526
533
|
modelUseCounts: raw.modelUseCounts && typeof raw.modelUseCounts === "object" ? raw.modelUseCounts : {},
|
|
527
534
|
updateDismissedVersion: typeof raw.updateDismissedVersion === "string" ? raw.updateDismissedVersion : null,
|
|
528
535
|
memoryGateway: raw.memoryGateway && typeof raw.memoryGateway === "object" ? raw.memoryGateway : {},
|
|
529
|
-
lsp: raw.lsp
|
|
536
|
+
lsp: parseLspSettings(raw.lsp),
|
|
530
537
|
browser: parseBrowserSettings(raw.browser),
|
|
531
538
|
shellPassthrough: parseShellPassthroughSettings(raw.shellPassthrough),
|
|
532
539
|
voice: parseVoiceSettings(raw.voice),
|
|
@@ -627,15 +634,10 @@ function resolveModelDefaults(settings, builtinPacks) {
|
|
|
627
634
|
* precedence over both and are handled by the caller.
|
|
628
635
|
*/
|
|
629
636
|
function resolveDefaultThinkingLevel(settings, mode) {
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
};
|
|
635
|
-
return {
|
|
636
|
-
level: settings.preferences.thinkingLevel,
|
|
637
|
-
source: "global"
|
|
638
|
-
};
|
|
637
|
+
return resolveDefaultThinkingLevel$1({
|
|
638
|
+
globalDefault: settings.preferences.thinkingLevel,
|
|
639
|
+
modeDefaults: settings.models.modeThinkingDefaults
|
|
640
|
+
}, mode);
|
|
639
641
|
}
|
|
640
642
|
/**
|
|
641
643
|
* Resolve the effective model ID for one of the two OM roles.
|
|
@@ -796,6 +798,6 @@ async function createBrowserFromSettings(settings) {
|
|
|
796
798
|
throw new Error(`Unsupported browser provider: ${provider}`);
|
|
797
799
|
}
|
|
798
800
|
//#endregion
|
|
799
|
-
export { MASTRA_GATEWAY_DEFAULT_URL, MASTRA_GATEWAY_PROVIDER, MEMORY_GATEWAY_DEFAULT_URL, MEMORY_GATEWAY_PROVIDER, OBSERVABILITY_AUTH_PREFIX, STORAGE_DEFAULTS, THINKING_LEVEL_VALUES, THREAD_ACTIVE_MODEL_PACK_ID_KEY, VIEWPORT_PRESETS, checkProfileProviderMismatch, createBrowserFromSettings, defaultVoiceEngine, getCustomProviderId, getProfileProvider, getSettingsPath, isThinkingLevelSetting, loadSettings, migrateLegacyVariedPack, parseCustomProviders, parseThreadSettings, parseViewportInput, resolveDefaultThinkingLevel, resolveModelDefaults, resolveOmModel, resolveOmRoleModel, resolveThreadActiveModelPackId, saveSettings, setProfileProvider, stripMastraCodeCustomProviderPrefix, toCustomProviderModelId };
|
|
801
|
+
export { MASTRA_GATEWAY_DEFAULT_URL, MASTRA_GATEWAY_PROVIDER, MEMORY_GATEWAY_DEFAULT_URL, MEMORY_GATEWAY_PROVIDER, OBSERVABILITY_AUTH_PREFIX, STORAGE_DEFAULTS, THINKING_LEVEL_VALUES, THREAD_ACTIVE_MODEL_PACK_ID_KEY, VIEWPORT_PRESETS, checkProfileProviderMismatch, createBrowserFromSettings, defaultVoiceEngine, getCustomProviderId, getProfileProvider, getSettingsPath, isThinkingLevelSetting, loadSettings, migrateLegacyVariedPack, parseCustomProviders, parseThreadSettings, parseViewportInput, resolveDefaultThinkingLevel, resolveLspSetting, resolveModelDefaults, resolveOmModel, resolveOmRoleModel, resolveThreadActiveModelPackId, saveSettings, setProfileProvider, stripMastraCodeCustomProviderPrefix, toCustomProviderModelId };
|
|
800
802
|
|
|
801
803
|
//# sourceMappingURL=settings.js.map
|