使用Semantic Kernel实现Claude Code的Agents TODO能力

使用Semantic Kernel实现Claude Code的Agents TODO能力

引言

在现代软件开发中,AI辅助编程工具正在成为开发者不可或缺的伙伴。Claude Code作为Anthropic推出的先进编程助手,其强大的TODO任务管理和智能代理(Agents)功能为开发者提供了卓越的项目管理和代码开发体验。本文将深入探讨如何使用Microsoft Semantic Kernel框架来实现类似Claude Code的TODO任务管理能力,让开发者能够在.NET生态系统中构建属于自己的智能编程助手。

Claude Code的TODO功能深度解析

1. 核心架构与设计理念

Claude Code采用了基于任务代理(Task Agents)的架构设计,其TODO功能不仅仅是简单的任务列表管理,更是一个智能的任务编排和执行系统:

任务代理工具(Task Agent Tools)

  • 并行处理能力:Claude Code通过Task工具能够将任务委派给子代理进行高效的并行处理
  • 智能任务分解:支持将复杂任务自动分解为多个可执行的子任务
  • 状态管理:提供pending、in_progress、completed三种状态的精确跟踪

7并行任务方法

Claude Code实现了一套标准化的并行任务处理流程:

  1. 组件创建 - 处理UI组件和业务逻辑组件的创建
  2. 样式处理 - 管理CSS/样式相关的任务
  3. 测试编写 - 自动生成和执行测试用例
  4. 类型定义 - 处理TypeScript类型定义和接口
  5. 工具函数 - 创建辅助函数和钩子
  6. 系统集成 - 处理路由、导入导出等系统级集成
  7. 配置管理 - 处理package.json、文档等配置文件

2. 智能任务编排特性

自动任务识别

  • 复杂多步骤任务(3个或更多步骤)自动创建TODO
  • 非平凡任务需要仔细规划时主动建议TODO管理
  • 用户提供多个任务时智能拆分和组织

任务状态流转

  • 实时状态更新和进度跟踪
  • 智能错误处理和任务阻塞检测
  • 任务完成后自动标记和后续任务发现

上下文感知

  • 基于项目结构和技术栈的智能任务建议
  • 与开发工作流的深度集成(git、构建、测试)
  • 支持团队协作的任务共享机制

MarkAgents项目:Semantic Kernel实现方案

1. 项目架构分析

MarkAgents项目采用了现代化的.NET 9.0架构,通过Semantic Kernel框架实现了对Claude Code TODO功能的本土化实现:

技术栈选型

xml 复制代码
<TargetFramework>net9.0</TargetFramework>
<PackageReference Include="Microsoft.SemanticKernel.Abstractions" Version="1.60.0" />
<PackageReference Include="Microsoft.SemanticKernel.Connectors.OpenAI" Version="1.60.0" />
<PackageReference Include="Microsoft.SemanticKernel.Core" Version="1.60.0" />

核心组件设计

  • AgentFunction.cs:13-569: 主要的智能代理函数实现
  • TodoInput.cs:1-39: TODO数据模型和状态管理
  • Program.cs:1-60: 应用程序入口和配置

2. TODO功能核心实现

数据模型设计(TodoInput.cs:1-39)

项目定义了完整的TODO数据结构:

csharp 复制代码
public sealed class TodoInputItem
{
    [JsonPropertyName("content")] public required string Content { get; set; }
    [JsonPropertyName("status")] public required TodoInputItemStatus Status { get; set; }
    [JsonPropertyName("priority")] public required Priority Priority { get; set; }
    [JsonPropertyName("id")] public required string Id { get; set; }
}

public enum TodoInputItemStatus
{
    Pending, InProgress, Completed
}

public enum Priority  
{
    Low, Medium, High
}

这种设计完全对标了Claude Code的TODO状态模型,支持优先级管理和状态流转。

智能TODO管理实现(AgentFunction.cs:239-569)

核心功能特性:

  1. 智能任务检测:通过详细的描述文档(AgentFunction.cs:242-417),系统能够自动识别何时需要创建TODO列表
  2. 可视化反馈:控制台彩色显示不同优先级的任务(AgentFunction.cs:432-451)
  3. 状态同步:实时更新任务状态并提供系统级反馈(AgentFunction.cs:519-546)

