Skip to content

tgoai/cos

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Company OS (cos)

用多个 AI Agent 自动运营一家公司。Agent 通过文件系统了解和管理公司状态,通过 CLI 执行实际工作。

文件即状态     公司的一切(组织、项目、任务、决策)都是文件
CLI 即能力     Agent 通过命令行工具与外部世界交互
人类可读       所有文件使用 Markdown + YAML,人类随时可审查和干预
Git 友好       公司全部状态可版本化,拥有完整变更历史

架构概览

协作模式(非技术视角)

graph TB
    subgraph Human["👤 人类决策层"]
        Admin[<b>人类管理员</b><br/>设定目标 · 审批决策 · 资源分配]
    end

    subgraph OS["⚙️ Company OS 智能引擎"]
        direction TB
        Core[<b>核心调度与执行</b>]
    end

    subgraph Agents["🤖 多角色 Agent 协作团队"]
        direction LR
        CEO[<b>CEO Agent</b><br/>接收指令 · 分解任务 · 调度协调]
        PM[<b>PM Agent</b><br/>规划任务 · 协调进度]
        Dev[<b>Dev Agent</b><br/>编写代码 · 修复 Bug]
        QA[<b>QA Agent</b><br/>自动化测试 · 质量把控]
    end

    subgraph Storage["📁 共享工作空间 (文件系统)"]
        Docs[任务单 / 代码库 / 知识库 / 决策记录]
    end

    Admin -->|下达指令 / 审批| CEO
    CEO -->|分解任务 · 调度| OS
    OS -->|调度任务| PM & Dev & QA

    CEO & PM & Dev & QA <-->|读写协作| Storage
    CEO -.->|指令分发| PM & Dev & QA
    PM -.->|任务流转| Dev
    Dev -.->|交付物| QA
    QA -.->|反馈| PM
    PM & Dev & QA -.->|汇报| CEO

    style Human fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
    style OS fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
    style Agents fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
    style Storage fill:#f5f5f5,stroke:#9e9e9e,stroke-dasharray: 5 5
Loading

Company OS 的核心在于人机协同:人类管理员只需与 CEO Agent 沟通,CEO 负责将指令分解为任务并调度其他 Agent(PM、Dev、QA 等)执行。所有 Agent 通过共享的文件系统进行异步协作,自动完成具体工作。

系统全景

graph TB
    subgraph Human["👤 Human Admin"]
        Admin[管理员]
    end

    subgraph CLI_Layer["cos CLI(人类 + Agent 共用)"]
        CLI[cos]
        CLI_Sub["init | agent | task | msg | session<br/>config | memory | project | ..."]
        AgentRun["cos agent run<br/>直接执行引擎"]
    end

    subgraph Daemon["cosd 守护进程"]
        direction TB
        Scheduler["Scheduler<br/>调度器"]
        Executor["Executor<br/>执行引擎"]
    end

    subgraph Triggers["触发源"]
        Cron["⏰ CronSource"]
        Watch["📁 WatchSource"]
        Invoke["🔔 InvokeSource"]
    end

    subgraph Runtime["运行时组件"]
        LM["LifecycleManager<br/>状态机"]
        EQ["EventQueue<br/>优先级队列"]
        Slots["SlotManager<br/>并发控制"]
        EH["ErrorHandler<br/>错误处理"]
    end

    subgraph Core["核心服务"]
        RBAC["RBAC<br/>权限校验"]
        Audit["AuditLogger<br/>审计日志"]
        Ctx["ContextBuilder<br/>上下文构建"]
    end

    subgraph External["外部能力"]
        LLM["LLM Provider<br/>OpenAI / DeepSeek / Ollama"]
    end

    subgraph Storage["cos:// 公司文件系统"]
        FS[("YAML / Markdown / JSONL")]
        Git[("Git 版本历史")]
    end

    Admin --> CLI
    CLI --- CLI_Sub
    CLI_Sub --> FS

    CLI --> AgentRun
    AgentRun -->|Think| LLM
    AgentRun -->|Act: shell| CLI
    AgentRun -->|Act: file_*| FS
    AgentRun --> RBAC & Audit & Ctx & EH

    Cron & Watch & Invoke --> EQ
    EQ --> Scheduler
    Scheduler --> LM & Slots
    Scheduler --> Executor

    Executor -->|Think| LLM
    Executor -->|Act: shell| CLI
    Executor -->|Act: file_*| FS
    Executor --> RBAC & Audit & Ctx & EH

    FS <--> Git

    style Human fill:#e8f5e9,stroke:#388e3c
    style Storage fill:#e3f2fd,stroke:#1565c0
    style External fill:#fff3e0,stroke:#ef6c00
