惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
Arctic Wolf
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Troy Hunt's Blog
Latest news
Latest news
Help Net Security
Help Net Security
S
Security Affairs
Webroot Blog
Webroot Blog
The Hacker News
The Hacker News
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tor Project blog
Forbes - Security
Forbes - Security
Google DeepMind News
Google DeepMind News
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
H
Help Net Security
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
MongoDB | Blog
MongoDB | Blog
Cyberwarzone
Cyberwarzone
The Last Watchdog
The Last Watchdog
S
Securelist
N
News and Events Feed by Topic
S
Secure Thoughts
F
Fortinet All Blogs
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
M
MIT News - Artificial intelligence
F
Full Disclosure
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Microsoft Security Blog
Microsoft Security Blog
I
InfoQ
P
Privacy International News Feed
L
LangChain Blog
Know Your Adversary
Know Your Adversary
C
CERT Recently Published Vulnerability Notes

博客园_首页

Linux实操--组管理、权限管理和定时任务 Java + EasyExcel 实现单个接口导出多个Excel Mem0 源码解析系列(二):提示词工程的深度剖析 Openclaw TaskFlow究竟是什么?和普通Skill技能有什么区别 博文阅读密码验证 - 博客园 嘉立创开源:应该是全网MicroPython教程最多的开发板 Hermes Agent 集成实践:从协议到生产 2026年AI编程工具横评:Cursor、Codex、Claude Code、Zed、Windsurf Java程序员必看的RAG入门教程 2026 AI效率神器:Superpowers + Claude Code 保姆级教程 本地大模型部署全攻略:从 0 到 1 玩转 Ollama 【从0到1构建一个ClaudeAgent】内存管理-上下文压缩 .NET 高级开发 | 设计、实现一个事件总线框架 电子小白入门之NE555 3. WorkBuddy:隐藏玩法,一键召唤专家,让 AI 以"专家身份"给你干活 和AI一起搞事情#3:Claude Teammate 游戏开发翻车实录 【OpenClaw】通过 Nanobot 源码学习架构---(7)Memory C# .NET 周刊|2026年3月3期 我在 Debian 11 上把 K8s 单机搭起来了,过程没你想的那么顺(/opt 目录版) 深度学习进阶(七)Data-efficient Image Transformer CLI+Skill搭建浏览器AI自动化框架,告别一切重复枯燥任务 告别Token账单无底洞:OpenClaw本地部署,重塑企业数据主权的唯一解 FastAPI+Vue:文件分片上传+秒传+断点续传,这坑我帮你踩平了! SBTI 爆火后,我做了个程序员版的 CBTI。。已开源 + 附开发过程 多模态检索开始进入工程期:用 Sentence Transformers 搭建可落地的 Multimodal RAG 100多行代码实现一个最简单的Agent(用ReAct) Claude Code 通关手册(八):推荐 5 个 Hooks,代码质量提升 3 倍 老板:“有人截图了!”。安全部门:“收到,马上查暗水印!” - why技术 技术之外,皆是人间 C#/.NET/.NET Core技术前沿周刊 | 第 69 期(2026年4.01-4.12) Snack JSONPath 项目架构分析 Claude Code Buddy 小析:一个非核心功能,如何体现产品的细节完成度 AI新时代下的图床管理方案-Cloudflare图床+MCP+Skills方案指南 化繁为简:顺丰速运App如何通过 HarmonyOS SDK实现专业级空间测量 从零实现富文本编辑器#13-React非编辑节点的内容渲染 AI开发-python-langchain框架(3-23-OpenAI Functions风格Tool Calling智能助手) .NET + AI 进阶实战:基于类的技能开发 - 打造可治理的 Agent 能力模块 【从0到1构建一个ClaudeAgent】规划与协调-技能 上周热点回顾(4.6-4.12) 电子小白的工具三件套:面包板、杜邦线、万能板 单表五亿数据的查询优化 | Mysql、StarRocks 2. WorkBuddy:从“我是谁”到“帮我干活” C# 如何减少代码运行时间:7 个实战技巧 基于HelixToolkit.SharpDX 渲染3D模型 - 笺上知微 从零开始的双臂具身VLA起源及现阶段发展综述 - SkyXZ 记对 xonsh shell 的使用, 脚本编写, 迁移及调优 - pluvium27 受够了Vibe Coding的失控?换个起点,让AI事半功倍 从开始配置漏洞环境到漏洞复现流程 - 難しい 关于10年工作经验的程序员对OpenClaw的实战经验分享以及看法 - 虚无境 Any metadata 的内存布局 C# .NET 周刊|2026年3月2期 - InCerry 我帮你测过了,测试圈排名第二的 Skill 依然很牛逼 Skill Discovery | 无监督技能发现的经典工作总结 - MoonOut PbootCMS 网站内容数量多导致访问慢?这些实用优化方案帮你提速! - 家兴网络技术工作室 上下文工程是什么?过时了么?一文讲明白! - 一枫说码 网站漏洞怎么发现并修复?一篇实用指南(附完整流程) - 家兴网络技术工作室 开了 TUN 模式还是直连?90% 的人都踩过这个坑 Github日报|2026年04月12日 - AI一族 AScript扩展多种脚本语言 - rockey627 AI 学习笔记:Agent 的记忆机制 你能被装进一个文件里吗?——7 万人把同事"蒸馏"成了 AI - 我没有三颗心脏 Claude Code 通关手册(七):给 AI 装上技能包——Skills 完全指南 - 暮色之狐 在浏览器中快速编辑代码:VSCode Web 集成实践 - Newbe36524 蒸馏自己 skill?基于 Deepseek 的蒸馏器,丐版蒸馏方式,简单便捷 - To_Carpe_Diem Spring AI Aliababa和AgentScope,哪个更好? - 苏三说技术 Etsy 把 1000 个 MySQL 分片迁进 Vitess:425TB 数据背后的真正问题不是性能,而是运维规模 MicroPython LVGL基础知识和概念:底层渲染与性能优化 - FreakStudio 数据库草图算法 Python 潮流周刊#146:CPython 引入 Rust 的进展 - 豌豆花下猫 最小生成树 - mofei1116 红日靶场七:从外网入口、容器逃逸到 AD 接管的完整利用链复盘 - YouDiscovered1t 分享四款开源且实用的 Kafka 管理工具 - 追逐时光者 vLLM 权重加载机制全解析:从挑战到理想架构 LCT 学习笔记 - ACehomoxue Avalonia UI 12.0.0 正式发布:架构演进和性能飞跃 - 张善友 当 AI Agent 把调用链拉长,延迟开始成为一门生意 conhost.exe 无法显示 U+2717 - 145a 太秀了,我把自己蒸馏成了 Skill!已开源 - 程序员鱼皮 ASP.NET Core 内存缓存实战:一篇搞懂该怎么配、怎么避坑 基于 Ghostty 带有分割标签页和为 Claude 编程设计的通知终端 - BugShare AI 焊死入口:教育的“操作系统级”重塑 - 郝hai 初级Java开发工程师使用sql脚本编写代码的过程是简单而且不糊涂 - CoderOilStation Claude Code通关手册(六):MCP协议完全指南 - 暮色之狐 边框灯光环绕动画特效实现指南 - Newbe36524 开源:子木蒸馏版的 SEO 审计工具 seo-audit-skill v1.0 我所理解的Python元模型 【从0到1构建一个ClaudeAgent】规划与协调-TodoWrite - 程序员Seven Claude 和 Codex 在审计 Skill 上性能差异探究 - ACai_sec AScript如何实现中文脚本引擎 - rockey627 【渗透测试】HTB Season10 Garfield 全过程wp - dynasty_chenzi Android 开发者为什么必须掌握 AI 能力?端侧视角下的技术变革 树状数组正确性证明 - AC-wyr 你的 AI 焦虑,可能比 AI 本身更危险——ATM 机没有消灭银行柜员,但恐慌消灭了你的判断力 - 我没有三颗心脏 一个拉胯的分库分表方案有多绝望?整个部门都在救火! - 冰河团队 动态规划入门必学之走方格问题 - Ofnoname PostgREST 与 PostgreSQL 角色权限配置全解析(生产级实践) - SheepDog1998 使用 UEFI 图形输出协议 GOP 在屏幕上显示图像的方法 - 阿源- Claude Code通关手册(五):组建你的AI专家团队,子代理系统 - 暮色之狐 一个程序员到架构师的催婚路之感悟(整整10年后的催婚相亲感悟) - MisterLip 用 Agent Skill 自动生成工作周报 - 赵康
【从0到1构建一个ClaudeAgent】并发-后台任务
程序员Seven · 2026-04-16 · via 博客园_首页

