<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      使用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功能的本土化實現:

      技術棧選型

      <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數據結構:

      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)

      關鍵實現亮點:

      [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架構優勢

      插件系統設計

      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)

      
      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的網絡搜索能力:

      多搜索引擎支持

      
          [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. 控制臺用戶體驗優化

      彩色輸出系統

      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

      posted on 2025-07-23 02:07  239573049  閱讀(747)  評論(2)    收藏  舉報



      主站蜘蛛池模板: 国产丰满乱子伦午夜福利| 天天澡日日澡狠狠欧美老妇| 狠狠躁日日躁夜夜躁欧美老妇 | 精品无码成人片一区二区| 欧美老熟妇乱子伦牲交视频| 香港日本三级亚洲三级| 新闻| 人妻中文字幕不卡精品| 国产四虎永久免费观看| 精品无码一区二区三区在线| 国産精品久久久久久久| 亚洲制服无码一区二区三区 | 国产成人欧美日韩在线电影| 人妻系列无码专区69影院| 精品一区二区亚洲国产| 加勒比中文字幕无码一区| 久久久久国产一级毛片高清版A| 丰满妇女强制高潮18xxxx | 国产精品久久无码不卡黑寡妇| 末发育娇小性色xxxxx视频| 日韩精品一区二区三区无| 永久黄网站色视频免费直播| 亚洲精品动漫免费二区| 亚洲精品国产综合久久一线| 香港日本三级亚洲三级| 日韩中文字幕v亚洲中文字幕| 久久人妻av无码中文专区| 午夜福利看片在线观看| xxxxbbbb欧美残疾人| 国产高清自产拍AV在线| 国产精品中文字幕第一页| 亚洲av午夜福利精品一区二区| 久国产精品韩国三级视频| 大港区| 99福利一区二区视频| 少妇爽到呻吟的视频| 亚洲AV日韩AV高清在线观看| 亚洲av影院一区二区三区| 亚洲熟女乱综合一区二区| 激情亚洲内射一区二区三区| 成人免费亚洲av在线|