Loading

数据流概览

graph LR
    subgraph Input["输入"]
        T1["⏰ 定时触发"]
        T2["📁 文件变更"]
        T3["🔔 手动调用"]
    end

    subgraph Pipeline["调度管道"]
        EQ["EventQueue<br/>去重 · 优先级 · 防饥饿"]
        DL["DispatchLoop<br/>状态检查 · 槽位获取"]
    end

    subgraph Execution["执行引擎"]
        Loop["Think → Act → Observe → Check"]
    end

    subgraph Output["输出"]
        Files["文件变更"]
        Commits["Git 提交"]
        Logs["审计日志"]
        Signals["控制信号"]
    end

    T1 & T2 & T3 --> EQ --> DL --> Loop --> Files & Commits & Logs & Signals
Loading

快速开始

前置要求

  • Go 1.23+
  • Git
  • LLM API Key(OpenAI / DeepSeek / Ollama 等 OpenAI 兼容接口)

构建

git clone <repo-url> && cd cos
make build

构建产物:

  • bin/cos — CLI 工具(人类管理员 + Agent 共用,含 cos agent run 执行引擎)
  • bin/cosd — 守护进程(start 调度守护 / status 状态查看)

初始化公司

./bin/cos init --name="My Company"

这会在 ./company/ 下创建完整的公司目录结构,并自动创建内置的 CEO Agent 实例(ID: ceo):

company/
├── AGENTS.md                          # Agent 操作手册
├── charter.md                         # 公司章程
├── config.yaml                        # 全局配置(LLM、预算、调度器等)
├── organization/
│   ├── roles/                         # 角色定义
│   │   ├── base.yaml                  #   基础角色(所有角色继承)
│   │   ├── ceo.yaml                   #   CEO 角色(人类与 Agent 的桥梁)
│   │   ├── developer.yaml             #   开发者角色
│   │   ├── pm.yaml                    #   项目经理角色
│   │   ├── qa.yaml                    #   QA 角色
│   │   └── reviewer.yaml              #   代码审查角色
│   ├── agents/                        # Agent 实例(YAML 文件)
│   └── structure.yaml                 # 组织架构
├── projects/                          # 项目目录
├── tasks/                             # 任务目录
├── communications/
│   ├── inbox/                         # Agent 收件箱
│   ├── outbox/                        # Agent 发件箱
│   └── reviews/                       # 审批/Review 请求
├── meetings/                          # 会议记录
├── knowledge/                         # 知识库
├── skills/                            # Skill 文档
│   ├── _index.yaml                    #   Skill 索引
│   └── cos/                           #   cos CLI Skill 文档
│       ├── SKILL.md                   #     总览
│       ├── agent.md, task.md, ...     #     各子命令文档
├── runtime/
│   ├── memory/                        # Agent 记忆
│   │   └── global/                    #   全局记忆
│   ├── logs/
│   │   ├── agents/                    #   Agent 审计日志
│   │   └── system/                    #   系统日志
│   └── grants/                        # 临时权限授予
└── .cos/
    └── id-counter.yaml                # 内部状态(ID 自增计数器)

配置 LLM

使用 cos config setup-llm 一键配置 LLM 提供商:

# OpenAI(默认)
./bin/cos config setup-llm --provider=openai
export OPENAI_API_KEY=sk-your-key-here

# DeepSeek
./bin/cos config setup-llm --provider=deepseek
export DEEPSEEK_API_KEY=your-key

# Ollama(本地)
./bin/cos config setup-llm --provider=ollama
export OLLAMA_API_KEY=any-value

# 自定义模型和参数
./bin/cos config setup-llm --provider=openai --model=gpt-4o-mini --temperature=0.5

也可以逐项修改:

cos config set model gpt-4o-mini
cos config set base_url https://api.openai.com/v1
cos config set temperature 0.5
cos config set max_steps 100

查看当前配置:

cos config view                  # 全部配置
cos config view --section=llm    # 仅 LLM 配置
cos config view --section=budget # 仅预算配置

CLI 命令参考

所有命令支持 --root 指定公司目录(默认 ./company),--agent 指定当前 Agent ID,--format 控制输出格式(text | brief)。

配置管理

# 一键配置 LLM(支持预设:openai | deepseek | ollama)
cos config setup-llm --provider=deepseek
cos config setup-llm --provider=openai --model=gpt-4o-mini --temperature=0.3

# 逐项设置
cos config set model gpt-4o
cos config set max_steps 100
cos config set company.name "New Name"

# 查看配置
cos config view                   # 全部
cos config view --section=llm     # 仅 LLM
cos config view --section=budget  # 仅预算

项目管理

# 创建项目
cos project create --slug=webapp --name="Web App" --workspace=~/projects/webapp

# 用自然语言创建(LLM 推断参数 + 组建团队 + 生成工作流)
cos project create --prompt="电商网站项目,需要2个后端开发和1个QA" --workspace=~/projects/shop

# 列出 / 查看项目
cos project list
cos project info webapp

# 管理成员
cos project add-member webapp agent-001
cos project remove-member webapp agent-001

工作流管理

# 初始化工作流(写入 {workspace}/WORKFLOW.md)
cos workflow init webapp                          # 默认 dev 模板
cos workflow init webapp --template=simple
cos workflow init webapp --template=custom

# 查看 / 编辑
cos workflow show webapp
cos workflow edit webapp                          # 输出文件路径

Agent 管理

# 创建 Agent
cos agent create --role=developer --name="Dev-1"
cos agent create --role=ceo --name="CEO" --activate

# 用自然语言创建(LLM 自动推断角色和名称)
cos agent create --prompt="创建一个专注前端的QA" --activate

# 查看 Agent 详情
cos agent info agent-001

# 列出所有 Agent
cos agent list
cos agent list --role=developer

# 激活 Agent(created/suspended → active)
cos agent activate agent-001

# 运行 Agent 会话(同步,阻塞直到完成)
cos agent run agent-001

# 异步运行(后台执行,立即返回)
cos agent run agent-001 --async

# 恢复中断的会话
cos agent run agent-001 --resume=<session-id>

# 向运行中的 Agent 发送中断
cos agent interrupt agent-001 --message="请优先处理 bug-123"
cos agent interrupt agent-001 --type=hard   # 立即终止会话

会话管理

# 列出 Agent 的会话
cos session list --agent=agent-001

# 查看会话详情
cos session info <session-id>

# 等待会话完成(阻塞)
cos session wait --agent=agent-001
cos session wait <ses-1> <ses-2> --any    # 任一完成即返回

# 删除会话
cos session delete <session-id>

任务管理

# 创建任务(Kanban 模型,自由列名)
cos task create --project=alpha --title="实现用户登录" --assignee=agent-001 --priority=high
cos task create --title="每日站会" --column=ready --schedule="0 9 * * *"   # 定时循环任务

# 列出任务
cos task list                              # 所有任务
cos task list --assignee=agent-001         # 按负责人过滤
cos task list --column=in_progress         # 按列过滤
cos task list --blocked                    # 仅被阻塞的任务

# 看板视图
cos task board
cos task board --project=alpha

# 查看任务详情 / 活动日志
cos task info task-001
cos task log task-001

# 移动任务到指定列
cos task move task-001 in_progress
cos task move task-001 review --assignee=agent-002

# 自助领取 / 自动领取最高优先级任务
cos task claim task-001
cos task pick --project=alpha

# 释放任务(清除负责人)
cos task release task-001

# 阻塞 / 解除阻塞
cos task block task-001 --reason="等待 API 文档"
cos task unblock task-001

# 记录交付物
cos task deliver task-001 --branch=feat/login --pr=https://...

# 归档 / 评论
cos task archive task-001 --reason="已废弃"
cos task comment task-001 --body="已完成核心逻辑,等待测试"

Kanban 列完全自由定义,常见流转:backlog → ready → in_progress → review → done

项目管理

