File size: 7,487 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | import { mkdir, open, unlink } from 'fs/promises'
import { join } from 'path'
import type { SettingSource } from 'src/utils/settings/constants.js'
import { getManagedFilePath } from 'src/utils/settings/managedPath.js'
import type { AgentMemoryScope } from '../../tools/AgentTool/agentMemory.js'
import {
type AgentDefinition,
isBuiltInAgent,
isPluginAgent,
} from '../../tools/AgentTool/loadAgentsDir.js'
import { getCwd } from '../../utils/cwd.js'
import type { EffortValue } from '../../utils/effort.js'
import { getClaudeConfigHomeDir } from '../../utils/envUtils.js'
import { getErrnoCode } from '../../utils/errors.js'
import { AGENT_PATHS } from './types.js'
/**
* Formats agent data as markdown file content
*/
export function formatAgentAsMarkdown(
agentType: string,
whenToUse: string,
tools: string[] | undefined,
systemPrompt: string,
color?: string,
model?: string,
memory?: AgentMemoryScope,
effort?: EffortValue,
): string {
// For YAML double-quoted strings, we need to escape:
// - Backslashes: \ -> \\
// - Double quotes: " -> \"
// - Newlines: \n -> \\n (so yaml reads it as literal backslash-n, not newline)
const escapedWhenToUse = whenToUse
.replace(/\\/g, '\\\\') // Escape backslashes first
.replace(/"/g, '\\"') // Escape double quotes
.replace(/\n/g, '\\\\n') // Escape newlines as \\n so yaml preserves them as \n
// Omit tools field entirely when tools is undefined or ['*'] (all tools allowed)
const isAllTools =
tools === undefined || (tools.length === 1 && tools[0] === '*')
const toolsLine = isAllTools ? '' : `\ntools: ${tools.join(', ')}`
const modelLine = model ? `\nmodel: ${model}` : ''
const effortLine = effort !== undefined ? `\neffort: ${effort}` : ''
const colorLine = color ? `\ncolor: ${color}` : ''
const memoryLine = memory ? `\nmemory: ${memory}` : ''
return `---
name: ${agentType}
description: "${escapedWhenToUse}"${toolsLine}${modelLine}${effortLine}${colorLine}${memoryLine}
---
${systemPrompt}
`
}
/**
* Gets the directory path for an agent location
*/
function getAgentDirectoryPath(location: SettingSource): string {
switch (location) {
case 'flagSettings':
throw new Error(`Cannot get directory path for ${location} agents`)
case 'userSettings':
return join(getClaudeConfigHomeDir(), AGENT_PATHS.AGENTS_DIR)
case 'projectSettings':
return join(getCwd(), AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR)
case 'policySettings':
return join(
getManagedFilePath(),
AGENT_PATHS.FOLDER_NAME,
AGENT_PATHS.AGENTS_DIR,
)
case 'localSettings':
return join(getCwd(), AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR)
}
}
function getRelativeAgentDirectoryPath(location: SettingSource): string {
switch (location) {
case 'projectSettings':
return join('.', AGENT_PATHS.FOLDER_NAME, AGENT_PATHS.AGENTS_DIR)
default:
return getAgentDirectoryPath(location)
}
}
/**
* Gets the file path for a new agent based on its name
* Used when creating new agent files
*/
export function getNewAgentFilePath(agent: {
source: SettingSource
agentType: string
}): string {
const dirPath = getAgentDirectoryPath(agent.source)
return join(dirPath, `${agent.agentType}.md`)
}
/**
* Gets the actual file path for an agent (handles filename vs agentType mismatch)
* Always use this for existing agents to get their real file location
*/
export function getActualAgentFilePath(agent: AgentDefinition): string {
if (agent.source === 'built-in') {
return 'Built-in'
}
if (agent.source === 'plugin') {
throw new Error('Cannot get file path for plugin agents')
}
const dirPath = getAgentDirectoryPath(agent.source)
const filename = agent.filename || agent.agentType
return join(dirPath, `${filename}.md`)
}
/**
* Gets the relative file path for a new agent based on its name
* Used for displaying where new agent files will be created
*/
export function getNewRelativeAgentFilePath(agent: {
source: SettingSource | 'built-in'
agentType: string
}): string {
if (agent.source === 'built-in') {
return 'Built-in'
}
const dirPath = getRelativeAgentDirectoryPath(agent.source)
return join(dirPath, `${agent.agentType}.md`)
}
/**
* Gets the actual relative file path for an agent (handles filename vs agentType mismatch)
*/
export function getActualRelativeAgentFilePath(agent: AgentDefinition): string {
if (isBuiltInAgent(agent)) {
return 'Built-in'
}
if (isPluginAgent(agent)) {
return `Plugin: ${agent.plugin || 'Unknown'}`
}
if (agent.source === 'flagSettings') {
return 'CLI argument'
}
const dirPath = getRelativeAgentDirectoryPath(agent.source)
const filename = agent.filename || agent.agentType
return join(dirPath, `${filename}.md`)
}
/**
* Ensures the directory for an agent location exists
*/
async function ensureAgentDirectoryExists(
source: SettingSource,
): Promise<string> {
const dirPath = getAgentDirectoryPath(source)
await mkdir(dirPath, { recursive: true })
return dirPath
}
/**
* Saves an agent to the filesystem
* @param checkExists - If true, throws error if file already exists
*/
export async function saveAgentToFile(
source: SettingSource | 'built-in',
agentType: string,
whenToUse: string,
tools: string[] | undefined,
systemPrompt: string,
checkExists = true,
color?: string,
model?: string,
memory?: AgentMemoryScope,
effort?: EffortValue,
): Promise<void> {
if (source === 'built-in') {
throw new Error('Cannot save built-in agents')
}
await ensureAgentDirectoryExists(source)
const filePath = getNewAgentFilePath({ source, agentType })
const content = formatAgentAsMarkdown(
agentType,
whenToUse,
tools,
systemPrompt,
color,
model,
memory,
effort,
)
try {
await writeFileAndFlush(filePath, content, checkExists ? 'wx' : 'w')
} catch (e: unknown) {
if (getErrnoCode(e) === 'EEXIST') {
throw new Error(`Agent file already exists: ${filePath}`)
}
throw e
}
}
/**
* Updates an existing agent file
*/
export async function updateAgentFile(
agent: AgentDefinition,
newWhenToUse: string,
newTools: string[] | undefined,
newSystemPrompt: string,
newColor?: string,
newModel?: string,
newMemory?: AgentMemoryScope,
newEffort?: EffortValue,
): Promise<void> {
if (agent.source === 'built-in') {
throw new Error('Cannot update built-in agents')
}
const filePath = getActualAgentFilePath(agent)
const content = formatAgentAsMarkdown(
agent.agentType,
newWhenToUse,
newTools,
newSystemPrompt,
newColor,
newModel,
newMemory,
newEffort,
)
await writeFileAndFlush(filePath, content)
}
/**
* Deletes an agent file
*/
export async function deleteAgentFromFile(
agent: AgentDefinition,
): Promise<void> {
if (agent.source === 'built-in') {
throw new Error('Cannot delete built-in agents')
}
const filePath = getActualAgentFilePath(agent)
try {
await unlink(filePath)
} catch (e: unknown) {
const code = getErrnoCode(e)
if (code !== 'ENOENT') {
throw e
}
}
}
async function writeFileAndFlush(
filePath: string,
content: string,
flag: 'w' | 'wx' = 'w',
): Promise<void> {
const handle = await open(filePath, flag)
try {
await handle.writeFile(content, { encoding: 'utf-8' })
await handle.datasync()
} finally {
await handle.close()
}
}
|