有些操作很慢,Agent 不能干等着。例如长时间编译/构建make, mvn compile, gradle build大数据处理hadoop, spark-submit 等的一些工作

Java实现代码

public class BackgroundTasksSystem {
    // --- 配置 ---
    private static final Path WORKDIR = Paths.get(System.getProperty("user.dir"));
    private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    
    // --- 后台任务管理器 ---
    static class BackgroundManager {
        // 任务存储
        private final Map<String, TaskInfo> tasks = new ConcurrentHashMap<>();
        // 通知队列
        private final Queue<TaskNotification> notificationQueue = new ConcurrentLinkedQueue<>();
        // 任务 ID 生成器
        private final AtomicInteger taskIdCounter = new AtomicInteger(1);
        // 锁
        private final Object lock = new Object();
        
        static class TaskInfo {
            String taskId;
            String status;  // running, completed, timeout, error
            String result;
            String command;
            long startTime;
            Thread thread;  // 关联的执行线程
        }
        
        static class TaskNotification {
            String taskId;
            String status;
            String command;
            String result;
        }
        
        /**
         * 启动后台任务
         * 立即返回任务 ID,不等待命令完成
         */
        public String run(String command) {
            String taskId = "task_" + taskIdCounter.getAndIncrement();
            
            TaskInfo task = new TaskInfo(taskId, command);
            tasks.put(taskId, task);
            
            // 创建并启动后台线程
            Thread thread = new Thread(() -> executeTask(task), "BackgroundTask-" + taskId);
            thread.setDaemon(true);
            task.thread = thread;
            thread.start();  // 立即返回,不阻塞
            
            return String.format("Background task %s started: %s", 
                taskId, command.substring(0, Math.min(command.length(), 80)));
        }
        
