@mastra/code-sdk 1.19.0-alpha.9 → 1.19.1-alpha.0
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/instructions.js +2 -2
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/prompts/agent-instructions.d.ts +24 -1
- package/dist/agents/prompts/agent-instructions.d.ts.map +1 -1
- package/dist/agents/prompts/agent-instructions.js +386 -41
- package/dist/agents/prompts/agent-instructions.js.map +1 -1
- package/dist/agents/prompts/index.d.ts +3 -1
- package/dist/agents/prompts/index.d.ts.map +1 -1
- package/dist/agents/prompts/index.js +15 -5
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/manager.d.ts +17 -2
- package/dist/hooks/manager.d.ts.map +1 -1
- package/dist/hooks/manager.js +46 -17
- package/dist/hooks/manager.js.map +1 -1
- package/dist/hooks/types.d.ts +8 -0
- package/dist/hooks/types.d.ts.map +1 -1
- package/dist/hooks/types.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -6
- package/dist/index.js.map +1 -1
- package/dist/knowledge-inspector.d.ts.map +1 -1
- package/dist/knowledge-inspector.js +4 -9
- package/dist/knowledge-inspector.js.map +1 -1
- package/dist/knowledge-scope.d.ts +5 -4
- package/dist/knowledge-scope.d.ts.map +1 -1
- package/dist/knowledge-scope.js +7 -5
- package/dist/knowledge-scope.js.map +1 -1
- package/dist/onboarding/settings.d.ts +1 -0
- package/dist/onboarding/settings.d.ts.map +1 -1
- package/dist/onboarding/settings.js +13 -6
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/schedules/scheduler.d.ts.map +1 -1
- package/dist/schedules/scheduler.js +3 -2
- package/dist/schedules/scheduler.js.map +1 -1
- package/package.json +17 -17
|
@@ -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, realpathSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, normalize, relative, resolve, 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\nfunction realpathOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return resolve(path);\n }\n}\n\nfunction createProjectPathResolver(projectPath: string): (path: string) => string | null {\n const canonicalRoot = realpathOrResolved(projectPath);\n return path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n\n // Match an alias of the project root, not the target of a checkout-controlled\n // descendant symlink. Missing descendants must still resolve against the ref.\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if (realpathOrResolved(ancestor) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\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 = createProjectPathResolver(projectPath);\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n if (!rel) 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 getPathIdentity: (path: string) => string;\n} {\n const gitReader = createGitRefInstructionReader(projectPath, ref);\n const toRelative = createProjectPathResolver(projectPath);\n const canonicalRoot = realpathOrResolved(projectPath);\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 getPathIdentity: path => {\n const rel = toRelative(path);\n // Only canonicalize the project root: checkout symlinks do not define\n // file identity in the trusted ref, including files missing on disk.\n return rel === null ? realpathOrResolved(path) : join(canonicalRoot, rel);\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 instructionSourcePaths(loadAgentInstructions(projectPath, configDirName, projectReader), [projectPath]);\n}\n\n/**\n * Directories a session's project instructions load from: the host's\n * `instructionRoots` (resolved against the working directory, the session's\n * own checkout first) when it sets any, else the working directory itself.\n */\nexport function sessionInstructionRoots(workingDir: string, instructionRoots?: readonly string[]): string[] {\n if (!instructionRoots?.length) return [workingDir];\n return [...new Set(instructionRoots.map(root => resolve(workingDir, root)))];\n}\n\n/**\n * The instruction files a session's system prompt carries. Global files load\n * once (unless `skipGlobal`), then each instruction root's project files, in\n * root order. An untrusted checkout never reads project files off the working\n * tree: with a `baseRef` the first root (the session's own checkout) is served\n * from that ref and the other roots are skipped; without one no project files\n * load.\n */\nexport function loadSessionInstructions({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): InstructionSource[] {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const primaryReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(primary!, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const sources = loadAgentInstructions(primary!, configDir, primaryReader, { skipGlobal });\n if (untrustedCheckout) return sources;\n for (const root of others) {\n sources.push(...loadAgentInstructions(root, configDir, undefined, { skipGlobal: true }));\n }\n return sources;\n}\n\n/**\n * Paths of loaded instruction sources, each project source also under its\n * root's canonical path, so reactive reminders never repeat a file the\n * system prompt already carries.\n */\nexport function instructionSourcePaths(sources: InstructionSource[], roots: readonly string[]): string[] {\n return sources.flatMap(source => {\n const path = normalize(source.path);\n if (source.scope !== 'project') return [path];\n const root = roots.find(candidate => {\n const rel = relative(candidate, path);\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);\n });\n if (!root) return [path];\n const canonicalPath = join(realpathOrResolved(root), relative(root, path));\n return path === canonicalPath ? [path] : [path, canonicalPath];\n });\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')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K,mBAAmB,IAAI,GAAG,SAAS,MAAM,IAAI,CAAC;EACzE,OAAO,SAAS,gBAAgB,CAAC,IAAI,IAAI,CAAC,MAAM,aAAa;CAC/D,CAAC;AACH;;AAGA,MAAa,6BAA6B;;;;;;;AAQ1C,SAAgB,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"}
|
|
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, spawn } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport { readFile, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, normalize, relative, resolve, 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\nfunction realpathOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return resolve(path);\n }\n}\n\nfunction createProjectPathResolver(projectPath: string): (path: string) => string | null {\n const canonicalRoot = realpathOrResolved(projectPath);\n return path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n\n // Match an alias of the project root, not the target of a checkout-controlled\n // descendant symlink. Missing descendants must still resolve against the ref.\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if (realpathOrResolved(ancestor) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\n}\n\n// Keys count towards the limit too: a path a folder lacks is cached as an empty listing.\nconst GIT_OBJECT_CACHE_MAX_CHARS = 16 * 1024 * 1024;\nconst gitObjectOutputs = new Map<string, string>();\nlet gitObjectCacheChars = 0;\n\n// The cache is shared by every checkout in the process, so a read is kept only once it is known to\n// match its id: git checks the tree it is asked to list, and `matchesId` covers what git does not check.\n// A blobless clone fetches file content over the network, so a failed read is never cached.\nfunction gitObjectRead(\n projectPath: string,\n args: string[],\n matchesId: (output: Buffer) => boolean = () => true,\n): string | null {\n const key = args.join('\\0');\n const cached = gitObjectOutputs.get(key);\n if (cached !== undefined) return cached;\n try {\n const raw = execFileSync('git', ['--no-replace-objects', '-C', projectPath, '--literal-pathspecs', ...args], {\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n if (!matchesId(raw)) return null;\n const output = raw.toString('utf-8');\n gitObjectOutputs.set(key, output);\n gitObjectCacheChars += key.length + output.length;\n for (const [oldest, evicted] of gitObjectOutputs) {\n if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;\n gitObjectOutputs.delete(oldest);\n gitObjectCacheChars -= oldest.length + evicted.length;\n }\n return output;\n } catch {\n return null;\n }\n}\n\nfunction blobMatchesId(id: string, content: Buffer): boolean {\n const hash = createHash(id.length === 40 ? 'sha1' : 'sha256');\n return hash.update(`blob ${content.length}\\0`).update(content).digest('hex') === id;\n}\n\nfunction createGitRefLookup(projectPath: string, ref: string) {\n // Resolved on first use and kept, so a lookup reads the ref as it stood then: build one per model step.\n let trees: string[] | undefined;\n const resolveTrees = (): string[] => {\n // A ref name never holds a space or control character, and each line of the batch below names\n // one object, so a line break in `ref` would add names of its own, such as the checkout's `HEAD`.\n if ([...ref].some(char => char <= ' ' || char === '\\x7f')) return [];\n try {\n const output = execFileSync('git', ['-C', projectPath, 'cat-file', '--batch-check=%(objectname)'], {\n encoding: 'utf-8',\n input: `origin/${ref}^{tree}\\n${ref}^{tree}\\n`,\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n return [...new Set(output.split('\\n').filter(line => /^[0-9a-f]+$/.test(line)))];\n } catch {\n return [];\n }\n };\n // One folder level per call: git hash-checks the tree it lists, not the trees it walks through.\n const entryAt = (tree: string, rel: string): string[] => {\n let entry = ['', 'tree', tree];\n for (const name of rel.split('/')) {\n if (entry[1] !== 'tree') return [];\n entry = gitObjectRead(projectPath, ['ls-tree', '--full-tree', entry[2]!, '--', name])?.split(/\\s/) ?? [];\n }\n return entry;\n };\n return {\n type: (rel: string): string | null => {\n for (const tree of (trees ??= resolveTrees())) {\n const [, type] = entryAt(tree, rel);\n if (type) return type;\n }\n return null;\n },\n show: (rel: string): string | null => {\n for (const tree of (trees ??= resolveTrees())) {\n const [, type, blob] = entryAt(tree, rel);\n if (type !== 'blob' || !blob) continue;\n const content = gitObjectRead(projectPath, ['cat-file', 'blob', blob], raw => blobMatchesId(blob, raw));\n if (content !== null) return content;\n }\n return null;\n },\n };\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 the blob at `<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 = createProjectPathResolver(projectPath);\n const lookup = createGitRefLookup(projectPath, ref);\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n return rel ? lookup.show(rel) : 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 getPathIdentity: (path: string) => string;\n} {\n const toRelative = createProjectPathResolver(projectPath);\n const canonicalRoot = realpathOrResolved(projectPath);\n const lookup = createGitRefLookup(projectPath, ref);\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n return lookup.type(rel);\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 const content = rel ? lookup.show(rel) : null;\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n getPathIdentity: path => {\n const rel = toRelative(path);\n // Only canonicalize the project root: checkout symlinks do not define\n // file identity in the trusted ref, including files missing on disk.\n return rel === null ? realpathOrResolved(path) : join(canonicalRoot, rel);\n },\n };\n}\n\n// Keep in-flight object reads shared across concurrent prompt and reminder lookups.\nconst pendingGitObjects = new Map<string, Promise<string | null>>();\n\nfunction gitAsync(args: string[], input?: string): Promise<Buffer | null> {\n return new Promise(resolveOutput => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('git', args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });\n } catch {\n resolveOutput(null);\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n let failed = false;\n child.stdout?.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > 1024 * 1024) {\n failed = true;\n child.kill();\n } else chunks.push(chunk);\n });\n child.on('error', () => {\n failed = true;\n });\n child.on('close', code => resolveOutput(!failed && code === 0 ? Buffer.concat(chunks) : null));\n if (input !== undefined) {\n child.stdin?.on('error', () => {\n failed = true;\n });\n child.stdin?.end(input);\n }\n });\n}\n\nasync function gitObjectReadAsync(\n projectPath: string,\n args: string[],\n matchesId: (raw: Buffer) => boolean = () => true,\n): Promise<string | null> {\n const key = args.join('\\0');\n const cached = gitObjectOutputs.get(key);\n if (cached !== undefined) return cached;\n const pendingKey = `${projectPath}\\0${key}`;\n let pending = pendingGitObjects.get(pendingKey);\n if (!pending) {\n pending = (async () => {\n const raw = await gitAsync(['--no-replace-objects', '-C', projectPath, '--literal-pathspecs', ...args]);\n if (!raw || !matchesId(raw)) return null;\n const output = raw.toString('utf-8');\n gitObjectOutputs.set(key, output);\n gitObjectCacheChars += key.length + output.length;\n for (const [oldest, evicted] of gitObjectOutputs) {\n if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;\n gitObjectOutputs.delete(oldest);\n gitObjectCacheChars -= oldest.length + evicted.length;\n }\n return output;\n })();\n pendingGitObjects.set(pendingKey, pending);\n void pending.then(\n () => pendingGitObjects.delete(pendingKey),\n () => pendingGitObjects.delete(pendingKey),\n );\n }\n return pending;\n}\n\nasync function realpathOrResolvedAsync(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch {\n return resolve(path);\n }\n}\n\nasync function createProjectPathResolverAsync(projectPath: string): Promise<(path: string) => Promise<string | null>> {\n const canonicalRoot = await realpathOrResolvedAsync(projectPath);\n return async path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if ((await realpathOrResolvedAsync(ancestor)) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\n}\n\nfunction createGitRefLookupAsync(projectPath: string, ref: string) {\n let trees: Promise<string[]> | undefined;\n const resolveTrees = async (): Promise<string[]> => {\n if ([...ref].some(char => char <= ' ' || char === '\\x7f')) return [];\n const raw = await gitAsync(\n ['-C', projectPath, 'cat-file', '--batch-check=%(objectname)'],\n `origin/${ref}^{tree}\\n${ref}^{tree}\\n`,\n );\n return raw\n ? [\n ...new Set(\n raw\n .toString('utf-8')\n .split('\\n')\n .filter(line => /^[0-9a-f]+$/.test(line)),\n ),\n ]\n : [];\n };\n const entryAt = async (tree: string, rel: string): Promise<string[]> => {\n let entry = ['', 'tree', tree];\n for (const name of rel.split('/')) {\n if (entry[1] !== 'tree') return [];\n entry =\n (await gitObjectReadAsync(projectPath, ['ls-tree', '--full-tree', entry[2]!, '--', name]))?.split(/\\s/) ?? [];\n }\n return entry;\n };\n return {\n type: async (rel: string): Promise<string | null> => {\n for (const tree of await (trees ??= resolveTrees())) {\n const [, type] = await entryAt(tree, rel);\n if (type) return type;\n }\n return null;\n },\n show: async (rel: string): Promise<string | null> => {\n for (const tree of await (trees ??= resolveTrees())) {\n const [, type, blob] = await entryAt(tree, rel);\n if (type !== 'blob' || !blob) continue;\n const content = await gitObjectReadAsync(projectPath, ['cat-file', 'blob', blob], raw =>\n blobMatchesId(blob, raw),\n );\n if (content !== null) return content;\n }\n return null;\n },\n };\n}\n\nexport async function createGitRefInstructionReaderAsync(\n projectPath: string,\n ref: string,\n): Promise<AsyncInstructionFileReader> {\n const toRelative = await createProjectPathResolverAsync(projectPath);\n const lookup = createGitRefLookupAsync(projectPath, ref);\n const show = async (path: string) => {\n const rel = await toRelative(path);\n return rel ? lookup.show(rel) : null;\n };\n return {\n ref,\n exists: async path => (await show(path)) !== null,\n read: async path => {\n const content = await show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\nexport function createGitRefReminderReaderAsync(projectPath: string, ref: string) {\n const toRelative = createProjectPathResolverAsync(projectPath);\n const canonicalRoot = realpathOrResolvedAsync(projectPath);\n const lookup = createGitRefLookupAsync(projectPath, ref);\n const objectType = (rel: string) => (rel === '' ? Promise.resolve('tree') : lookup.type(rel));\n return {\n pathExists: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n }\n return (await objectType(rel)) !== null;\n },\n isDirectory: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) {\n try {\n return (await stat(path)).isDirectory();\n } catch {\n return false;\n }\n }\n return (await objectType(rel)) === 'tree';\n },\n readFile: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) return readFile(path, 'utf-8');\n const content = rel ? await lookup.show(rel) : null;\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n getPathIdentity: async (path: string) => {\n const rel = await (await toRelative)(path);\n return rel === null ? realpathOrResolvedAsync(path) : join(await canonicalRoot, rel);\n },\n };\n}\n\nexport interface AsyncInstructionFileReader {\n exists(path: string): Promise<boolean>;\n read(path: string): Promise<string>;\n ref?: string;\n}\n\nconst fsInstructionReaderAsync: AsyncInstructionFileReader = {\n exists: async path => {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n },\n read: path => readFile(path, 'utf-8'),\n};\n\nexport async function loadAgentInstructionsAsync(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: AsyncInstructionFileReader = fsInstructionReaderAsync,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): Promise<InstructionSource[]> {\n const sources: InstructionSource[] = [];\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 if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n for (const location of globalLocations) {\n const base = join(homedir(), location);\n for (const filename of INSTRUCTION_FILES) {\n const path = join(base, filename);\n if (!(await fsInstructionReaderAsync.exists(path))) continue;\n try {\n const content = (await fsInstructionReaderAsync.read(path)).trim();\n if (content) {\n sources.push({ path, content, scope: 'global' });\n break;\n }\n } catch {\n /* Skip unreadable instructions. */\n }\n break;\n }\n if (sources.length) break;\n }\n for (const location of projectLocations) {\n const base = location ? join(projectPath, location) : projectPath;\n for (const filename of INSTRUCTION_FILES) {\n const path = join(base, filename);\n if (!(await projectReader.exists(path))) continue;\n try {\n const content = (await projectReader.read(path)).trim();\n if (content) {\n sources.push({ path, content, scope: 'project', ...(projectReader.ref ? { ref: projectReader.ref } : {}) });\n break;\n }\n } catch {\n /* Skip unreadable instructions. */\n }\n break;\n }\n if (sources.some(source => source.scope === 'project')) break;\n }\n return sources;\n}\n\nexport async function loadSessionInstructionsAsync({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): Promise<InstructionSource[]> {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const reader = untrustedCheckout\n ? baseRef\n ? await createGitRefInstructionReaderAsync(primary!, baseRef)\n : { exists: async () => false, read: async () => '' }\n : undefined;\n const sources = await loadAgentInstructionsAsync(primary!, configDir, reader, { skipGlobal });\n if (!untrustedCheckout) {\n for (const root of others)\n sources.push(...(await loadAgentInstructionsAsync(root, configDir, undefined, { skipGlobal: true })));\n }\n return sources;\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 instructionSourcePaths(loadAgentInstructions(projectPath, configDirName, projectReader), [projectPath]);\n}\n\n/**\n * Directories a session's project instructions load from: the host's\n * `instructionRoots` (resolved against the working directory, the session's\n * own checkout first) when it sets any, else the working directory itself.\n */\nexport function sessionInstructionRoots(workingDir: string, instructionRoots?: readonly string[]): string[] {\n if (!instructionRoots?.length) return [workingDir];\n return [...new Set(instructionRoots.map(root => resolve(workingDir, root)))];\n}\n\n/**\n * The instruction files a session's system prompt carries. Global files load\n * once (unless `skipGlobal`), then each instruction root's project files, in\n * root order. An untrusted checkout never reads project files off the working\n * tree: with a `baseRef` the first root (the session's own checkout) is served\n * from that ref and the other roots are skipped; without one no project files\n * load.\n */\nexport function loadSessionInstructions({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): InstructionSource[] {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const primaryReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(primary!, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const sources = loadAgentInstructions(primary!, configDir, primaryReader, { skipGlobal });\n if (untrustedCheckout) return sources;\n for (const root of others) {\n sources.push(...loadAgentInstructions(root, configDir, undefined, { skipGlobal: true }));\n }\n return sources;\n}\n\n/**\n * Paths of loaded instruction sources, each project source also under its\n * root's canonical path, so reactive reminders never repeat a file the\n * system prompt already carries.\n */\nexport function instructionSourcePaths(sources: InstructionSource[], roots: readonly string[]): string[] {\n return sources.flatMap(source => {\n const path = normalize(source.path);\n if (source.scope !== 'project') return [path];\n const root = roots.find(candidate => {\n const rel = relative(candidate, path);\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);\n });\n if (!root) return [path];\n const canonicalPath = join(realpathOrResolved(root), relative(root, path));\n return path === canonicalPath ? [path] : [path, canonicalPath];\n });\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":";;;;;;;;;;;;AAcA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;AACF;AAEA,MAAM,mBAAmB;CAAC;CAAW;CAAe;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;EACvB,MAAM,gBAAgB,KAAK,mBAAmB,IAAI,GAAG,SAAS,MAAM,IAAI,CAAC;EACzE,OAAO,SAAS,gBAAgB,CAAC,IAAI,IAAI,CAAC,MAAM,aAAa;CAC/D,CAAC;AACH;;AAGA,MAAa,6BAA6B;;;;;;;AAQ1C,SAAgB,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"}
|
|
@@ -6,6 +6,7 @@ export { planModePrompt } from './plan.js';
|
|
|
6
6
|
export { fastModePrompt } from './fast.js';
|
|
7
7
|
import type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';
|
|
8
8
|
import type { RequestContextReader } from '../../auth/account-routing-context.js';
|
|
9
|
+
import type { InstructionSource } from './agent-instructions.js';
|
|
9
10
|
export interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {
|
|
10
11
|
modeId: string;
|
|
11
12
|
state?: any;
|
|
@@ -51,9 +52,10 @@ export declare function joinPromptSections(sections: PromptSection[]): string;
|
|
|
51
52
|
* Combines the base prompt with mode-specific instructions.
|
|
52
53
|
*/
|
|
53
54
|
export declare function buildFullPrompt(ctx: PromptContext): string;
|
|
55
|
+
export declare function buildFullPromptSectionsAsync(ctx: PromptContext): Promise<PromptSection[]>;
|
|
54
56
|
/**
|
|
55
57
|
* Build the system prompt as labeled sections. `buildFullPrompt` is the join of
|
|
56
58
|
* these, so the two can never disagree about what the model receives.
|
|
57
59
|
*/
|
|
58
|
-
export declare function buildFullPromptSections(ctx: PromptContext): PromptSection[];
|
|
60
|
+
export declare function buildFullPromptSections(ctx: PromptContext, loadedInstructions?: InstructionSource[]): PromptSection[];
|
|
59
61
|
//# 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;AACpF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,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;AACpF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAYlF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAQjE,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,0FAA0F;IAC1F,cAAc,CAAC,EAAE,oBAAoB,CAAC;IACtC,sFAAsF;IACtF,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,4FAA4F;IAC5F,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,6FAA6F;IAC7F,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,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,wBAAsB,4BAA4B,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAY/F;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,aAAa,EAAE,kBAAkB,CAAC,EAAE,iBAAiB,EAAE,GAAG,aAAa,EAAE,CAgIrH"}
|
|
@@ -7,7 +7,7 @@ import "../../tools/index.js";
|
|
|
7
7
|
import { getLocalPlansRelativeDir } from "../../utils/plans.js";
|
|
8
8
|
import { hasParallelKey, hasTavilyKey } from "../../tools/web-search.js";
|
|
9
9
|
import { resolveProviderWebSearchRoute } from "../model.js";
|
|
10
|
-
import { AGENT_INSTRUCTIONS_HEADING, formatInstructionSource, loadSessionInstructions } from "./agent-instructions.js";
|
|
10
|
+
import { AGENT_INSTRUCTIONS_HEADING, formatInstructionSource, loadSessionInstructions, loadSessionInstructionsAsync } from "./agent-instructions.js";
|
|
11
11
|
import { modelSpecificPrompts } from "./model.js";
|
|
12
12
|
import { buildToolGuidance } from "./tool-guidance.js";
|
|
13
13
|
import { buildBasePrompt } from "@mastra/core/coding-agent";
|
|
@@ -28,11 +28,21 @@ function joinPromptSections(sections) {
|
|
|
28
28
|
function buildFullPrompt(ctx) {
|
|
29
29
|
return joinPromptSections(buildFullPromptSections(ctx));
|
|
30
30
|
}
|
|
31
|
+
async function buildFullPromptSectionsAsync(ctx) {
|
|
32
|
+
return buildFullPromptSections(ctx, ctx.workingDir ? await loadSessionInstructionsAsync({
|
|
33
|
+
workingDir: ctx.workingDir,
|
|
34
|
+
instructionRoots: Array.isArray(ctx.state?.instructionRoots) ? ctx.state.instructionRoots : void 0,
|
|
35
|
+
configDir: ctx.state?.configDir,
|
|
36
|
+
untrustedCheckout: ctx.state?.untrustedCheckout === true,
|
|
37
|
+
baseRef: typeof ctx.state?.baseRef === "string" ? ctx.state.baseRef : void 0,
|
|
38
|
+
skipGlobal: ctx.state?.skipGlobalInstructions === true
|
|
39
|
+
}) : []);
|
|
40
|
+
}
|
|
31
41
|
/**
|
|
32
42
|
* Build the system prompt as labeled sections. `buildFullPrompt` is the join of
|
|
33
43
|
* these, so the two can never disagree about what the model receives.
|
|
34
44
|
*/
|
|
35
|
-
function buildFullPromptSections(ctx) {
|
|
45
|
+
function buildFullPromptSections(ctx, loadedInstructions) {
|
|
36
46
|
const hasWebExtract = hasParallelKey() || hasTavilyKey();
|
|
37
47
|
const hasWebSearch = hasWebExtract || resolveProviderWebSearchRoute(ctx.modelId, { requestContext: ctx.requestContext }) !== void 0;
|
|
38
48
|
const deniedTools = /* @__PURE__ */ new Set();
|
|
@@ -80,14 +90,14 @@ function buildFullPromptSections(ctx) {
|
|
|
80
90
|
const configDir = ctx.state?.configDir;
|
|
81
91
|
const baseRef = typeof ctx.state?.baseRef === "string" ? ctx.state.baseRef : void 0;
|
|
82
92
|
const instructionRoots = Array.isArray(ctx.state?.instructionRoots) ? ctx.state.instructionRoots : void 0;
|
|
83
|
-
const instructionSources = ctx.workingDir ? loadSessionInstructions({
|
|
93
|
+
const instructionSources = loadedInstructions ?? (ctx.workingDir ? loadSessionInstructions({
|
|
84
94
|
workingDir: ctx.workingDir,
|
|
85
95
|
instructionRoots,
|
|
86
96
|
configDir,
|
|
87
97
|
untrustedCheckout: ctx.state?.untrustedCheckout === true,
|
|
88
98
|
baseRef,
|
|
89
99
|
skipGlobal: ctx.state?.skipGlobalInstructions === true
|
|
90
|
-
}) : [];
|
|
100
|
+
}) : []);
|
|
91
101
|
const instructionSections = instructionSources.map((source, index) => {
|
|
92
102
|
const isFirst = index === 0;
|
|
93
103
|
const isLast = index === instructionSources.length - 1;
|
|
@@ -128,6 +138,6 @@ function buildFullPromptSections(ctx) {
|
|
|
128
138
|
}
|
|
129
139
|
].filter((section) => Boolean(section.content));
|
|
130
140
|
}
|
|
131
|
-
export { buildFullPrompt, buildFullPromptSections, buildModePrompt, buildModePromptFn, fastModePrompt, joinPromptSections, planModePrompt };
|
|
141
|
+
export { buildFullPrompt, buildFullPromptSections, buildFullPromptSectionsAsync, buildModePrompt, buildModePromptFn, fastModePrompt, joinPromptSections, planModePrompt };
|
|
132
142
|
|
|
133
143
|
//# 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 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 /** Host-configured workspace-relative plans directory (see `MastraCodeConfig.plansDir`). */\n plansDir?: 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, plansDir: ctx.plansDir }),\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 planApprovalStartsGoal: ctx.planApprovalStartsGoal,\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":";;;;;;;;;;;;;;AA0CA,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;CAG3E,MAAM,gBAAgB,eAAe,KAAK,aAAa;CACvD,MAAM,eACJ,iBAAiB,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
|
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 {\n loadSessionInstructions,\n loadSessionInstructionsAsync,\n formatInstructionSource,\n AGENT_INSTRUCTIONS_HEADING,\n} from './agent-instructions.js';\nimport type { InstructionSource } 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 /** Host-configured workspace-relative plans directory (see `MastraCodeConfig.plansDir`). */\n plansDir?: 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\nexport async function buildFullPromptSectionsAsync(ctx: PromptContext): Promise<PromptSection[]> {\n const sources = ctx.workingDir\n ? await loadSessionInstructionsAsync({\n workingDir: ctx.workingDir,\n instructionRoots: Array.isArray(ctx.state?.instructionRoots) ? ctx.state.instructionRoots : undefined,\n configDir: ctx.state?.configDir,\n untrustedCheckout: ctx.state?.untrustedCheckout === true,\n baseRef: typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined,\n skipGlobal: ctx.state?.skipGlobalInstructions === true,\n })\n : [];\n return buildFullPromptSections(ctx, sources);\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, loadedInstructions?: InstructionSource[]): 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, plansDir: ctx.plansDir }),\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 planApprovalStartsGoal: ctx.planApprovalStartsGoal,\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 =\n loadedInstructions ??\n (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":";;;;;;;;;;;;;;AAgDA,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;AAEA,eAAsB,6BAA6B,KAA8C;CAW/F,OAAO,wBAAwB,KAVf,IAAI,aAChB,MAAM,6BAA6B;EACjC,YAAY,IAAI;EAChB,kBAAkB,MAAM,QAAQ,IAAI,OAAO,gBAAgB,IAAI,IAAI,MAAM,mBAAmB,KAAA;EAC5F,WAAW,IAAI,OAAO;EACtB,mBAAmB,IAAI,OAAO,sBAAsB;EACpD,SAAS,OAAO,IAAI,OAAO,YAAY,WAAW,IAAI,MAAM,UAAU,KAAA;EACtE,YAAY,IAAI,OAAO,2BAA2B;CACpD,CAAC,IACD,CAAC,CACsC;AAC7C;;;;;AAMA,SAAgB,wBAAwB,KAAoB,oBAA2D;CAGrH,MAAM,gBAAgB,eAAe,KAAK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AAQ,QAAQ,OAAO,CAAC;AAC9C"}
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -2,5 +2,5 @@ export { HookManager } from './manager.js';
|
|
|
2
2
|
export { loadHooksConfig, getProjectHooksPath, getGlobalHooksPath, VALID_EVENTS } from './config.js';
|
|
3
3
|
export { executeHook, runHooksForEvent, matchesHook } from './executor.js';
|
|
4
4
|
export { isBlockingEvent } from './types.js';
|
|
5
|
-
export type { HookEventName, HookDefinition, HookMatcher, HooksConfig, HookStdin, HookStdinBase, HookStdinToolEvent, HookStdinUserPrompt, HookStdinStop, HookStdinSession, HookStdinNotification, HookStdinAgentStart, HookStdinAgentEnd, HookStdinPermissionRequest, HookStdinPermissionResult, HookStdinInterrupt, HookStdinSubagentStart, HookStdinSubagentEnd, HookStdout, HookResult, HookEventResult, BlockingHookEvent, LifecycleHookEvent, PermissionKind, PermissionDecision, InterruptReason, } from './types.js';
|
|
5
|
+
export type { HookEventName, HookDefinition, HookMatcher, HooksConfig, HookStdin, HookStdinBase, HookStdinToolEvent, HookStdinUserPrompt, HookStdinStop, HookStdinSession, SessionStartSource, HookStdinNotification, HookStdinAgentStart, HookStdinAgentEnd, HookStdinPermissionRequest, HookStdinPermissionResult, HookStdinInterrupt, HookStdinSubagentStart, HookStdinSubagentEnd, HookStdout, HookResult, HookEventResult, BlockingHookEvent, LifecycleHookEvent, PermissionKind, PermissionDecision, InterruptReason, } from './types.js';
|
|
6
6
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACrG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,YAAY,EACV,aAAa,EACb,cAAc,EACd,WAAW,EACX,WAAW,EACX,SAAS,EACT,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB,qBAAqB,EACrB,mBAAmB,EACnB,iBAAiB,EACjB,0BAA0B,EAC1B,yBAAyB,EACzB,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,kBAAkB,EAClB,eAAe,GAChB,MAAM,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACrG,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,YAAY,EACV,aAAa,EACb,cAAc,EACd,WAAW,EACX,WAAW,EACX,SAAS,EACT,aAAa,EACb,kBAAkB,EAClB,mBAAmB,EACnB,aAAa,EACb,gBAAgB,EAChB,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,iBAAiB,EACjB,0BAA0B,EAC1B,yBAAyB,EACzB,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,UAAU,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,kBAAkB,EAClB,eAAe,GAChB,MAAM,YAAY,CAAC"}
|
package/dist/hooks/manager.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HooksConfig, HookEventResult, PermissionKind, PermissionDecision, InterruptReason, SessionWorktreeInfo } from './types.js';
|
|
1
|
+
import type { HooksConfig, HookEventResult, SessionStartSource, PermissionKind, PermissionDecision, InterruptReason, SessionWorktreeInfo } from './types.js';
|
|
2
2
|
export declare class HookManager {
|
|
3
3
|
private config;
|
|
4
4
|
private projectDir;
|
|
@@ -7,9 +7,24 @@ export declare class HookManager {
|
|
|
7
7
|
private homeDir?;
|
|
8
8
|
private runId?;
|
|
9
9
|
private worktree?;
|
|
10
|
+
/** True once SessionStart has fired, so later thread binds announce themselves. */
|
|
11
|
+
private sessionStarted;
|
|
12
|
+
/**
|
|
13
|
+
* The latest queued SessionStart, settled or not. SessionStart runs one after another,
|
|
14
|
+
* and other events wait for it, so hooks see each session in order and before its events.
|
|
15
|
+
*/
|
|
16
|
+
private pendingSessionStart?;
|
|
10
17
|
constructor(projectDir: string, sessionId: string, configDirName?: string, homeDir?: string, worktree?: SessionWorktreeInfo);
|
|
11
18
|
reload(): void;
|
|
19
|
+
/**
|
|
20
|
+
* Bind hooks to a thread. After SessionStart has fired, binding a different thread
|
|
21
|
+
* (the first message creating one, `/new`, a resumed thread) fires SessionStart again
|
|
22
|
+
* with `source: 'thread_change'`, so a hook that tracks sessions learns the new id
|
|
23
|
+
* before any event of that thread reaches it.
|
|
24
|
+
*/
|
|
12
25
|
setSessionId(sessionId: string): void;
|
|
26
|
+
/** Dispatch an event's hooks once any queued SessionStart has finished. */
|
|
27
|
+
private dispatch;
|
|
13
28
|
/** Set the active agent run id. Included as `run_id` in all hook stdin while a run is active. */
|
|
14
29
|
setRunId(runId: string): void;
|
|
15
30
|
/** Clear the active run id. Call only after end-of-run hooks (AgentEnd, Stop) have been dispatched. */
|
|
@@ -36,7 +51,7 @@ export declare class HookManager {
|
|
|
36
51
|
runPostToolUse(toolName: string, toolInput: unknown, toolOutput: unknown, toolError: boolean): Promise<HookEventResult>;
|
|
37
52
|
runUserPromptSubmit(userMessage: string): Promise<HookEventResult>;
|
|
38
53
|
runStop(assistantMessage: string | undefined, stopReason: 'complete' | 'aborted' | 'error'): Promise<HookEventResult>;
|
|
39
|
-
runSessionStart(): Promise<HookEventResult>;
|
|
54
|
+
runSessionStart(source?: SessionStartSource): Promise<HookEventResult>;
|
|
40
55
|
runSessionEnd(): Promise<HookEventResult>;
|
|
41
56
|
/**
|
|
42
57
|
* Fire notification hooks (non-blocking, fire-and-forget).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/hooks/manager.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,
|
|
1
|
+
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/hooks/manager.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EAMf,kBAAkB,EASlB,cAAc,EACd,kBAAkB,EAClB,eAAe,EACf,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAIpB,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,KAAK,CAAC,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAC,CAAsB;IACvC,mFAAmF;IACnF,OAAO,CAAC,cAAc,CAAS;IAC/B;;;OAGG;IACH,OAAO,CAAC,mBAAmB,CAAC,CAAgB;IAE5C,YACE,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,aAAa,SAAqB,EAClC,OAAO,CAAC,EAAE,MAAM,EAChB,QAAQ,CAAC,EAAE,mBAAmB,EAQ/B;IAED,MAAM,IAAI,IAAI,CAEb;IAED;;;;;OAKG;IACH,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAMpC;IAED,2EAA2E;YAC7D,QAAQ;I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oBAAoB,CACxB,cAAc,EAAE,cAAc,EAC9B,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,OAAO,GAClB,OAAO,CAAC,eAAe,CAAC,CAoB1B;IAEK,mBAAmB,CACvB,cAAc,EAAE,cAAc,EAC9B,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,kBAAkB,EAC5B,SAAS,CAAC,EAAE,OAAO,GAClB,OAAO,CAAC,eAAe,CAAC,CAsB1B;IAEK,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAkBpE;IAEK,gBAAgB,CACpB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,OAAO,GACf,OAAO,CAAC,eAAe,CAAC,CAqB1B;IAEK,cAAc,CAClB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,OAAO,EACf,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,CAAC,CAqB1B;CACF"}
|
package/dist/hooks/manager.js
CHANGED
|
@@ -19,6 +19,13 @@ var HookManager = class {
|
|
|
19
19
|
homeDir;
|
|
20
20
|
runId;
|
|
21
21
|
worktree;
|
|
22
|
+
/** True once SessionStart has fired, so later thread binds announce themselves. */
|
|
23
|
+
sessionStarted = false;
|
|
24
|
+
/**
|
|
25
|
+
* The latest queued SessionStart, settled or not. SessionStart runs one after another,
|
|
26
|
+
* and other events wait for it, so hooks see each session in order and before its events.
|
|
27
|
+
*/
|
|
28
|
+
pendingSessionStart;
|
|
22
29
|
constructor(projectDir, sessionId, configDirName = DEFAULT_CONFIG_DIR, homeDir, worktree) {
|
|
23
30
|
this.worktree = worktree;
|
|
24
31
|
this.projectDir = projectDir;
|
|
@@ -30,8 +37,21 @@ var HookManager = class {
|
|
|
30
37
|
reload() {
|
|
31
38
|
this.config = loadHooksConfig(this.projectDir, this.configDirName, this.homeDir);
|
|
32
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Bind hooks to a thread. After SessionStart has fired, binding a different thread
|
|
42
|
+
* (the first message creating one, `/new`, a resumed thread) fires SessionStart again
|
|
43
|
+
* with `source: 'thread_change'`, so a hook that tracks sessions learns the new id
|
|
44
|
+
* before any event of that thread reaches it.
|
|
45
|
+
*/
|
|
33
46
|
setSessionId(sessionId) {
|
|
47
|
+
if (sessionId === this.sessionId) return;
|
|
34
48
|
this.sessionId = sessionId;
|
|
49
|
+
if (this.sessionStarted) this.runSessionStart("thread_change").catch(() => {});
|
|
50
|
+
}
|
|
51
|
+
/** Dispatch an event's hooks once any queued SessionStart has finished. */
|
|
52
|
+
async dispatch(...args) {
|
|
53
|
+
if (this.pendingSessionStart) await this.pendingSessionStart;
|
|
54
|
+
return runHooksForEvent(...args);
|
|
35
55
|
}
|
|
36
56
|
/** Set the active agent run id. Included as `run_id` in all hook stdin while a run is active. */
|
|
37
57
|
setRunId(runId) {
|
|
@@ -74,8 +94,9 @@ var HookManager = class {
|
|
|
74
94
|
* session events so a hook that provisions on start can tear down on end using
|
|
75
95
|
* the same fields.
|
|
76
96
|
*/
|
|
77
|
-
sessionStdin(hook_event_name) {
|
|
97
|
+
sessionStdin(hook_event_name, source) {
|
|
78
98
|
const stdin = this.baseStdinFields(hook_event_name);
|
|
99
|
+
if (source) stdin.source = source;
|
|
79
100
|
if (this.worktree) {
|
|
80
101
|
stdin.worktree_path = this.worktree.path;
|
|
81
102
|
if (this.worktree.branch) stdin.branch = this.worktree.branch;
|
|
@@ -91,7 +112,7 @@ var HookManager = class {
|
|
|
91
112
|
tool_name: toolName,
|
|
92
113
|
tool_input: toolInput
|
|
93
114
|
};
|
|
94
|
-
return
|
|
115
|
+
return this.dispatch(hooks, stdin, { tool_name: toolName });
|
|
95
116
|
}
|
|
96
117
|
async runPostToolUse(toolName, toolInput, toolOutput, toolError) {
|
|
97
118
|
const hooks = this.config.PostToolUse;
|
|
@@ -103,7 +124,7 @@ var HookManager = class {
|
|
|
103
124
|
tool_output: toolOutput,
|
|
104
125
|
tool_error: toolError
|
|
105
126
|
};
|
|
106
|
-
return
|
|
127
|
+
return this.dispatch(hooks, stdin, { tool_name: toolName });
|
|
107
128
|
}
|
|
108
129
|
async runUserPromptSubmit(userMessage) {
|
|
109
130
|
const hooks = this.config.UserPromptSubmit;
|
|
@@ -112,7 +133,7 @@ var HookManager = class {
|
|
|
112
133
|
...this.baseStdinFields("UserPromptSubmit"),
|
|
113
134
|
user_message: userMessage
|
|
114
135
|
};
|
|
115
|
-
return
|
|
136
|
+
return this.dispatch(hooks, stdin);
|
|
116
137
|
}
|
|
117
138
|
async runStop(assistantMessage, stopReason) {
|
|
118
139
|
const hooks = this.config.Stop;
|
|
@@ -122,19 +143,27 @@ var HookManager = class {
|
|
|
122
143
|
assistant_message: assistantMessage,
|
|
123
144
|
stop_reason: stopReason
|
|
124
145
|
};
|
|
125
|
-
return
|
|
146
|
+
return this.dispatch(hooks, stdin);
|
|
126
147
|
}
|
|
127
|
-
async runSessionStart() {
|
|
148
|
+
async runSessionStart(source = "startup") {
|
|
149
|
+
this.sessionStarted = true;
|
|
128
150
|
const hooks = this.config.SessionStart;
|
|
129
151
|
if (!hooks || hooks.length === 0) return emptyResult();
|
|
130
|
-
const stdin = this.sessionStdin("SessionStart");
|
|
131
|
-
|
|
152
|
+
const stdin = this.sessionStdin("SessionStart", source);
|
|
153
|
+
const previous = this.pendingSessionStart;
|
|
154
|
+
const run = previous ? previous.then(() => runHooksForEvent(hooks, stdin)) : runHooksForEvent(hooks, stdin);
|
|
155
|
+
const settled = run.then(() => {}, () => {});
|
|
156
|
+
this.pendingSessionStart = settled;
|
|
157
|
+
settled.then(() => {
|
|
158
|
+
if (this.pendingSessionStart === settled) this.pendingSessionStart = void 0;
|
|
159
|
+
});
|
|
160
|
+
return run;
|
|
132
161
|
}
|
|
133
162
|
async runSessionEnd() {
|
|
134
163
|
const hooks = this.config.SessionEnd;
|
|
135
164
|
if (!hooks || hooks.length === 0) return emptyResult();
|
|
136
165
|
const stdin = this.sessionStdin("SessionEnd");
|
|
137
|
-
return
|
|
166
|
+
return this.dispatch(hooks, stdin);
|
|
138
167
|
}
|
|
139
168
|
/**
|
|
140
169
|
* Fire notification hooks (non-blocking, fire-and-forget).
|
|
@@ -148,7 +177,7 @@ var HookManager = class {
|
|
|
148
177
|
reason,
|
|
149
178
|
message
|
|
150
179
|
};
|
|
151
|
-
|
|
180
|
+
this.dispatch(hooks, stdin).catch(() => {});
|
|
152
181
|
}
|
|
153
182
|
async runAgentStart() {
|
|
154
183
|
const hooks = this.config.AgentStart;
|
|
@@ -159,7 +188,7 @@ var HookManager = class {
|
|
|
159
188
|
...this.baseStdinFields("AgentStart"),
|
|
160
189
|
run_id: runId
|
|
161
190
|
};
|
|
162
|
-
return
|
|
191
|
+
return this.dispatch(hooks, stdin);
|
|
163
192
|
}
|
|
164
193
|
async runAgentEnd(stopReason) {
|
|
165
194
|
const hooks = this.config.AgentEnd;
|
|
@@ -171,7 +200,7 @@ var HookManager = class {
|
|
|
171
200
|
run_id: runId,
|
|
172
201
|
stop_reason: stopReason
|
|
173
202
|
};
|
|
174
|
-
return
|
|
203
|
+
return this.dispatch(hooks, stdin);
|
|
175
204
|
}
|
|
176
205
|
async runPermissionRequest(permissionKind, toolCallId, toolName, toolInput) {
|
|
177
206
|
const hooks = this.config.PermissionRequest;
|
|
@@ -186,7 +215,7 @@ var HookManager = class {
|
|
|
186
215
|
tool_name: toolName,
|
|
187
216
|
...toolInput !== void 0 ? { tool_input: toolInput } : {}
|
|
188
217
|
};
|
|
189
|
-
return
|
|
218
|
+
return this.dispatch(hooks, stdin);
|
|
190
219
|
}
|
|
191
220
|
async runPermissionResult(permissionKind, toolCallId, toolName, decision, toolInput) {
|
|
192
221
|
const hooks = this.config.PermissionResult;
|
|
@@ -202,7 +231,7 @@ var HookManager = class {
|
|
|
202
231
|
decision,
|
|
203
232
|
...toolInput !== void 0 ? { tool_input: toolInput } : {}
|
|
204
233
|
};
|
|
205
|
-
return
|
|
234
|
+
return this.dispatch(hooks, stdin);
|
|
206
235
|
}
|
|
207
236
|
async runInterrupt(reason) {
|
|
208
237
|
const hooks = this.config.Interrupt;
|
|
@@ -214,7 +243,7 @@ var HookManager = class {
|
|
|
214
243
|
run_id: runId,
|
|
215
244
|
reason
|
|
216
245
|
};
|
|
217
|
-
return
|
|
246
|
+
return this.dispatch(hooks, stdin);
|
|
218
247
|
}
|
|
219
248
|
async runSubagentStart(toolCallId, agentType, task, modelId, forked) {
|
|
220
249
|
const hooks = this.config.SubagentStart;
|
|
@@ -230,7 +259,7 @@ var HookManager = class {
|
|
|
230
259
|
...modelId !== void 0 ? { model_id: modelId } : {},
|
|
231
260
|
...forked !== void 0 ? { forked } : {}
|
|
232
261
|
};
|
|
233
|
-
return
|
|
262
|
+
return this.dispatch(hooks, stdin);
|
|
234
263
|
}
|
|
235
264
|
async runSubagentEnd(toolCallId, agentType, result, isError, durationMs) {
|
|
236
265
|
const hooks = this.config.SubagentEnd;
|
|
@@ -246,7 +275,7 @@ var HookManager = class {
|
|
|
246
275
|
is_error: isError,
|
|
247
276
|
duration_ms: durationMs
|
|
248
277
|
};
|
|
249
|
-
return
|
|
278
|
+
return this.dispatch(hooks, stdin);
|
|
250
279
|
}
|
|
251
280
|
};
|
|
252
281
|
export { HookManager };
|