# 创建项目(手动)
cos project create --slug=webapp --name="Web App" --workspace=~/projects/webapp

# 用自然语言创建(LLM 自动推断参数、组建团队、生成工作流)
cos project create --prompt="电商网站项目,需要2个后端开发和1个QA"
cos project create --prompt="mobile app" --slug=mobile --workspace=~/projects/mobile

# 列出项目
cos project list

# 查看项目详情
cos project info webapp

# 管理项目成员
cos project add-member webapp agent-001
cos project remove-member webapp agent-001

--prompt 模式下,LLM 会自动:

  • 推断项目名称、描述、slug
  • 根据项目需求组建团队(优先复用空闲 Agent,不足时自动创建)
  • 选择最合适的工作流模板(或生成自定义工作流)写入 {workspace}/WORKFLOW.md

工作流管理

工作流定义项目的协作流程,存放在项目 workspace 目录下的 WORKFLOW.md

# 从模板初始化工作流
cos workflow init webapp                          # 默认 dev 模板
cos workflow init webapp --template=simple        # 简单流程
cos workflow init webapp --template=custom        # 空骨架

# 查看工作流(Agent 在开始工作前应调用此命令)
cos workflow show webapp

# 获取工作流文件路径(用于编辑)
cos workflow edit webapp

内置模板(templates/workflow_templates/*.md,可扩展):

  • dev — 标准开发流程(requirements → design → planning → development → review → testing → done)
  • simple — 简单流程(planning → execution → review → done)
  • custom — 空骨架

工作流阶段名括号中的标识符对应 Kanban 列名,使用 cos task move <task-id> <列名> 推进任务。

消息系统

# 发送消息
cos msg send --to=agent-001 --subject="请处理紧急 bug" --body="详情见 task-003" --priority=urgent

# 查看收件箱
cos --agent=agent-001 msg inbox              # 全部消息
cos --agent=agent-001 msg inbox --unread     # 仅未读

# 阅读消息(自动标记已读)
cos --agent=agent-001 msg read message-001

# 归档消息
cos --agent=agent-001 msg archive message-001

Agent 记忆

# 添加记忆
cos --agent=agent-001 memory add --content="项目 alpha 使用 React + TypeScript" --type=fact --weight=0.9

# 加载记忆
cos --agent=agent-001 memory load --limit=10

记忆类型:learned | preference | fact | mistake | relationship

ID 生成

# 生成下一个 ID(原子操作,带文件锁)
cos id next --type=task     # → task-001
cos id next --type=agent    # → agent-002

初始化

# 初始化新公司
cos init --name="Acme Corp" --timezone="Asia/Shanghai"

运行 Agent

方式一:手动触发(单次会话)

# 同步运行(阻塞直到完成)
./bin/cos agent run agent-001

# 异步运行(后台执行,立即返回)
./bin/cos agent run agent-001 --async

# 恢复中断/超预算的会话
./bin/cos agent run agent-001 --resume=<session-id>

方式二:Scheduler 守护进程(自动调度)

# 启动调度器,Agent 将根据触发器自动唤醒
./bin/cosd start --root=company

# 查看当前 Agent 和调度状态
./bin/cosd status --root=company

Scheduler 根据角色中定义的触发器自动调度 Agent:

触发类型 说明 默认优先级 配置示例
cron 定时执行 Low (1) schedule: "*/30 * * * *"
file_watch 文件变更时执行 Normal (2) paths: ["cos://communications/inbox/{self}/**"]
invoke 手动/程序触发 High (3) 通过 cos agent invoke 或 Agent 间消息
task_cron 定时循环任务 Normal (2) 任务 --schedule="0 9 * * *" 自动触发

Scheduler 调度管道

graph LR
    subgraph Sources["触发源"]
        CS["⏰ CronSource<br/><i>robfig/cron</i>"]
        WS["📁 WatchSource<br/><i>fsnotify + debounce</i>"]
        IS["🔔 InvokeSource<br/><i>API + 文件轮询</i>"]
    end

    subgraph Queue["事件队列"]
        EQ["EventQueue<br/>优先级排序 · 去重合并<br/>防饥饿提升 · 容量监控"]
    end

    subgraph Dispatch["调度循环"]
        DL["DispatchLoop"]
        LM["LifecycleManager<br/>状态校验"]
        SM["SlotManager<br/>并发控制"]
    end

    subgraph Exec["执行"]
        EX["Executor.Run()"]
        RE["Executor.Resume()"]
    end

    CS & WS & IS -->|Enqueue| EQ
    EQ -->|Pop| DL
    DL --> LM -->|"active?"| SM
    SM -->|"获取槽位"| EX & RE

    EX & RE -->|"完成/错误"| DL
    DL -->|"释放槽位"| SM
Loading

Scheduler 特性:

  • 事件优先级队列:urgent > high > normal > low,同优先级先到先服务
  • 事件去重合并:同一 Agent 在队列中最多 1 个待处理事件
  • 并发槽位控制:限制总并发和每角色并发 Agent 数
  • 防饥饿机制:长时间未执行的事件自动优先级提升
  • 启动恢复:自动修复上次崩溃遗留的 stale working 状态
  • 队列压力监控:队列使用率超过 80% 时告警

Agent 生命周期状态机

stateDiagram-v2
    [*] --> created : cos agent create
    created --> active : cos agent activate / --activate
    created --> terminated : terminate

    active --> working : Scheduler dispatch
    active --> suspended : manual suspend
    active --> terminated : terminate

    working --> active : 会话正常结束
    working --> suspended : 错误 / 中断 / 超预算
    working --> terminated : terminate

    suspended --> active : cos agent activate / 自动恢复
    suspended --> terminated : terminate

    terminated --> [*]

    note right of working
        Executor 运行中
        占用一个并发槽位
    end note

    note right of suspended
        可通过 Resume 恢复
        保留会话快照
    end note
Loading

Agent 执行循环

Agent 被唤醒后自动执行 Think-Act-Observe-Check 循环:

flowchart TD
    Start([会话开始]) --> Load["加载 Agent & Role"]
    Load --> BuildCtx["构建 LLM 上下文<br/><i>系统提示 + Skills + 记忆 + 收件箱 + 任务</i>"]
    BuildCtx --> Loop

    subgraph Loop["主循环(每步)"]
        direction TB
        IntChk{"🛑 中断检查"}
        IntChk -->|Hard 中断| Interrupted([中断退出])
        IntChk -->|Soft 中断| InjectCtx["注入中断上下文"] --> Think
        IntChk -->|无中断| Think

        Think["🧠 Think<br/>压缩历史 → 调用 LLM"]
        Think -->|纯文本回复| Checkpoint1["💾 Checkpoint"]
        Think -->|工具调用| Act

        Act["⚡ Act<br/>逐个执行工具调用"]

        Act --> Observe["👁 Observe<br/>收集执行结果"]
        Observe --> Checkpoint2["💾 Checkpoint<br/>持久化会话"]
        Checkpoint2 --> Check

        Check{"✅ Check"}
        Check -->|"signal: done/blocked"| Completed([正常结束])
        Check -->|预算耗尽| BudgetEx([超预算<br/><i>可 Resume</i>])
        Check -->|继续| IntChk
    end

    Checkpoint1 --> Check

    style Think fill:#e8eaf6,stroke:#3f51b5
    style Act fill:#fff3e0,stroke:#ef6c00
    style Observe fill:#e8f5e9,stroke:#388e3c
    style Check fill:#fce4ec,stroke:#c62828
Loading

5 个原子工具:

工具 说明 RBAC
shell 执行 shell 命令(cos CLI、git 等) CLI 权限校验
file_read 读取文件内容 文件读权限校验
file_write 创建/覆盖文件(公司文件自动 Git 提交) 文件写权限校验
file_edit 搜索替换编辑文件 文件写权限校验
signal 控制信号:done / blocked / pause / need-help 无需校验

会话持久化与恢复:

sequenceDiagram
    participant E as Executor
    participant SS as SessionStore
    participant FS as File System

    Note over E: 新会话
    E->>E: Run(agentID)
    loop 每步结束
        E->>SS: Save(session) — Checkpoint
        SS->>FS: runtime/sessions/{agentID}/{sessionID}.json
    end

    Note over E: 中断或超预算
    E-->>SS: Save(session) — Final

    Note over E: 恢复会话
    E->>SS: Load(sessionID)
    SS->>FS: 读取快照
    SS-->>E: 完整历史 + 状态
    E->>E: Resume(sessionID)
    E->>E: 压缩历史 · 注入恢复提示 · 继续循环
Loading

配置

config.yaml 中配置会话预算和调度器:

budget:
  max_steps: 50              # 最大步数
  max_tokens: 200000         # 最大 token 数
  max_duration_seconds: 600  # 最大时长(秒)
  reserve_tokens: 4096       # 预留 token

scheduler:
  max_concurrent_agents: 3        # 最大并发 Agent 数
  max_concurrent_per_role:        # 每角色并发限制
    developer: 2
  slot_timeout_seconds: 3600      # 执行超时(秒)
  max_queue_size: 100             # 事件队列最大长度
  dedup_window_seconds: 5         # 去重窗口
  starvation_hours: 2             # 饥饿防护阈值(小时)
  file_watch:
    debounce_ms: 500              # 文件变更防抖(毫秒)
    ignore_patterns: ["*.tmp", ".git/**"]

完整示例

# 1. 构建
make build

# 2. 初始化公司(自动创建内置 CEO Agent)
./bin/cos init --name="Startup Inc"

# 3. 配置 LLM
./bin/cos config setup-llm --provider=openai
export OPENAI_API_KEY=sk-your-key

# 4a. 用自然语言一键创建项目(自动组建团队 + 生成工作流)
./bin/cos project create --prompt="电商网站,需要前后端开发和QA" --workspace=~/projects/ecommerce

# 4b. 或手动创建项目和团队
./bin/cos project create --slug=webapp --name="Web App" --workspace=~/projects/webapp
./bin/cos agent create --role=developer --name="Dev-1" --activate
./bin/cos agent create --role=reviewer --name="Reviewer-1" --activate
./bin/cos agent create --role=qa --name="QA-1" --activate
./bin/cos project add-member webapp agent-001
./bin/cos project add-member webapp agent-002
./bin/cos project add-member webapp agent-003
./bin/cos workflow init webapp                    # 初始化工作流

# 5. 创建任务
./bin/cos task create --project=webapp --title="实现 hello world API" --column=ready --priority=high

# 6a. CEO 模式:向 CEO 发送指令,CEO 自动分解任务并调度其他 Agent
./bin/cos msg send --to=ceo --subject="请完成 webapp 项目" --body="实现 hello world API 并编写测试"
./bin/cos agent run ceo                           # CEO 会自动 dispatch 其他 Agent

# 6b. 直接运行:手动运行指定 Agent
./bin/cos agent run agent-001                     # 同步运行
./bin/cos agent run agent-001 --async             # 异步运行,立即返回
./bin/cos session wait --agent=agent-001          # 等待 Agent 完成

# 6c. Scheduler 模式:Agent 根据触发器自动唤醒
./bin/cosd start
./bin/cosd status

# 7. 查看结果
./bin/cos task board                              # 看板视图
./bin/cos task info task-001
./bin/cos workflow show webapp                    # 查看工作流
./bin/cos session list --agent=agent-001          # 查看会话历史
./bin/cos --agent=agent-001 memory load

权限系统(RBAC)

采用 deny-first 模型。每个 Agent 的权限由其角色(organization/roles/*.yaml)定义:

permissions:
  files:
    read:  ["cos://projects/**"]
    write: ["cos://projects/{assigned}/**"]
    deny:  ["cos://.cos/**"]
  cli:
    allow: ["cos task *", "cos msg *", "git *"]
    deny:  ["git push * main", "cos agent terminate *"]
  messages:
    can_send_to: ["tech-lead", "pm", "developer"]

权限校验流程

flowchart TD
    Req(["权限请求<br/>文件 / CLI / 消息"]) --> Admin{"人类管理员?"}
    Admin -->|是| ALLOW([✅ Allow])
    Admin -->|否| Bypass{"Bypass 标记?"}
    Bypass -->|是| ALLOW
    Bypass -->|否| DenyChk{"命中 Deny 规则?<br/><i>doublestar 匹配</i>"}
    DenyChk -->|是| DENY([🚫 Deny])
    DenyChk -->|否| ApprovalChk{"需要审批?<br/><i>仅 CLI</i>"}
    ApprovalChk -->|是| APPROVAL([⏳ Approval Required])
    ApprovalChk -->|否| AllowChk{"命中 Allow 规则?"}
    AllowChk -->|是| ALLOW
    AllowChk -->|否| Workspace{"在项目工作区内?<br/><i>仅文件操作</i>"}
    Workspace -->|是| ALLOW
    Workspace -->|否| External{"外部路径?"}
    External -->|是| APPROVAL
    External -->|否| DENY

    style ALLOW fill:#c8e6c9,stroke:#2e7d32
    style DENY fill:#ffcdd2,stroke:#c62828
    style APPROVAL fill:#fff9c4,stroke:#f9a825
Loading

校验优先级:Deny > Approval Required > Allow > 项目工作区 > Default Deny


测试

# 运行所有测试
make test

# 仅运行单元测试(快速)
make test-unit

测试分层策略:

  • 单元测试 — mock 所有外部依赖,测试纯逻辑
  • 集成测试 — 基于 t.TempDir() 的真实文件操作,无 LLM/Git
  • Executor 循环测试 — MockLLM + FakeRunner 验证完整工作循环
  • CLI 端到端测试 — 构造 TestApp + 执行 cobra 命令验证输入输出

项目结构

cos/
├── cmd/
│   ├── cos/main.go              # CLI 入口
│   └── cosd/main.go             # 守护进程入口
├── internal/
│   ├── model/                   # 数据模型(Agent, Task, Message, ...)
│   ├── store/                   # 文件系统存储层(Store 接口 + FileStore)
│   ├── rbac/                    # 权限校验(PermissionChecker 接口)
│   ├── audit/                   # 审计日志(AuditLogger 接口)
│   ├── cli/                     # CLI 命令实现 + App 服务容器
│   ├── testutil/                # 测试工具集(mock, fixture)
│   └── runtime/
│       ├── executor/            # 核心执行引擎(Think-Act-Observe-Check)
│       ├── scheduler/           # 调度器(触发源→事件队列→并发调度→执行器)
│       ├── context/             # LLM 上下文构建器
│       ├── lifecycle/           # Agent 生命周期状态机
│       └── errorhandler/        # 错误处理与重试
├── pkg/
│   └── llm/                     # LLM Provider 接口 + OpenAI 实现
├── docs/                        # 设计文档
├── go.mod
├── Makefile
└── README.md

核心接口

所有模块遵循接口驱动 + 依赖注入,确保可独立测试:

接口 说明
Store internal/store 文件系统读写
PermissionChecker internal/rbac 权限校验
AuditLogger internal/audit 审计日志
LifecycleManager internal/runtime/lifecycle Agent 状态机
Scheduler internal/runtime/scheduler Agent 调度(触发、排队、并发控制)
ErrorHandler internal/runtime/errorhandler 错误处理
ContextBuilder internal/runtime/context LLM 上下文构建
CommandRunner internal/runtime/executor Shell 命令执行
SessionStore internal/runtime/executor 会话持久化
Provider pkg/llm LLM 调用

依赖关系

graph TD
    cmd_cos["cmd/cos"] --> cli["internal/cli"]
    cmd_cosd["cmd/cosd"] --> scheduler["runtime/scheduler"]
    cmd_cosd --> executor["runtime/executor"]

    cli --> store["internal/store"]
    cli --> rbac["internal/rbac"]
    cli --> audit["internal/audit"]

    scheduler --> executor
    scheduler --> lifecycle["runtime/lifecycle"]
    scheduler --> event["EventQueue + SlotManager"]

    executor --> llm["pkg/llm"]
    executor --> store
    executor --> rbac
    executor --> audit
    executor --> context["runtime/context"]
    executor --> errorhandler["runtime/errorhandler"]

    store --> templates["templates (embed.FS)"]
    context --> store

    model["internal/model"] -.->|"被所有包导入"| store & rbac & audit & cli & executor & scheduler

    style model fill:#f3e5f5,stroke:#7b1fa2
    style llm fill:#fff3e0,stroke:#ef6c00
    style store fill:#e3f2fd,stroke:#1565c0
Loading

技术栈

License

MIT

About

Company OS

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages