GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - liujilongObject/mini-coding-agent: A minimalist coding agent implemented in TypeScript, providing insights into the core architecture and implementation logic of a general coding agent.

BranchesTags
Open more actions menu

Latest commit

 

History

2 Commits
2 Commits

Folders and files

NameName
Last commit message
Last commit date
commands
commands
 
 
src
src
 
 
test
test
 
 
.env.example
.env.example
 
 
.gitignore
.gitignore
 
 
.oxfmtrc.json
.oxfmtrc.json
 
 
README.md
README.md
 
 
package.json
package.json
 
 
pnpm-lock.yaml
pnpm-lock.yaml
 
 
tsconfig.json
tsconfig.json
 
 
tsdown.config.ts
tsdown.config.ts
 
 

Repository files navigation

Mini Coding Agent

一个用 TypeScript 实现的极简 Coding Agent,可供开发者学习和理解通用 Coding Agent 的核心架构与实现逻辑。


目录

  • 项目简介
  • 架构总览
  • 核心概念
    • 主 Agent 循环
    • 工具系统
    • 上下文压缩
    • Todo 与任务管理
    • 子 Agent 与 Teammate
    • 消息总线
    • 技能系统
  • 目录结构
  • 模块说明
  • 运行时流程
  • 快速上手

项目简介

本项目以最精简的代码展示一个具备以下能力的 Coding Agent 是如何构建的:

  • 工具调用循环:LLM 自主决策 → 调用工具 → 处理结果 → 继续决策
  • 上下文管理:自动检测上下文长度并进行压缩,避免超出模型限制
  • 多 Agent 协作:支持 Subagent(临时子任务)和 Teammate(长期自治协作者)
  • 持久化任务板:跨会话的任务管理,支持依赖关系和认领机制
  • 后台任务执行:非阻塞地执行耗时命令,完成后通知主循环
  • 技能系统:通过 Markdown 文件定义可复用的行为指令

架构总览

┌─────────────────────────────────────────────────┐
│                  index.ts (REPL)                │
│  用户输入 / 内置命令 (/compact /tasks /team ...)  │
└────────────────────┬────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────┐
│              agent.ts (主 Agent 循环)            │
│                                                 │
│  ┌──────────┐  ┌──────────┐  ┌───────────────┐ │
│  │ 压缩检查 │  │ 后台通知 │  │  收件箱消息   │ │
│  └──────────┘  └──────────┘  └───────────────┘ │
│                     │                           │
│            调用 LLM(@mariozechner/pi-ai)        │
│                     │                           │
│         解析 toolCall → 执行工具                 │
└──────┬──────────┬───────────┬───────────────────┘
       │          │           │
       ▼          ▼           ▼
  tools.ts   subagent.ts  teammate.ts
 (bash/文件)  (临时子Agent) (长期协作者)
       │                      │
       ▼                      ▼
  taskManager.ts         messageBus.ts
   (任务看板)              (文件邮箱)

核心概念

主 Agent 循环

文件:src/agent.ts

主循环是整个系统的核心,采用经典的 ReAct 模式(推理 + 行动交替):

每一轮迭代:
1. microcompact()        ← 轻量清理旧工具输出
2. 检查上下文大小
   └─ > 100k tokens → autoCompact() 压缩并归档
3. 注入后台任务完成通知
4. 注入收件箱新消息
5. 调用 LLM(@mariozechner/pi-ai complete())
6. 输出本轮 token 用量(in / out / total)
7. 响应中无 toolCall 内容块 → 返回最终回答
8. 响应中有 toolCall → 执行所有工具 → 回到步骤 1

Todo 提醒机制:若有未完成的 Todo,且模型连续 3 轮没有调用 TodoWrite,自动注入提醒消息。


工具系统

文件:src/tools.ts、src/agent.ts

工具分两层定义:

层级 描述
Schema 层(TOOLS) 用 JSON Schema 向 LLM 描述每个工具的名称、参数和功能
执行层(TOOL_HANDLERS) 将工具名映射到实际处理函数

内置工具一览:

工具 功能
bash 执行 Shell 命令(带超时和危险命令拦截)
read_file 读取文件内容(可限制行数)
write_file 写入文件(自动创建目录)
edit_file 精确字符串替换编辑
background_run 后台非阻塞执行命令
check_background 查询后台任务状态
task 委派任务给 Subagent
spawn_teammate 创建长期自治协作者
list_teammates 列出所有 Teammate 状态
send_message 向 Teammate 发送消息
read_inbox 读取并清空主 Agent 收件箱
broadcast 广播消息给所有 Teammate
task_create 在任务看板上创建任务
task_get 获取任务详情
task_update 更新任务状态/依赖
task_list 列出所有任务
claim_task 认领一个任务
load_skill 加载指定技能的详细指令
TodoWrite 更新当前执行的 Todo 列表
compress 手动触发上下文压缩

安全边界:所有文件操作通过 safePath() 限制在 WORKDIR 目录内;bash 工具会拦截 rm -rf /、sudo 等危险命令。


上下文压缩

文件:src/compression.ts

两级压缩策略,平衡效率与成本:

Level 1 - microcompact(每轮自动,极低成本)
  └─ 保留最新 3 条工具输出,其余超过 100 字符的内容替换为 [cleared]

Level 2 - autoCompact(触发条件:tokens > 100k,或手动 /compact)
  ├─ 将完整对话归档为 .transcripts/transcript_<时间戳>.jsonl
  ├─ 取最近 80k 字符生成摘要(调用 LLM,max_tokens=2000)
  └─ 将对话历史重置为单条摘要消息,保持对话连续性

归档的 transcript 文件确保历史可追溯,即使发生压缩也不丢失。


Todo 与任务管理

项目有两套独立的任务追踪机制,各司其职:

Todo(短期执行清单)

文件:src/todo.ts

  • 存储:纯内存,会话结束即消失
  • 用途:追踪当前任务的执行步骤,引导模型行为
  • 约束:最多 20 条;同时只能有 1 条 in_progress;每条需有 content(待办形式)和 activeForm(进行形式)

任务看板(跨会话持久化)

文件:src/taskManager.ts

  • 存储:文件系统 .tasks/task_<id>.json
  • 用途:团队协作的持久化工作项,支持依赖关系
  • 状态:pending → in_progress → completed / deleted
  • 阻塞关系:通过 blockedBy 数组表达依赖,任务完成时自动从其他任务的 blockedBy 中移除
[ ] task_1: 实现登录接口
[>] task_2: 编写单元测试(blockedBy: [])
[x] task_3: 初始化项目结构

子 Agent 与 Teammate

项目支持两种"分身"模式:

Subagent(临时子 Agent)

文件:src/subagent.ts

特点:
- 短生命周期,同步执行(await 等待结果)
- 独立对话历史,不共享主 Agent 上下文
- 最多 30 轮工具调用
- 两种模式:
  - Explore:只读权限(bash + read_file)
  - general-purpose:读写权限(+ write_file + edit_file)
- 返回最终文本摘要给主 Agent

Teammate(长期自治协作者)

文件:src/teammate.ts

特点:
- 长生命周期,异步运行(setImmediate 启动,不阻塞主 Agent)
- 状态持久化至 .team/config.json
- 生命周期:working → idle → shutdown
  - working:最多 50 轮,每轮检查收件箱
  - idle:轮询收件箱(每 5 秒),60 秒无消息后自动 shutdown
- 额外工具:send_message / idle / claim_task
- 支持接收 shutdown 信号优雅退出

消息总线

文件:src/messageBus.ts

基于文件系统的异步消息传递,实现主 Agent 与 Teammate 之间的松耦合通信:

存储路径:.team/inbox/<接收方名称>.jsonl
          每条消息是一行 JSON

消息类型:
  message                  ← 普通点对点消息
  broadcast                ← 广播(自动排除发送者)
  shutdown_request         ← 请求 Teammate 关闭
  shutdown_response        ← Teammate 确认关闭
  plan_approval_response   ← 计划审批回复

投递语义:追加写入 / 读取即清空(drain,不重复消费)

技能系统

文件:src/skills.ts

技能是存储在 skills/**/SKILL.md 中的 Markdown 文件,前置 YAML Frontmatter 定义元数据:

---
name: my-skill
description: 这个技能用于...
---

# 技能详细指令

当需要 X 时,按以下步骤执行...
  • 启动时自动扫描并加载所有技能,描述列表注入系统提示
  • 模型通过 load_skill 工具按需获取完整指令内容
  • 技能名默认取父目录名,可通过 frontmatter 覆盖