        /**
         * 线程目标:执行子进程,捕获输出,推送结果到队列
         */
        private void executeTask(TaskInfo task) {
            String output;
            String status;
            
            try {
                ProcessBuilder pb = new ProcessBuilder("bash", "-c", task.command);
                pb.directory(WORKDIR.toFile());
                pb.redirectErrorStream(true);
                
                Process process = pb.start();
                boolean finished = process.waitFor(300, TimeUnit.SECONDS);  // 5分钟超时
                
                if (!finished) {
                    process.destroy();
                    output = "Error: Timeout (300s)";
                    status = "timeout";
                } else {
                    output = new String(process.getInputStream().readAllBytes()).trim();
                    status = "completed";
                }
            } catch (Exception e) {
                output = "Error: " + e.getMessage();
                status = "error";
            }
            
            // 更新任务状态
            task.status = status;
            task.result = output.isEmpty() ? "(no output)" : 
                          output.substring(0, Math.min(output.length(), 50000));
            
            // 添加通知到队列
            synchronized (lock) {
                notificationQueue.offer(new TaskNotification(
                    task.taskId,
                    status,
                    task.command.substring(0, Math.min(task.command.length(), 80)),
                    task.result.substring(0, Math.min(task.result.length(), 500))
                ));
            }
        }
        