关键实现亮点:

csharp 复制代码
[KernelFunction,
     Description(
         """
         Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
         It also helps the user understand the progress of the task and overall progress of their requests.

         ## When to Use This Tool
         Use this tool proactively in these scenarios:

         1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
         2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
         3. User explicitly requests todo list - When the user directly asks you to use the todo list
         4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
         5. After receiving new instructions - Immediately capture user requirements as todos
         6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
         7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation

         ## When NOT to Use This Tool

         Skip using this tool when:
         1. There is only a single, straightforward task
         2. The task is trivial and tracking it provides no organizational benefit
         3. The task can be completed in less than 3 trivial steps
         4. The task is purely conversational or informational

         NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.

         ## Examples of When to Use the Todo List

         <example>
         User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
         Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
         *Creates todo list with the following items:*
         1. Create dark mode toggle component in Settings page
         2. Add dark mode state management (context/store)
         3. Implement CSS-in-JS styles for dark theme
         4. Update existing components to support theme switching
         5. Run tests and build process, addressing any failures or errors that occur
         *Begins working on the first task*

         <reasoning>
         The assistant used the todo list because:
         1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
         2. The user explicitly requested tests and build be run afterward
         3. The assistant inferred that tests and build need to pass by adding \\\"Ensure tests and build succeed\\\" as the final task
         </reasoning>
         </example>

         <example>
         User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
         Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
         *Uses grep or search tools to locate all instances of getCwd in the codebase*
         Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
         *Creates todo list with specific items for each file that needs updating*

         <reasoning>
         The assistant used the todo list because:
         1. First, the assistant searched to understand the scope of the task
         2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
         3. The todo list helps ensure every instance is tracked and updated systematically
         4. This approach prevents missing any occurrences and maintains code consistency
         </reasoning>
         </example>


         <example>
         User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
         Assistant: I'll help implement these features. First, let's add all the features to the todo list.
         *Creates a todo list breaking down each feature into specific tasks based on the project architecture*
         Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.

         <reasoning>
         The assistant used the todo list because:
         1. The user provided multiple complex features to implement in a comma separated list
         2. The todo list helps organize these large features into manageable tasks
         3. This approach allows for tracking progress across the entire implementation
         </reasoning>
         </example>

         <example>
         User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
         Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
         *Reviews component structure, render patterns, state management, and data fetching*
         Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
         *Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
         Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>

         <reasoning>
         The assistant used the todo list because:
         1. First, the assistant examined the codebase to identify specific performance issues
         2. Based on this analysis, it identified multiple optimization opportunities
         3. Performance optimization is a non-trivial task requiring multiple steps
         4. The todo list helps methodically track improvements across different components
         5. This systematic approach ensures all performance bottlenecks are addressed
         </reasoning>
         </example>

         ## Examples of When NOT to Use the Todo List

         <example>
         User: How do I print 'Hello World' in Python?
         Assistant: In Python, you can print \\\"Hello World\\\" with this simple code:

         python
         print(\\\"Hello World\\\")

         This will output the text \\\"Hello World\\\" to the console when executed.</assistant>

         <reasoning>
         The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
         </reasoning>
         </example>

         <example>
         User: What does the git status command do?
         Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.

         <reasoning>
         The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
         </reasoning>
         </example>

         <example>
         User: Can you add a comment to the calculateTotal function to explain what it does?
         Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
         * Uses the Edit tool to add a comment to the calculateTotal function *

         <reasoning>
         The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
         </reasoning>
         </example>

         <example>
         User: Run npm install for me and tell me what happens.
         Assistant: I'll run the npm install command for you.

         *Executes: npm install*

         The command completed successfully. Here's the output:
         [Output of npm install command]

         All dependencies have been installed according to your package.json file.

         <reasoning>
         The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
         </reasoning>
         </example>

         ## Task States and Management

         1. **Task States**: Use these states to track progress:
            - pending: Task not yet started
            - in_progress: Currently working on (limit to ONE task at a time)
            - completed: Task finished successfully

         2. **Task Management**:
            - Update task status in real-time as you work
            - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
            - Only have ONE task in_progress at any time
            - Complete current tasks before starting new ones
            - Remove tasks that are no longer relevant from the list entirely

         3. **Task Completion Requirements**:
            - ONLY mark a task as completed when you have FULLY accomplished it
            - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
            - When blocked, create a new task describing what needs to be resolved
            - Never mark a task as completed if:
              - Tests are failing
              - Implementation is partial
              - You encountered unresolved errors
              - You couldn't find necessary files or dependencies

         4. **Task Breakdown**:
            - Create specific, actionable items
            - Break complex tasks into smaller, manageable steps
            - Use clear, descriptive task names

         When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
         """)]
    public string TodoWrite(
        [Description("The updated todo list")] TodoInputItem[] todos)
    {
        if (_input == null)
        {
            // 初始化TODO列表
            _input = new List<TodoInputItem>(todos);
            // 设置控制台编码支持UTF-8
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine();
            Console.WriteLine("□ Initializing TODO list...");
            // 通过控制台打印一下TODO
            foreach (var item in todos)
            {
                // 根据item等级渲染不同颜色
                if (item.Priority == Priority.High)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                else if (item.Priority == Priority.Medium)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }

                Console.Write("□ ");
                Console.Write(item.Content);
                Console.WriteLine();

                Console.ResetColor();
            }

            return GenerateInitialTodoMessage(todos);
        }
        else
        {
            // 添加新的TODO项
            var newItems = todos.Where(x => _input.All(existing => existing.Id != x.Id)).ToList();
            _input.AddRange(newItems);

            // 更新现有TODO项的状态
            foreach (var item in _input)
            {
                var updatedItem = todos.FirstOrDefault(x => x.Id == item.Id);
                if (updatedItem == null) continue;
                item.Status = updatedItem.Status;
                item.Content = updatedItem.Content;
                item.Priority = updatedItem.Priority;
            }

            Console.WriteLine("□ Updating TODO list...");
            foreach (var item in _input)
            {
                // 根据item等级渲染不同颜色
                if (item.Priority == Priority.High)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                else if (item.Priority == Priority.Medium)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }

                if (item.Status == TodoInputItemStatus.Pending)
                {
                    Console.Write("□ ");
                }
                else if (item.Status == TodoInputItemStatus.InProgress)
                {
                    Console.Write("■ ");
                }
                else if (item.Status == TodoInputItemStatus.Completed)
                {
                    Console.Write("✓ ");
                }

                Console.Write(item.Content);
                Console.WriteLine();
                Console.ResetColor();
            }

            return GenerateUpdateTodoMessage(_input.ToArray());
        }
    }

    private string GenerateInitialTodoMessage(TodoInputItem[] input)
    {
        var sb = new StringBuilder();
        sb.AppendLine(
            "Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable");
        sb.AppendLine();

        // 返回当前TODO列表的JSON字符串
        var currentTodoJson = SerializeTodoList(input);
        sb.AppendLine("<system-reminder>");
        sb.AppendLine(
            "Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:");
        sb.AppendLine();
        sb.AppendLine(currentTodoJson);
        sb.AppendLine(". Continue on with the tasks at hand if applicable.");
        sb.AppendLine("</system-reminder>");

        return sb.ToString();
    }

    private string GenerateUpdateTodoMessage(TodoInputItem[] todoList)
    {
        var sb = new StringBuilder();
        sb.AppendLine(
            "Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable");
        sb.AppendLine();

        // 返回当前TODO列表的JSON字符串
        var currentTodoJson = SerializeTodoList(todoList);
        sb.AppendLine("<system-reminder>");
        sb.AppendLine(
            "Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:");
        sb.AppendLine();
        sb.AppendLine(currentTodoJson);
        sb.AppendLine(". Continue on with the tasks at hand if applicable.");
        sb.AppendLine("</system-reminder>");

        return sb.ToString();
    }

    private string SerializeTodoList(TodoInputItem[] todoList)
    {
        var todoItems = todoList.Select(item => new
        {
            content = item.Content,
            status = item.Status.ToString().ToLowerInvariant(),
            priority = item.Priority.ToString().ToLowerInvariant(),
            id = item.Id
        }).ToList();

        var options = new JsonSerializerOptions
        {
            WriteIndented = false,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };

        return JsonSerializer.Serialize(todoItems, options);
    }

