Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Model: claude-opus-4-6 (anthropic/claude-opus-4-6) Generated: 2026-04-03 Book: Claude Code VS OpenCode: Architecture, Design and The Road Ahead 章节: 第12章 — 解剖一个13万行代码的插件 Token Usage: ~120,000 input + ~7,500 output

12.8 背景智能体生成器与会话管理

什么是“背景智能体“?

想象你是项目经理(Sisyphus),手头大任务需要多人并行:让 A 调研技术方案,让 B 搜索代码库,让 C 查文档。他们在后台工作,完成后报告给你。

OMO 的背景智能体就是这个机制。但关键区别:它们不是轻量协程,而是真正的 OpenCode session

graph LR
    subgraph Light["Lightweight Coroutine"]
        LC1["Shared memory"]
        LC2["No history"]
        LC3["No persistence"]
    end

    subgraph Session["OpenCode Session"]
        S1["Independent transcript"]
        S2["Full message history"]
        S3["Parent-child relation"]
        S4["Session ID tracking"]
        S5["Native tool chain"]
    end

    style Light fill:#ffcdd2
    style Session fill:#c8e6c9

核心架构

📁 文件说明:src/features/background-agent/ 目录 包括 manager.ts(管理)、spawner.ts(启动)、concurrency.ts(并发)、state.ts(状态)等。

flowchart TD
    Main(["Main Agent calls task"]) --> BM["BackgroundManager"]
    BM --> Queue["Task Queue<br/>grouped by concurrency key"]
    Queue --> CM["ConcurrencyManager"]
    CM --> Spawn["Spawner"]
    Spawn --> Session["Create OC Session<br/>set parent session"]
    Session --> Agent["Select Agent + Model"]
    Agent --> Send["Send Prompt"]
    Send --> Running["Task Running..."]
    Running --> Done["Complete"]
    Done --> Notify["Notify Parent"]
    Notify --> Parent(["Main Agent Gets Result"])

一个任务的完整旅程

flowchart TD
    Submit(["Submit Task"]) --> Pending["Status: pending<br/>Record in taskHistory"]
    Pending --> Enqueue["Enqueue by concurrency key"]
    Enqueue --> Check{Within limit?}
    Check -->|Yes| Start["Status: running"]
    Check -->|No| Wait["Queue and Wait"]
    Wait --> Start
    Start --> Dir["Inherit parent workdir"]
    Dir --> Create["Create Child Session"]
    Create --> Tmux{Tmux available?}
    Tmux -->|Yes| Pane["Open tmux pane<br/>Visualize agent work"]
    Tmux -->|No| NoPane["Skip visualization"]
    Pane --> Send["Send Prompt with tool restrictions"]
    NoPane --> Send
    Send --> Exec["Agent Works..."]
    Exec --> Complete["Task Complete"]
    Complete --> Release["Release Concurrency Slot"]
    Release --> Notify["Notify Parent Session"]

关键细节

继承工作目录:子智能体在父会话的工作目录里继续,保证项目上下文一致。

工具限制

flowchart LR
    subgraph Allowed["Allowed Tools"]
        A1["call_omo_agent"]
        A2["All standard tools"]
    end
    subgraph Blocked["Blocked Tools"]
        B1["task - prevent infinite nesting"]
        B2["question - can't ask user in bg"]
    end
    style Blocked fill:#ffcdd2

tmux 可视化:每个后台子智能体自动获得一个 tmux pane。


并发控制详解

flowchart TD
    Task(["New Task"]) --> Key["Compute Key"]

    subgraph KeyLogic["Key Computation"]
        K1{Explicit model?}
        K1 -->|Yes| K2["key = provider/model<br/>e.g. anthropic/claude-sonnet"]
        K1 -->|No| K3["key = agent name<br/>e.g. explore"]
    end

    Key --> Acquire["acquire()"]
    Acquire --> Below{count < limit?}
    Below -->|Yes| Inc["count++ and run"]
    Below -->|No| Enqueue["Push to wait queue"]

释放时的 Handoff 机制

flowchart TD
    Release["release()"] --> HasWaiter{Queue has waiter?}
    HasWaiter -->|Yes| Handoff["Direct handoff<br/>Don't decrement count"]
    HasWaiter -->|No| Dec["count--"]
    Handoff --> Next["Next task starts immediately"]

直接交接避免了“释放后被新任务抢走“的竞态问题。


父会话通知机制