        /**
         * 检查任务状态
         * 如果指定 taskId,检查单个任务;否则列出所有任务
         */
        public String check(String taskId) {
            if (taskId != null && !taskId.isEmpty()) {
                TaskInfo task = tasks.get(taskId);
                if (task == null) {
                    return "Error: Unknown task " + taskId;
                }
                return String.format("[%s] %s\n%s", 
                    task.status,
                    task.command.substring(0, Math.min(task.command.length(), 60)),
                    task.result != null ? task.result : "(running)");
            } else {
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, TaskInfo> entry : tasks.entrySet()) {
                    TaskInfo task = entry.getValue();
                    sb.append(String.format("%s: [%s] %s\n", 
                        task.taskId,
                        task.status,
                        task.command.substring(0, Math.min(task.command.length(), 60))));
                }
                return sb.length() > 0 ? sb.toString().trim() : "No background tasks.";
            }
        }
        
        /**
         * 清空通知队列并返回所有待处理的通知
         */
        public List<TaskNotification> drainNotifications() {
            synchronized (lock) {
                List<TaskNotification> notifications = new ArrayList<>();
                while (!notificationQueue.isEmpty()) {
                    notifications.add(notificationQueue.poll());
                }
                return notifications;
            }
        }
        
        /**
         * 获取所有任务
         */
        public Map<String, TaskInfo> getAllTasks() {
            return new HashMap<>(tasks);
        }
    }
    
    // 初始化后台管理器
    private static final BackgroundManager BG_MANAGER = new BackgroundManager();
    
    // --- 工具枚举 ---
    public enum ToolType {
        BASH("bash", "Run a shell command (blocking)."),
        READ_FILE("read_file", "Read file contents."),
        WRITE_FILE("write_file", "Write content to file."),
        EDIT_FILE("edit_file", "Replace exact text in file."),
        BACKGROUND_RUN("background_run", "Run command in background thread. Returns task_id immediately."),  // 新增
        CHECK_BACKGROUND("check_background", "Check background task status. Omit task_id to list all.");  // 新增
        public final String name;
        public final String description;
        ToolType(String name, String description) { this.name = name; this.description = description; }
    }

    // --- 工具处理器映射 ---
    private static final Map<String, ToolExecutor> TOOL_HANDLERS = new HashMap<>();
    
    static {
        // ... 省略基础工具注册
        
        // 后台任务工具
        TOOL_HANDLERS.put(ToolType.BACKGROUND_RUN.name, args -> {
            String command = (String) args.get("command");
            return BG_MANAGER.run(command);
        });
        
        TOOL_HANDLERS.put(ToolType.CHECK_BACKGROUND.name, args -> {
            String taskId = (String) args.get("task_id");
            return BG_MANAGER.check(taskId);
        });
    }
    
    // ... 省略相同的工具实现
    
    // --- Agent 主循环(集成后台任务通知)---
    public static void agentLoop(List<Map<String, Object>> messages) {
        while (true) {
            try {
                // 在 LLM 调用前检查后台通知
                List<BackgroundManager.TaskNotification> notifications = BG_MANAGER.drainNotifications();
                
                if (!notifications.isEmpty() && !messages.isEmpty()) {
                    StringBuilder notifText = new StringBuilder();
                    notifText.append("<background-results>\n");
                    
                    for (BackgroundManager.TaskNotification notif : notifications) {
                        notifText.append(String.format("[bg:%s] %s: %s\n", 
                            notif.taskId, notif.status, notif.result));
                    }
                    
                    notifText.append("</background-results>");
                    
                    messages.add(Map.of(
                        "role", "user",
                        "content", notifText.toString()
                    ));
                    
                    messages.add(Map.of(
                        "role", "assistant",
                        "content", "Noted background results."
                    ));
                    // 异步结果注入:将后台任务结果插入到对话中
                    // 结构化格式:用XML标签包裹,便于LLM解析
                }
                
                // 显示当前活动任务
                Map<String, BackgroundManager.TaskInfo> activeTasks = BG_MANAGER.getAllTasks();
                int runningTasks = (int) activeTasks.values().stream()
                    .filter(t -> "running".equals(t.status))
                    .count();
                
                if (runningTasks > 0) {
                    System.out.printf("[Active background tasks: %d]\n", runningTasks);
                }
                
                // ... 省略相同的 LLM 调用和工具执行逻辑
                
            } catch (Exception e) {
                System.err.println("Error in agent loop: " + e.getMessage());
                e.printStackTrace();
                return;
            }
        }
    }
}