技术实现深度剖析

1. Semantic Kernel架构优势

插件系统设计

csharp 复制代码
var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.Plugins.AddFromType<AgentFunction>();
kernelBuilder.AddOpenAIChatCompletion("kimi-k2-0711-preview", 
    new Uri("https://api.token-ai.cn/v1"), "sk-xxx");

Semantic Kernel的插件架构允许开发者:

  • 模块化功能开发
  • 热插拔功能组件
  • 统一的函数调用接口
  • 多模型支持(OpenAI、Azure OpenAI、本地模型)

系统提示词工程(Program.cs:22-39)

csharp 复制代码
history.AddSystemMessage("You are an AI assistant specialized in C# and .NET development. You assist with Semantic Kernel applications, code analysis, debugging, and feature development.");
history.AddSystemMessage(@"You excel at: **Code Analysis** - Understanding C#/.NET project structure, dependencies, NuGet packages; **Bug Fixing** - Identifying and resolving C# compilation errors, runtime issues; **Feature Development** - Implementing functionality using Microsoft.SemanticKernel framework; **Code Review** - Analyzing C# code quality, best practices, security.

EXECUTION WORKFLOW - STRICTLY FOLLOW THIS ORDER:
1. FIRST: Create TODO list using TodoWrite tool for EVERY user query (MANDATORY)
2. SECOND: Mark first TODO as in_progress and begin work
3. THIRD: Execute the specific task described in the TODO with concrete actions
4. FOURTH: Mark TODO as completed ONLY after providing actual results/findings
5. REPEAT: Move to next TODO item until all are completed

CRITICAL RULES:
- NEVER skip TodoWrite - use it immediately for ANY user request
- NEVER mark TODO as completed without performing actual work and providing concrete results
- ALWAYS work on TODOs sequentially, one at a time
- Each TODO must result in specific findings, analysis, code, or answers - not just status updates
- Break complex requests into detailed, actionable TODO items

Example for 'Search C# info': 1. Search web for C# SemanticKernel documentation and tutorials, 2. Analyze and categorize found resources by topic areas, 3. Extract key concepts and code examples, 4. Compile comprehensive tutorial with practical examples, 5. Provide structured learning path and resource links.");

这种强制性工作流程确保了任务管理的一致性和完整性。

2. 智能网络搜索集成(AgentFunction.cs:27-237)

项目还实现了类似Claude Code的网络搜索能力:

多搜索引擎支持

csharp 复制代码
    [KernelFunction,
     Description(
         """
         - Allows Claude to search the web and use the results to inform responses
         - Provides up-to-date information for current events and recent data
         - Returns search result information formatted as search result blocks
         - Use this tool for accessing information beyond Claude's knowledge cutoff
         - Searches are performed automatically within a single API call

         Usage notes:
           - Domain filtering is supported to include or block specific websites
           - Web search is only available in the US
           - Account for \\\"Today's date\\\" in <env>. For example, if <env> says \\\"Today's date: 2025-07-01\\\", and the user wants the latest docs, do not use 2024 in the search query. Use 2025.
         """)]
    public async Task<string> WebSearch(
        [Description("The search query to use")]
        string query,
        [Description("Only include search results from these domains")]
        string[]? allowed_domains,
        [Description("Never include search results from these domains")]
        string[]? blocked_domains)
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("User-Agent", "MarkAgents/1.0 (Compatible Search Engine)");
        client.Timeout = TimeSpan.FromSeconds(30);
        
        var searchEngines = new[]
        {
            "https://search.brave.com/api/search?q={0}&format=json&safesearch=moderate&count=10",
            "https://searx.be/search?q={0}&format=json&categories=general&safesearch=1",
            "https://paulgo.io/search?q={0}&format=json",
            "https://api.duckduckgo.com/?q={0}&format=json&no_html=1&skip_disambig=1"
        };
        
        var results = new StringBuilder();
        results.AppendLine($"# Search Results for: {query}");
        results.AppendLine();
        
        foreach (var engineUrl in searchEngines)
        {
            try
            {
                var searchUrl = string.Format(engineUrl, Uri.EscapeDataString(query));
                var response = await client.GetStringAsync(searchUrl);
                var searchData = JsonSerializer.Deserialize<JsonElement>(response);
                
                var engineResults = await ExtractSearchResults(searchData, allowed_domains, blocked_domains, client);
                if (!string.IsNullOrEmpty(engineResults))
                {
                    results.AppendLine(engineResults);
                    break;
                }
            }
            catch
            {
                continue;
            }
        }
        
        if (results.Length <= 50)
        {
            results.AppendLine("## Alternative Search Results");
            results.AppendLine();
            var fallbackResult = await FallbackWebSearch(query, allowed_domains, blocked_domains, client);
            results.AppendLine(fallbackResult);
        }
        
        return results.ToString();
    }
    
    private async Task<string> ExtractSearchResults(JsonElement searchData, string[]? allowedDomains, string[]? blockedDomains, HttpClient client)
    {
        var results = new StringBuilder();
        var count = 0;
        
        if (searchData.TryGetProperty("results", out var resultsArray))
        {
            foreach (var result in resultsArray.EnumerateArray())
            {
                if (count >= 8) break;
                
                if (result.TryGetProperty("url", out var urlProp) && 
                    result.TryGetProperty("title", out var titleProp))
                {
                    var url = urlProp.GetString() ?? "";
                    var title = titleProp.GetString() ?? "";
                    var snippet = "";
                    
                    if (result.TryGetProperty("content", out var contentProp))
                        snippet = contentProp.GetString() ?? "";
                    else if (result.TryGetProperty("description", out var descProp))
                        snippet = descProp.GetString() ?? "";
                    
                    if (!IsValidUrl(url, allowedDomains, blockedDomains)) continue;
                    
                    var detailedContent = await FetchPageContent(url, client);
                    
                    results.AppendLine($"## Result {count + 1}: {title}");
                    results.AppendLine($"**URL:** {url}");
                    results.AppendLine($"**Summary:** {snippet}");
                    if (!string.IsNullOrEmpty(detailedContent))
                    {
                        results.AppendLine($"**Content Preview:**");
                        results.AppendLine(detailedContent.Substring(0, Math.Min(500, detailedContent.Length)) + "...");
                    }
                    results.AppendLine();
                    count++;
                }
            }
        }
        else if (searchData.TryGetProperty("RelatedTopics", out var topics))
        {
            foreach (var topic in topics.EnumerateArray())
            {
                if (count >= 8) break;
                
                if (topic.TryGetProperty("Text", out var text) && 
                    topic.TryGetProperty("FirstURL", out var url))
                {
                    var urlStr = url.GetString() ?? "";
                    var textStr = text.GetString() ?? "";
                    
                    if (!IsValidUrl(urlStr, allowedDomains, blockedDomains)) continue;
                    
                    var detailedContent = await FetchPageContent(urlStr, client);
                    
                    results.AppendLine($"## Result {count + 1}");
                    results.AppendLine($"**URL:** {urlStr}");
                    results.AppendLine($"**Summary:** {textStr}");
                    if (!string.IsNullOrEmpty(detailedContent))
                    {
                        results.AppendLine($"**Content Preview:**");
                        results.AppendLine(detailedContent.Substring(0, Math.Min(500, detailedContent.Length)) + "...");
                    }
                    results.AppendLine();
                    count++;
                }
            }
        }
        
        return results.ToString();
    }
    
    private async Task<string> FetchPageContent(string url, HttpClient client)
    {
        try
        {
            var response = await client.GetStringAsync(url);
            var cleanContent = System.Text.RegularExpressions.Regex.Replace(response, @"<[^>]+>", " ");
            cleanContent = System.Text.RegularExpressions.Regex.Replace(cleanContent, @"\s+", " ");
            return cleanContent.Trim();
        }
        catch
        {
            return string.Empty;
        }
    }
    
    private bool IsValidUrl(string url, string[]? allowedDomains, string[]? blockedDomains)
    {
        try
        {
            var uri = new Uri(url);
            
            if (allowedDomains != null && allowedDomains.Length > 0)
            {
                if (!allowedDomains.Any(domain => uri.Host.Contains(domain, StringComparison.OrdinalIgnoreCase)))
                    return false;
            }
            
            if (blockedDomains != null && blockedDomains.Length > 0)
            {
                if (blockedDomains.Any(domain => uri.Host.Contains(domain, StringComparison.OrdinalIgnoreCase)))
                    return false;
            }
            
            return true;
        }
        catch
        {
            return false;
        }
    }
    
    private async Task<string> FallbackWebSearch(string query, string[]? allowedDomains, string[]? blockedDomains, HttpClient client)
    {
        var results = new StringBuilder();
        var searchTerms = query.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        
        var commonSources = new[]
        {
            $"https://github.com/search?q={Uri.EscapeDataString(query)}&type=repositories",
            $"https://stackoverflow.com/search?q={Uri.EscapeDataString(query)}",
            $"https://docs.microsoft.com/en-us/search/?terms={Uri.EscapeDataString(query)}",
        };
        
        foreach (var source in commonSources)
        {
            try
            {
                if (!IsValidUrl(source, allowedDomains, blockedDomains)) continue;
                
                var content = await FetchPageContent(source, client);
                if (!string.IsNullOrEmpty(content))
                {
                    results.AppendLine($"**Source:** {source}");
                    results.AppendLine($"**Content:** {content.Substring(0, Math.Min(300, content.Length))}...");
                    results.AppendLine();
                }
            }
            catch
            {
                continue;
            }
        }
        
        if (results.Length == 0)
        {
            results.AppendLine($"Search completed for query: {query}");
            results.AppendLine("No detailed results found from available search engines.");
            results.AppendLine($"Suggested search terms: {string.Join(", ", searchTerms)}");
        }
        
        return results.ToString();
    }

智能内容提取

  • HTML标签清理和内容标准化
  • 域名过滤(白名单/黑名单)
  • 结果去重和质量评估
  • 分块内容预览

3. 控制台用户体验优化

彩色输出系统

csharp 复制代码
if (item.Priority == Priority.High)
    Console.ForegroundColor = ConsoleColor.Red;
else if (item.Priority == Priority.Medium) 
    Console.ForegroundColor = ConsoleColor.Yellow;
else
    Console.ForegroundColor = ConsoleColor.Green;

if (item.Status == TodoInputItemStatus.Pending)
    Console.Write("□ ");
else if (item.Status == TodoInputItemStatus.InProgress)
    Console.Write("■ ");  
else if (item.Status == TodoInputItemStatus.Completed)
    Console.Write("✓ ");

这种设计提供了直观的视觉反馈,让开发者能够快速了解任务状态。

实际应用场景与最佳实践

1. 复杂项目开发场景

微服务架构开发

复制代码
高优先级任务:
■ 设计API网关路由配置
□ 实现用户认证服务
□ 创建订单处理微服务

中优先级任务:  
□ 编写单元测试用例
□ 配置Docker容器化
□ 设置CI/CD流水线

低优先级任务:
□ 编写API文档
□ 性能测试和优化

结论

通过深入分析Claude Code的TODO功能并使用Semantic Kernel进行本土化实现,MarkAgents项目成功地展示了如何在.NET生态系统中构建智能的任务管理和代理系统。项目不仅实现了Claude Code的核心功能特性,还结合.NET平台的优势提供了额外的扩展性和定制化能力。

这种实现方案为开发者提供了:

  • 完整的功能对等:涵盖Claude Code的主要TODO管理特性
  • 技术栈一致性:与现有.NET项目无缝集成
  • 可扩展架构:支持未来功能的持续演进
  • 开源友好:便于社区贡献和定制开发

技术交流

开源地址:https://github.com/AIDotNet/MarkAgents

qq交流群:961090189