chore: initialize recovered claude workspace

This commit is contained in:
2026-04-02 15:29:01 +08:00
commit a10efa3b4b
1940 changed files with 506426 additions and 0 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
import { c as _c } from "react/compiler-runtime";
import * as React from 'react';
import { useExitOnCtrlCDWithKeybindings } from '../../hooks/useExitOnCtrlCDWithKeybindings.js';
import { Box, Text } from '../../ink.js';
type Props = {
instructions?: string;
};
export function AgentNavigationFooter(t0) {
const $ = _c(2);
const {
instructions: t1
} = t0;
const instructions = t1 === undefined ? "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to go back" : t1;
const exitState = useExitOnCtrlCDWithKeybindings();
const t2 = exitState.pending ? `Press ${exitState.keyName} again to exit` : instructions;
let t3;
if ($[0] !== t2) {
t3 = <Box marginLeft={2}><Text dimColor={true}>{t2}</Text></Box>;
$[0] = t2;
$[1] = t3;
} else {
t3 = $[1];
}
return t3;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsInVzZUV4aXRPbkN0cmxDRFdpdGhLZXliaW5kaW5ncyIsIkJveCIsIlRleHQiLCJQcm9wcyIsImluc3RydWN0aW9ucyIsIkFnZW50TmF2aWdhdGlvbkZvb3RlciIsInQwIiwiJCIsIl9jIiwidDEiLCJ1bmRlZmluZWQiLCJleGl0U3RhdGUiLCJ0MiIsInBlbmRpbmciLCJrZXlOYW1lIiwidDMiXSwic291cmNlcyI6WyJBZ2VudE5hdmlnYXRpb25Gb290ZXIudHN4Il0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0J1xuaW1wb3J0IHsgdXNlRXhpdE9uQ3RybENEV2l0aEtleWJpbmRpbmdzIH0gZnJvbSAnLi4vLi4vaG9va3MvdXNlRXhpdE9uQ3RybENEV2l0aEtleWJpbmRpbmdzLmpzJ1xuaW1wb3J0I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TQUF3RSxHQUF4RSx5RUFBd0UsR0FBeEVELEVBQXdFO0VBRXhFLE1BQUFFLFNBQUEsR0FBa0JYLDhCQUE4QixDQUFDLENBQUM7RUFLM0MsTUFBQVksRUFBQSxHQUFBRCxTQUFTLENBQUFFLE9BRU0sR0FGZixTQUNZRixTQUFTLENBQUFHLE9BQVEsZ0JBQ2QsR0FGZlYsWUFFZTtFQUFBLElBQUFXLEVBQUE7RUFBQSxJQUFBUixDQUFBLFFBQUFLLEVBQUE7SUFKcEJHLEVBQUEsSUFBQyxHQUFHLENBQWEsVUFBQyxDQUFELEdBQUMsQ0FDaEIsQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFSLEtBQU8sQ0FBQyxDQUNYLENBQUFILEVBRWMsQ0FDakIsRUFKQyxJQUFJLENBS1AsRUFOQyxHQUFHLENBTUU7SUFBQUwsQ0FBQSxNQUFBSyxFQUFBO0lBQUFMLENBQUEsTUFBQVEsRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQVIsQ0FBQTtFQUFBO0VBQUEsT0FOTlEsRUFNTTtBQUFBIiwiaWdub3JlTGlzdCI6W119

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
import { useEffect } from 'react'
type Props = {
agentType: string
scope: unknown
snapshotTimestamp: string
onComplete: (choice: 'merge' | 'keep' | 'replace') => void
onCancel: () => void
}
export function SnapshotUpdateDialog({ onCancel }: Props) {
useEffect(() => {
onCancel()
}, [onCancel])
return null
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,272 @@
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()
}
}

View File

@@ -0,0 +1,197 @@
import type { ContentBlock } from '@anthropic-ai/sdk/resources/index.mjs'
import { getUserContext } from 'src/context.js'
import { queryModelWithoutStreaming } from 'src/services/api/claude.js'
import { getEmptyToolPermissionContext } from 'src/Tool.js'
import { AGENT_TOOL_NAME } from 'src/tools/AgentTool/constants.js'
import { prependUserContext } from 'src/utils/api.js'
import {
createUserMessage,
normalizeMessagesForAPI,
} from 'src/utils/messages.js'
import type { ModelName } from 'src/utils/model/model.js'
import { isAutoMemoryEnabled } from '../../memdir/paths.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../../services/analytics/index.js'
import { jsonParse } from '../../utils/slowOperations.js'
import { asSystemPrompt } from '../../utils/systemPromptType.js'
type GeneratedAgent = {
identifier: string
whenToUse: string
systemPrompt: string
}
const AGENT_CREATION_SYSTEM_PROMPT = `You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.
**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.
When a user describes what they want an agent to do, you will:
1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.
2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.
3. **Architect Comprehensive Instructions**: Develop a system prompt that:
- Establishes clear behavioral boundaries and operational parameters
- Provides specific methodologies and best practices for task execution
- Anticipates edge cases and provides guidance for handling them
- Incorporates any specific requirements or preferences mentioned by the user
- Defines output format expectations when relevant
- Aligns with project-specific coding standards and patterns from CLAUDE.md
4. **Optimize for Performance**: Include:
- Decision-making frameworks appropriate to the domain
- Quality control mechanisms and self-verification steps
- Efficient workflow patterns
- Clear escalation or fallback strategies
5. **Create Identifier**: Design a concise, descriptive identifier that:
- Uses lowercase letters, numbers, and hyphens only
- Is typically 2-4 words joined by hyphens
- Clearly indicates the agent's primary function
- Is memorable and easy to type
- Avoids generic terms like "helper" or "assistant"
6 **Example agent descriptions**:
- in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
- examples should be of the form:
- <example>
Context: The user is creating a test-runner agent that should be called after a logical chunk of code is written.
user: "Please write a function that checks if a number is prime"
assistant: "Here is the relevant function: "
<function call omitted for brevity only for this example>
<commentary>
Since a significant piece of code was written, use the ${AGENT_TOOL_NAME} tool to launch the test-runner agent to run the tests.
</commentary>
assistant: "Now let me use the test-runner agent to run the tests"
</example>
- <example>
Context: User is creating an agent to respond to the word "hello" with a friendly jok.
user: "Hello"
assistant: "I'm going to use the ${AGENT_TOOL_NAME} tool to launch the greeting-responder agent to respond with a friendly joke"
<commentary>
Since the user is greeting, use the greeting-responder agent to respond with a friendly joke.
</commentary>
</example>
- If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.
Your output must be a valid JSON object with exactly these fields:
{
"identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'test-runner', 'api-docs-writer', 'code-formatter')",
"whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
"systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
}
Key principles for your system prompts:
- Be specific rather than generic - avoid vague instructions
- Include concrete examples when they would clarify behavior
- Balance comprehensiveness with clarity - every instruction should add value
- Ensure the agent has enough context to handle variations of the core task
- Make the agent proactive in seeking clarification when needed
- Build in quality assurance and self-correction mechanisms
Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
`
// Agent memory instructions to include in the system prompt when memory is mentioned or relevant
const AGENT_MEMORY_INSTRUCTIONS = `
7. **Agent Memory Instructions**: If the user mentions "memory", "remember", "learn", "persist", or similar concepts, OR if the agent would benefit from building up knowledge across conversations (e.g., code reviewers learning patterns, architects learning codebase structure, etc.), include domain-specific memory update instructions in the systemPrompt.
Add a section like this to the systemPrompt, tailored to the agent's specific domain:
"**Update your agent memory** as you discover [domain-specific items]. This builds up institutional knowledge across conversations. Write concise notes about what you found and where.
Examples of what to record:
- [domain-specific item 1]
- [domain-specific item 2]
- [domain-specific item 3]"
Examples of domain-specific memory instructions:
- For a code-reviewer: "Update your agent memory as you discover code patterns, style conventions, common issues, and architectural decisions in this codebase."
- For a test-runner: "Update your agent memory as you discover test patterns, common failure modes, flaky tests, and testing best practices."
- For an architect: "Update your agent memory as you discover codepaths, library locations, key architectural decisions, and component relationships."
- For a documentation writer: "Update your agent memory as you discover documentation patterns, API structures, and terminology conventions."
The memory instructions should be specific to what the agent would naturally learn while performing its core tasks.
`
export async function generateAgent(
userPrompt: string,
model: ModelName,
existingIdentifiers: string[],
abortSignal: AbortSignal,
): Promise<GeneratedAgent> {
const existingList =
existingIdentifiers.length > 0
? `\n\nIMPORTANT: The following identifiers already exist and must NOT be used: ${existingIdentifiers.join(', ')}`
: ''
const prompt = `Create an agent configuration based on this request: "${userPrompt}".${existingList}
Return ONLY the JSON object, no other text.`
const userMessage = createUserMessage({ content: prompt })
// Fetch user and system contexts
const userContext = await getUserContext()
// Prepend user context to messages and append system context to system prompt
const messagesWithContext = prependUserContext([userMessage], userContext)
// Include memory instructions when the feature is enabled
const systemPrompt = isAutoMemoryEnabled()
? AGENT_CREATION_SYSTEM_PROMPT + AGENT_MEMORY_INSTRUCTIONS
: AGENT_CREATION_SYSTEM_PROMPT
const response = await queryModelWithoutStreaming({
messages: normalizeMessagesForAPI(messagesWithContext),
systemPrompt: asSystemPrompt([systemPrompt]),
thinkingConfig: { type: 'disabled' as const },
tools: [],
signal: abortSignal,
options: {
getToolPermissionContext: async () => getEmptyToolPermissionContext(),
model,
toolChoice: undefined,
agents: [],
isNonInteractiveSession: false,
hasAppendSystemPrompt: false,
querySource: 'agent_creation',
mcpTools: [],
},
})
const textBlocks = response.message.content.filter(
(block): block is ContentBlock & { type: 'text' } => block.type === 'text',
)
const responseText = textBlocks.map(block => block.text).join('\n')
let parsed: GeneratedAgent
try {
parsed = jsonParse(responseText.trim())
} catch {
const jsonMatch = responseText.match(/\{[\s\S]*\}/)
if (!jsonMatch) {
throw new Error('No JSON object found in response')
}
parsed = jsonParse(jsonMatch[0])
}
if (!parsed.identifier || !parsed.whenToUse || !parsed.systemPrompt) {
throw new Error('Invalid agent configuration generated')
}
logEvent('tengu_agent_definition_generated', {
agent_identifier:
parsed.identifier as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
identifier: parsed.identifier,
whenToUse: parsed.whenToUse,
systemPrompt: parsed.systemPrompt,
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
import { c as _c } from "react/compiler-runtime";
import React, { type ReactNode } from 'react';
import { ConfigurableShortcutHint } from '../../../ConfigurableShortcutHint.js';
import { Byline } from '../../../design-system/Byline.js';
import { KeyboardShortcutHint } from '../../../design-system/KeyboardShortcutHint.js';
import { useWizard } from '../../../wizard/index.js';
import { WizardDialogLayout } from '../../../wizard/WizardDialogLayout.js';
import { ModelSelector } from '../../ModelSelector.js';
import type { AgentWizardData } from '../types.js';
export function ModelStep() {
const $ = _c(8);
const {
goNext,
goBack,
updateWizardData,
wizardData
} = useWizard();
let t0;
if ($[0] !== goNext || $[1] !== updateWizardData) {
t0 = model => {
updateWizardData({
selectedModel: model
});
goNext();
};
$[0] = goNext;
$[1] = updateWizardData;
$[2] = t0;
} else {
t0 = $[2];
}
const handleComplete = t0;
let t1;
if ($[3] === Symbol.for("react.memo_cache_sentinel")) {
t1 = <Byline><KeyboardShortcutHint shortcut={"\u2191\u2193"} action="navigate" /><KeyboardShortcutHint shortcut="Enter" action="select" /><ConfigurableShortcutHint action="confirm:no" context="Confirmation" fallback="Esc" description="go back" /></Byline>;
$[3] = t1;
} else {
t1 = $[3];
}
let t2;
if ($[4] !== goBack || $[5] !== handleComplete || $[6] !== wizardData.selectedModel) {
t2 = <WizardDialogLayout subtitle="Select model" footerText={t1}><ModelSelector initialModel={wizardData.selectedModel} onComplete={handleComplete} onCancel={goBack} /></WizardDialogLayout>;
$[4] = goBack;
$[5] = handleComplete;
$[6] = wizardData.selectedModel;
$[7] = t2;
} else {
t2 = $[7];
}
return t2;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlJlYWN0Tm9kZSIsIkNvbmZpZ3VyYWJsZVNob3J0Y3V0SGludCIsIkJ5bGluZSIsIktleWJvYXJkU2hvcnRjdXRIaW50IiwidXNlV2l6YXJkIiwiV2l6YXJkRGlhbG9nTGF5b3V0IiwiTW9kZWxTZWxlY3RvciIsIkFnZW50V2l6YXJkRGF0YSIsIk1vZGVsU3RlcCIsIiQiLCJfYyIsImdvTmV4dCIsImdvQmFjayIsInVwZGF0ZVdpemFyZERhdGEiLCJ3aXphcmREYXRhIiwidDAiLCJtb2RlbCIsInNlbGVjdGVkTW9kZWwiLCJoYW5kbGVDb21wbGV0ZSIsInQxIiwiU3ltYm9sIiwiZm9yIiwidDIiXSwic291cmNlcyI6WyJNb2RlbFN0ZXAudHN4Il0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBSZWFjdCwgeyB0eXBlIFJlYWN0Tm9kZSB9IGZyb20gJ3JlYWN0J1xuaW1wb3J0IHsgQ29uZmlndXJhYmxlU2hvcnRjdXRIaW50IH0gZnJvbSAnLi4vLi4vLi4vQ29uZmlndXJhYmxlU2hvcnRjdXRIaW50LmpzJ1xuaW1wb3J0IHsgQnlsaW5lIH0gZnJvbSAnLi4vLi4vLi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QVQsQ0FBQSxRQUFBSyxVQUFBLENBQUFHLGFBQUE7SUFaYkssRUFBQSxJQUFDLGtCQUFrQixDQUNSLFFBQWMsQ0FBZCxjQUFjLENBRXJCLFVBU1MsQ0FUVCxDQUFBSCxFQVNRLENBQUMsQ0FHWCxDQUFDLGFBQWEsQ0FDRSxZQUF3QixDQUF4QixDQUFBTCxVQUFVLENBQUFHLGFBQWEsQ0FBQyxDQUMxQkMsVUFBYyxDQUFkQSxlQUFhLENBQUMsQ0FDaEJOLFFBQU0sQ0FBTkEsT0FBSyxDQUFDLEdBRXBCLEVBcEJDLGtCQUFrQixDQW9CRTtJQUFBSCxDQUFBLE1BQUFHLE1BQUE7SUFBQUgsQ0FBQSxNQUFBUyxjQUFBO0lBQUFULENBQUEsTUFBQUssVUFBQSxDQUFBRyxhQUFBO0lBQUFSLENBQUEsTUFBQWEsRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQWIsQ0FBQTtFQUFBO0VBQUEsT0FwQnJCYSxFQW9CcUI7QUFBQSIsImlnbm9yZUxpc3QiOltdfQ==

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import type { SettingSource } from 'src/utils/settings/constants.js'
import type { AgentDefinition } from '../../tools/AgentTool/loadAgentsDir.js'
export const AGENT_PATHS = {
FOLDER_NAME: '.claude',
AGENTS_DIR: 'agents',
} as const
// Base types for common patterns
type WithPreviousMode = { previousMode: ModeState }
type WithAgent = { agent: AgentDefinition }
// Simplified state type using intersection types
export type ModeState =
| { mode: 'main-menu' }
| { mode: 'list-agents'; source: SettingSource | 'all' | 'built-in' }
| ({ mode: 'agent-menu' } & WithAgent & WithPreviousMode)
| ({ mode: 'view-agent' } & WithAgent & WithPreviousMode)
| { mode: 'create-agent' }
| ({ mode: 'edit-agent' } & WithAgent & WithPreviousMode)
| ({ mode: 'delete-confirm' } & WithAgent & WithPreviousMode)
export type AgentValidationResult = {
isValid: boolean
warnings: string[]
errors: string[]
}

View File

@@ -0,0 +1,18 @@
import capitalize from 'lodash-es/capitalize.js'
import type { SettingSource } from 'src/utils/settings/constants.js'
import { getSettingSourceName } from 'src/utils/settings/constants.js'
export function getAgentSourceDisplayName(
source: SettingSource | 'all' | 'built-in' | 'plugin',
): string {
if (source === 'all') {
return 'Agents'
}
if (source === 'built-in') {
return 'Built-in agents'
}
if (source === 'plugin') {
return 'Plugin agents'
}
return capitalize(getSettingSourceName(source))
}

View File

@@ -0,0 +1,109 @@
import type { Tools } from '../../Tool.js'
import { resolveAgentTools } from '../../tools/AgentTool/agentToolUtils.js'
import type {
AgentDefinition,
CustomAgentDefinition,
} from '../../tools/AgentTool/loadAgentsDir.js'
import { getAgentSourceDisplayName } from './utils.js'
export type AgentValidationResult = {
isValid: boolean
errors: string[]
warnings: string[]
}
export function validateAgentType(agentType: string): string | null {
if (!agentType) {
return 'Agent type is required'
}
if (!/^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/.test(agentType)) {
return 'Agent type must start and end with alphanumeric characters and contain only letters, numbers, and hyphens'
}
if (agentType.length < 3) {
return 'Agent type must be at least 3 characters long'
}
if (agentType.length > 50) {
return 'Agent type must be less than 50 characters'
}
return null
}
export function validateAgent(
agent: Omit<CustomAgentDefinition, 'location'>,
availableTools: Tools,
existingAgents: AgentDefinition[],
): AgentValidationResult {
const errors: string[] = []
const warnings: string[] = []
// Validate agent type
if (!agent.agentType) {
errors.push('Agent type is required')
} else {
const typeError = validateAgentType(agent.agentType)
if (typeError) {
errors.push(typeError)
}
// Check for duplicates (excluding self for editing)
const duplicate = existingAgents.find(
a => a.agentType === agent.agentType && a.source !== agent.source,
)
if (duplicate) {
errors.push(
`Agent type "${agent.agentType}" already exists in ${getAgentSourceDisplayName(duplicate.source)}`,
)
}
}
// Validate description
if (!agent.whenToUse) {
errors.push('Description (description) is required')
} else if (agent.whenToUse.length < 10) {
warnings.push(
'Description should be more descriptive (at least 10 characters)',
)
} else if (agent.whenToUse.length > 5000) {
warnings.push('Description is very long (over 5000 characters)')
}
// Validate tools
if (agent.tools !== undefined && !Array.isArray(agent.tools)) {
errors.push('Tools must be an array')
} else {
if (agent.tools === undefined) {
warnings.push('Agent has access to all tools')
} else if (agent.tools.length === 0) {
warnings.push(
'No tools selected - agent will have very limited capabilities',
)
}
// Check for invalid tools
const resolvedTools = resolveAgentTools(agent, availableTools, false)
if (resolvedTools.invalidTools.length > 0) {
errors.push(`Invalid tools: ${resolvedTools.invalidTools.join(', ')}`)
}
}
// Validate system prompt
const systemPrompt = agent.getSystemPrompt()
if (!systemPrompt) {
errors.push('System prompt is required')
} else if (systemPrompt.length < 20) {
errors.push('System prompt is too short (minimum 20 characters)')
} else if (systemPrompt.length > 10000) {
warnings.push('System prompt is very long (over 10,000 characters)')
}
return {
isValid: errors.length === 0,
errors,
warnings,
}
}