这段代码引入了后台任务系统,解决了 Agent 在执行长时间任务时的阻塞问题

关键洞察:Agent 可以在命令执行时继续工作,而不是被阻塞。

异步任务处理架构

核心思想:从同步阻塞的任务执行升级为异步非阻塞的并发处理,让Agent能够同时处理多个耗时任务,实现"并行计算"能力,大幅提升效率和响应性。

// 后台任务管理器 - 异步执行引擎
static class BackgroundManager {
    // 任务存储
    private final Map<String, TaskInfo> tasks = new ConcurrentHashMap<>();
    // 通知队列
    private final Queue<TaskNotification> notificationQueue = new ConcurrentLinkedQueue<>();
    // 任务 ID 生成器
    private final AtomicInteger taskIdCounter = new AtomicInteger(1);
    // 并发安全:使用线程安全集合
    // 异步通信:通过队列传递任务结果
    // 唯一标识:自动生成任务ID
}
  • 解耦执行:任务提交和执行分离,立即返回控制权
  • 并发管理:多个后台任务可以同时运行
  • 结果异步收集:通过队列机制收集完成的任务结果
  • 线程安全:使用并发集合确保多线程安全

任务信息结构设计

// 任务信息实体
static class TaskInfo {
    String taskId;        // 唯一标识
    String status;        // 状态:running, completed, timeout, error
    String result;        // 执行结果
    String command;       // 执行的命令
    long startTime;       // 开始时间
    Thread thread;        // 关联的执行线程
    // 完整状态跟踪:从启动到完成的全生命周期
    // 线程关联:可以控制或监控执行线程
    // 时间戳:支持超时和性能分析
}

// 任务通知实体
static class TaskNotification {
    String taskId;
    String status;
    String command;
    String result;
    // 轻量传输:只包含必要信息
    // 结构化:易于解析和处理
    // 结果截断:避免过大的通知消息
}
  • 状态驱动:明确的任务状态生命周期
  • 结果持久:任务结果可以多次查询
  • 线程管理:可以跟踪和控制执行线程
  • 事件驱动:通过通知机制传递完成事件

异步任务启动机制

/**
 * 启动后台任务
 * 立即返回任务 ID,不等待命令完成
 */
public String run(String command) {
    String taskId = "task_" + taskIdCounter.getAndIncrement();
    
    TaskInfo task = new TaskInfo(taskId, command);
    tasks.put(taskId, task);
    
    // 创建并启动后台线程
    Thread thread = new Thread(() -> executeTask(task), "BackgroundTask-" + taskId);
    thread.setDaemon(true);  // 守护线程,不会阻止JVM退出
    task.thread = thread;
    thread.start();  // 立即返回,不阻塞调用者
    
    return String.format("Background task %s started: %s", 
        taskId, command.substring(0, Math.min(command.length(), 80)));
    // 异步启动:立即返回任务ID,不等待命令完成
    // 守护线程:不会阻止程序正常退出
    // 线程命名:便于调试和监控
}
  • 立即返回:不阻塞主线程,立即返回控制权
  • 守护线程:后台任务不会阻止JVM退出
  • 资源管理:线程自动清理,避免内存泄漏
  • 友好反馈:返回任务ID和简化的命令描述

任务执行与结果收集

/**
 * 线程目标:执行子进程,捕获输出,推送结果到队列
 */