目录结构

mini-coding-agent/
├── src/
│   ├── index.ts          # CLI REPL 入口
│   ├── agent.ts          # 主 Agent 循环、工具定义与调度
│   ├── tools.ts          # 工具底层实现(bash/文件操作)
│   ├── compression.ts    # 上下文压缩(microcompact / autoCompact)
│   ├── subagent.ts       # 临时子 Agent 执行器
│   ├── teammate.ts       # 长期自治协作者
│   ├── messageBus.ts     # 文件邮箱消息总线
│   ├── taskManager.ts    # 持久化任务看板
│   ├── todo.ts           # 内存 Todo 管理器
│   ├── skills.ts         # 技能加载与解析
│   ├── background.ts     # 后台命令执行
│   └── config.ts         # 全局配置与 Anthropic 客户端
├── skills/               # 技能 Markdown 文件目录
├── .tasks/               # 持久化任务文件(运行时生成)
├── .team/                # Teammate 配置与收件箱(运行时生成)
│   ├── config.json
│   └── inbox/
├── .transcripts/         # 压缩前的对话归档(运行时生成)
└── .env                  # 环境变量配置

模块说明

模块 职责
config.ts 环境变量加载、路径常量、pi-ai 模型配置
index.ts 用户交互 REPL,解析内置命令,驱动主循环
agent.ts 核心编排器:系统提示、工具注册、主循环
tools.ts 安全的 bash/文件工具实现,被所有 Agent 共用
compression.ts 两级上下文压缩,含 transcript 归档
subagent.ts 隔离的短期子任务执行环境
teammate.ts 异步长期协作者,含 work/idle/shutdown 状态机
messageBus.ts 基于文件的异步消息投递与收取
taskManager.ts 持久化任务看板,支持依赖图和状态流转
todo.ts 内存执行清单,带验证和进度渲染
skills.ts 技能文件扫描、解析、按需加载
background.ts 非阻塞后台命令、状态追踪、通知队列

运行时流程

以一次完整的用户请求为例:

用户输入:"帮我重构 utils.ts 文件"
         │
         ▼
index.ts 推入 history,调用 agentLoop()
         │
         ▼
agent.ts 主循环
  │
  ├─ [预处理] microcompact → 检查 tokens → 注入通知/收件箱
  │
  ├─ [LLM 调用] 模型思考,决定先 read_file 读取文件
  │
  ├─ [工具执行] 执行 read_file,返回文件内容
  │
  ├─ [LLM 调用] 模型分析内容,决定 TodoWrite 记录步骤
  │
  ├─ [工具执行] 更新 Todo 列表
  │
  ├─ [LLM 调用] 模型决定 edit_file 进行重构
  │
  ├─ [工具执行] 执行编辑操作
  │
  ├─ [LLM 调用] 模型决定 bash 运行测试验证结果
  │
  ├─ [工具执行] 执行测试命令
  │
  ├─ [Token 输出] 打印本轮 in/out/total token 用量
  │
  └─ [LLM 调用] 无 toolCall 内容块 → 返回最终回答
         │
         ▼
index.ts 打印输出,等待下一次用户输入

快速上手

1. 安装依赖

pnpm install

2. 配置环境变量

cp .env.example .env

编辑 .env:

# 1. 使用 Anthropic 官方 API
MODEL_PROVIDER=anthropic
MODEL_ID=claude-sonnet-4-5
MODEL_API_KEY=your_anthropic_api_key
# MODEL_BASE_URL=  # 可选,自定义 API 地址

# 或 2. 使用 OpenRouter 兼容格式
# MODEL_PROVIDER=openrouter
# MODEL_ID=google/gemini-2.5-pro
# MODEL_API_KEY=your_openrouter_api_key
# MODEL_BASE_URL=

3. 启动

pnpm run start

4. 内置命令

在 REPL 中可使用以下命令:

命令 说明
/help 查看帮助文档
/compact 手动压缩对话上下文
/tasks 查看任务看板
/team 查看 Teammate 状态
/inbox 查看并清空主 Agent 收件箱
q / exit 退出

About

A minimalist coding agent implemented in TypeScript, providing insights into the core architecture and implementation logic of a general coding agent.

Resources

Readme
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.