flowchart TD
    T1["Task A completes"] --> Queue["Notification Queue"]
    T2["Task B completes"] --> Queue
    T3["Task C completes"] --> Queue
    Queue --> Batch["Batch within time window"]
    Batch --> Notify["Single notification to parent:<br/>3 background tasks completed"]

📁 文件说明:src/features/background-agent/manager.ts BackgroundManager 维护 notifications 队列、pendingByParent、completion timers、idle deferral timers 等。

批量通知:5 个后台任务完成时,不发 5 条独立通知——打包成一条,减少对主智能体的打断。


Session 继续

路径 1:同步继续

📁 文件说明:src/features/background-agent/subagent-session-creator.ts 创建或复用子智能体 session。

flowchart TD
    Call["call_omo_agent"] --> HasID{session_id provided?}
    HasID -->|Yes| Load["Load Existing Session<br/>Full context preserved"]
    HasID -->|No| Create["Create New Session"]
    Load --> Send["Continue with new prompt"]
    Create --> Send

省 70%+ token:不用重新描述之前的结果,直接在已有上下文上继续。

路径 2:任务树追踪

flowchart TD
    Parent["Parent Session"] --> T1["Child Task A<br/>session: ses_001"]
    Parent --> T2["Child Task B<br/>session: ses_002"]
    T2 --> T3["Grandchild Task<br/>session: ses_003"]

    BM["BackgroundManager"] -->|"getTasksByParentSession()"| T1 & T2
    BM -->|"getAllDescendantTasks()"| T1 & T2 & T3

Boulder State:长期计划持久化

📁 文件说明:src/features/boulder-state/storage.ts “巨石状态“存储。把长期计划持久化到 .sisyphus/ 目录。

“Boulder”(巨石)来自西西弗斯神话——需要持续推进的长期计划。

flowchart LR
    BS["Boulder State"] --> F1["active_plan"]
    BS --> F2["started_at"]
    BS --> F3["session_ids list"]
    BS --> F4["plan_name"]

支持的操作:

flowchart TD
    Append["appendSessionId()<br/>Add session to plan"] --> State["Boulder State File"]
    Clear["clearBoulderState()<br/>Stop plan"] --> State
    Find["findPrometheusPlans()<br/>Find plan markdown"] --> State
    Progress["getPlanProgress()<br/>Count checkboxes"] --> State

三层持久化架构

flowchart TD
    subgraph L1["Layer 1: OpenCode Session - Memory"]
        S1["Conversation history"]
        S2["Runtime context"]
        S3["Tool call records"]
    end
    subgraph L2["Layer 2: Background Task State - Runtime"]
        T1["Task queue + status"]
        T2["Notification queue"]
        T3["Concurrency counters"]
    end
    subgraph L3["Layer 3: Boulder State - Disk"]
        B1["Active plan info"]
        B2["Associated session IDs"]
        B3["Progress tracking"]
    end

中断恢复

flowchart LR
    Crash["System Restart"] --> L1_Lost["L1: Lost"]
    Crash --> L2_Lost["L2: Lost"]
    Crash --> L3_OK["L3: Preserved on disk"]
    L3_OK --> Resume["Read plan file<br/>Know where we left off<br/>Rebuild L1 + L2"]

    style L1_Lost fill:#ffcdd2
    style L2_Lost fill:#ffcdd2
    style L3_OK fill:#c8e6c9

全景总结

graph TD
    subgraph Capabilities["Background Agent Capabilities"]
        Cap1["Task Creation<br/>via OC Session"]
        Cap2["Concurrency Control<br/>3-layer limits"]
        Cap3["Parent Notification<br/>Batch system"]
        Cap4["Context Preservation<br/>session_id continue"]
        Cap5["Visualization<br/>tmux panes"]
        Cap6["Crash Recovery<br/>Boulder State"]
        Cap7["Task Tree Tracking<br/>parent-child-grandchild"]
    end

OMO 的后台智能体不是简单的异步 job——它们有 session、任务树、通知系统和计划持久化共同支撑。


本节要点

  • 后台智能体 = 真正的 OpenCode session:独立消息历史和工具链路
  • 并发控制三层限额:model → provider → default(5),加 handoff 保证正确性
  • 批量通知:避免打断主智能体思路
  • session 继续:通过 session_id 复用,节省 70%+ token
  • 三层持久化:Session(内存) → Task State(运行时) → Boulder State(磁盘)
  • 子智能体有限制:不能再派子任务、不能向用户提问