private void executeTask(TaskInfo task) {
    String output;
    String status;
    
    try {
        ProcessBuilder pb = new ProcessBuilder("bash", "-c", task.command);
        pb.directory(WORKDIR.toFile());
        pb.redirectErrorStream(true);
        
        Process process = pb.start();
        boolean finished = process.waitFor(300, TimeUnit.SECONDS);  // 5分钟超时
        
        if (!finished) {
            process.destroy();
            output = "Error: Timeout (300s)";
            status = "timeout";
        } else {
            output = new String(process.getInputStream().readAllBytes()).trim();
            status = "completed";
        }
    } catch (Exception e) {
        output = "Error: " + e.getMessage();
        status = "error";
    }
    
    // 更新任务状态
    task.status = status;
    task.result = output.isEmpty() ? "(no output)" : 
                  output.substring(0, Math.min(output.length(), 50000));
    
    // 添加通知到队列
    synchronized (lock) {
        notificationQueue.offer(new TaskNotification(
            task.taskId,
            status,
            task.command.substring(0, Math.min(task.command.length(), 80)),
            task.result.substring(0, Math.min(task.result.length(), 500))
        ));
    }
}
  • 超时保护:防止长时间运行的任务阻塞
  • 异常安全:全面捕获执行异常
  • 内存管理:截断大结果,避免内存溢出
  • 事件驱动:完成后立即通知主线程

智能通知注入机制

// 在 LLM 调用前检查后台通知
List<BackgroundManager.TaskNotification> notifications = BG_MANAGER.drainNotifications();

if (!notifications.isEmpty() && !messages.isEmpty()) {
    StringBuilder notifText = new StringBuilder();
    notifText.append("<background-results>\n");
    
    for (BackgroundManager.TaskNotification notif : notifications) {
        notifText.append(String.format("[bg:%s] %s: %s\n", 
            notif.taskId, notif.status, notif.result));
    }
    
    notifText.append("</background-results>");
    
    messages.add(Map.of(
        "role", "user",
        "content", notifText.toString()
    ));
    
    messages.add(Map.of(
        "role", "assistant",
        "content", "Noted background results."
    ));
    // 自动注入:自动将后台结果插入到对话中
    // 结构化格式:XML标签明确标识内容类型
    // 对话完整:添加assistant确认,保持对话结构
    // 时机智能:在LLM调用前插入,确保LLM能看到最新结果
}
  • 自动同步:后台结果自动同步到主对话
  • 结构化格式:便于LLM识别和解析
  • 对话集成:无缝集成到现有对话流
  • 时机优化:在决策前注入,确保信息及时性

工具集成架构

// 后台任务工具集
public enum ToolType {
    BACKGROUND_RUN("background_run", "Run command in background thread. Returns task_id immediately."),
    CHECK_BACKGROUND("check_background", "Check background task status. Omit task_id to list all.");
    // 异步执行:立即返回,不阻塞
    // 状态查询:支持单个和批量查询
    // 语义清晰:工具名明确表示异步特性
}

// 工具处理器映射
TOOL_HANDLERS.put(ToolType.BACKGROUND_RUN.name, args -> {
    String command = (String) args.get("command");
    return BG_MANAGER.run(command);
    // 委托执行:将命令转交给后台管理器
    // 立即返回:不等待任务完成
});

TOOL_HANDLERS.put(ToolType.CHECK_BACKGROUND.name, args -> {
    String taskId = (String) args.get("task_id");
    return BG_MANAGER.check(taskId);
    // 灵活查询:支持单任务详查和列表概览
});
  • 接口统一:与同步工具相同的调用方式
  • 异步语义:工具名明确区分同步/异步
  • 灵活查询:支持多种查询方式
  • 无缝集成:与现有工具系统完全兼容

架构演进与价值

从 ContextCompactSystem 到 BackgroundTasksSystem 的升级

维度 ContextCompactSystem BackgroundTasksSystem
执行模式 同步串行 异步并行
吞吐量 一次一个任务 并发多个任务
响应性 阻塞等待 立即响应
资源利用 单线程 多线程并发
任务类型 短任务为主 长短任务混合