feat: implement full agent-team platform
Go backend: - LLM client with DeepSeek/Kimi/Ollama/OpenAI support (OpenAI-compat) - Agent loader: AGENT.md frontmatter, SOUL.md, memory read/write - Skill system following agentskills.io standard - Room orchestration: master assign→execute→review loop with streaming - Hub: GitHub repo clone and team package install - Echo HTTP server with WebSocket and full REST API React frontend: - Discord-style 3-panel layout with Tailwind v4 - Zustand store with WebSocket streaming message handling - Chat view: streaming messages, role styles, right panel, drawer buttons - Agent MD editor with Monaco Editor (AGENT.md + SOUL.md) - Market page for GitHub team install/publish Docs: - plan.md with full progress tracking and next steps Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
21a7cf0b4e
commit
de773586c7
13
.claude/settings.local.json
Normal file
13
.claude/settings.local.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"WebFetch(domain:github.com)",
|
||||
"WebFetch(domain:support.claude.com)",
|
||||
"Bash(git:*)",
|
||||
"Bash(go:*)",
|
||||
"Bash(npm create:*)",
|
||||
"Bash(npm install:*)",
|
||||
"Bash(node:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
8
agents/example-master/AGENT.md
Normal file
8
agents/example-master/AGENT.md
Normal file
@ -0,0 +1,8 @@
|
||||
---
|
||||
name: example-master
|
||||
description: 示例 master agent,负责任务拆分和团队协调
|
||||
provider: deepseek
|
||||
model: deepseek-chat
|
||||
api_key_env: DEEPSEEK_API_KEY
|
||||
skills: []
|
||||
---
|
||||
7
agents/example-master/SOUL.md
Normal file
7
agents/example-master/SOUL.md
Normal file
@ -0,0 +1,7 @@
|
||||
你是一个经验丰富的团队 master,负责理解用户需求、拆分任务、分配给团队成员,并对结果进行审核。
|
||||
|
||||
工作原则:
|
||||
- 收到任务后先分析,制定清晰的执行计划
|
||||
- 根据团队成员的能力合理分配任务
|
||||
- 对成员的输出进行严格审核,不满意则提出具体修改意见
|
||||
- 最终汇总所有成果,给用户一个完整的答复
|
||||
30
cmd/server/main.go
Normal file
30
cmd/server/main.go
Normal file
@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/sdaduanbilei/agent-team/internal/api"
|
||||
)
|
||||
|
||||
func main() {
|
||||
agentsDir := env("AGENTS_DIR", "agents")
|
||||
skillsDir := env("SKILLS_DIR", "skills")
|
||||
roomsDir := env("ROOMS_DIR", "rooms")
|
||||
addr := env("ADDR", ":8080")
|
||||
|
||||
for _, dir := range []string{agentsDir, skillsDir, roomsDir} {
|
||||
os.MkdirAll(dir, 0755)
|
||||
}
|
||||
|
||||
s := api.New(agentsDir, skillsDir, roomsDir)
|
||||
log.Printf("agent-team server starting on %s", addr)
|
||||
log.Fatal(s.Start(addr))
|
||||
}
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
137
docs/plans/plan.md
Normal file
137
docs/plans/plan.md
Normal file
@ -0,0 +1,137 @@
|
||||
# Agent Team — 开发进度
|
||||
|
||||
**最后更新**: 2026-03-04
|
||||
**仓库**: https://gitea.catter.cn/sdaduanbilei/agent-team.git
|
||||
|
||||
---
|
||||
|
||||
## 已完成
|
||||
|
||||
### Go 后端
|
||||
- [x] `go.mod` 初始化,依赖已锁定(Go 1.20 兼容版本)
|
||||
- [x] `internal/llm/client.go` — OpenAI 兼容客户端,支持 DeepSeek/Kimi/Ollama/OpenAI,流式输出
|
||||
- [x] `internal/agent/agent.go` — AGENT.md frontmatter 解析,SOUL.md 加载,memory 读写,system prompt 构建
|
||||
- [x] `internal/skill/skill.go` — agentskills.io 标准,skill 发现/加载/XML 生成
|
||||
- [x] `internal/room/room.go` — 群配置加载,master orchestration 循环(分配→执行→review→迭代),WebSocket 事件广播
|
||||
- [x] `internal/hub/hub.go` — GitHub repo clone,团队包安装(agents/ + skills/)
|
||||
- [x] `internal/api/server.go` — Echo HTTP 服务,WebSocket hub,全部 REST 接口
|
||||
- [x] `cmd/server/main.go` — 入口,读取环境变量启动
|
||||
|
||||
### React 前端
|
||||
- [x] Vite + React + TypeScript 项目初始化(`web/`)
|
||||
- [x] Tailwind CSS v4 + `@tailwindcss/vite` 配置
|
||||
- [x] `web/src/types.ts` — 所有类型定义
|
||||
- [x] `web/src/store.ts` — Zustand store,WebSocket 连接,消息流式拼接
|
||||
- [x] `web/src/App.tsx` — 三栏布局骨架,左侧导航(群聊/Agents/市场)
|
||||
- [x] `web/src/components/RoomSidebar.tsx` — 群列表,实时状态 badge,创建群表单
|
||||
- [x] `web/src/components/ChatView.tsx` — 消息流,角色样式,右侧面板(Members/Tasks/产物),抽屉按钮
|
||||
- [x] `web/src/components/AgentsPage.tsx` — Monaco MD 编辑器,AGENT.md/SOUL.md 编辑,创建/删除 agent
|
||||
- [x] `web/src/components/MarketPage.tsx` — GitHub 一键雇佣,发布说明
|
||||
|
||||
### 配置文件
|
||||
- [x] `agents/example-master/AGENT.md` + `SOUL.md` — 示例 master agent
|
||||
- [x] `skills/example/SKILL.md` — 示例 skill
|
||||
- [x] `docs/plans/PRD.md` — 完整产品需求文档
|
||||
- [x] `README.md`
|
||||
|
||||
---
|
||||
|
||||
## 待完成
|
||||
|
||||
### 紧急(下次开始先做)
|
||||
|
||||
- [ ] **提交代码到 git** — 所有代码已写好但还未 commit/push
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "feat: implement full agent-team platform"
|
||||
git push
|
||||
```
|
||||
|
||||
- [ ] **前端构建验证** — 确认 Tailwind v4 + Monaco Editor 能正常编译
|
||||
```bash
|
||||
cd web && npm run build
|
||||
```
|
||||
|
||||
- [ ] **后端编译验证** — 已通过 `go build ./...`,但需要实际运行测试
|
||||
```bash
|
||||
DEEPSEEK_API_KEY=xxx go run cmd/server/main.go
|
||||
```
|
||||
|
||||
### 功能补全
|
||||
|
||||
- [ ] **SkillsPage 组件** — skills 列表页面(查看/创建 skill),目前 store 有 `fetchSkills` 但没有对应页面
|
||||
- 在 `web/src/components/SkillsPage.tsx` 新建
|
||||
- App.tsx 加入 skills 导航入口
|
||||
|
||||
- [ ] **Agent memory 自动更新** — 任务完成后 master 自动总结经验写入 `agents/<name>/memory/`
|
||||
- 在 `internal/room/room.go` 的 orchestration 循环末尾调用 `agent.SaveMemory()`
|
||||
- 需要让 master 生成一段经验总结
|
||||
|
||||
- [ ] **消息历史持久化** — 目前消息只在内存,刷新页面丢失
|
||||
- 每条消息追加写入 `rooms/<id>/history/YYYY-MM-DD.md`
|
||||
- 前端启动时通过 REST 接口加载历史
|
||||
|
||||
- [ ] **右侧面板 Skills tab** — 点击 Skills 抽屉按钮时展示群内可用 skills
|
||||
- 调用 `GET /api/skills` 获取列表
|
||||
|
||||
- [ ] **Workspace 文件预览** — 点击产物文件名时展示 MD 内容
|
||||
- 新增 `GET /api/rooms/:id/workspace/:filename` 接口
|
||||
- 前端弹出 Modal 展示 ReactMarkdown 渲染
|
||||
|
||||
- [ ] **创建群时成员选择优化** — 目前是手动输入 agent 名,改为下拉多选
|
||||
- 调用 `GET /api/agents` 获取列表,渲染 checkbox
|
||||
|
||||
- [ ] **Leader 群的 orchestration** — 目前 room.go 的 Handle 只支持单 master,Leader 群需要广播给多个 master
|
||||
- Leader 群:用户消息广播给所有 master,每个 master 在自己的部门群里处理
|
||||
|
||||
- [ ] **环境变量配置页** — 前端提供一个设置页,配置各 provider 的 API Key
|
||||
- 写入本地 `.env` 文件或通过 `PUT /api/config` 接口
|
||||
|
||||
### 已知问题
|
||||
|
||||
- [ ] `web/src/App.css` 可以删除(Vite 默认生成,已不需要)
|
||||
- [ ] `web/src/assets/react.svg` 可以删除
|
||||
- [ ] `web/public/vite.svg` 可以删除
|
||||
- [ ] `main.tsx` 里的 `import './App.css'` 需要删除
|
||||
|
||||
---
|
||||
|
||||
## 环境要求
|
||||
|
||||
| 工具 | 版本 |
|
||||
|------|------|
|
||||
| Go | 1.20+ |
|
||||
| Node.js | 18+ |
|
||||
| git | 任意 |
|
||||
|
||||
## 启动方式
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
export DEEPSEEK_API_KEY=your_key
|
||||
go run cmd/server/main.go
|
||||
|
||||
# 前端(另一个终端)
|
||||
cd web
|
||||
npm install
|
||||
npm run dev
|
||||
# 访问 http://localhost:5173
|
||||
```
|
||||
|
||||
## 关键设计决策(供参考)
|
||||
|
||||
1. **一切皆 MD** — agent 配置、soul、memory、tasks、history 全部是 MD 文件,无数据库
|
||||
2. **Context 隔离** — 每个 agent 的 LLM 调用独立,master 只看摘要,子 agent 只看自己的任务
|
||||
3. **agentskills.io 标准** — skill 格式遵循开放标准,可复用社区 skill
|
||||
4. **OpenAI 兼容接口** — 所有 provider 统一用 go-openai,只改 BaseURL
|
||||
5. **去中心化 Hub** — 团队包就是 GitHub repo,topic `agent-team` 聚合发现
|
||||
|
||||
## 用户问题备忘
|
||||
|
||||
> "导演 agent 会不会忘记之前的内容?"
|
||||
|
||||
**答**:不会忘,通过两个机制保证:
|
||||
1. **任务内 context**:整个 orchestration 循环(分配→执行→review)是同一个 `masterMsgs` 数组,导演始终看到完整对话
|
||||
2. **跨任务 memory**:任务完成后经验写入 `agents/director/memory/`,下次任务时注入 system prompt
|
||||
|
||||
导演的 identity(SOUL.md)永远不变,memory 会随经验积累越来越丰富。
|
||||
19
go.mod
Normal file
19
go.mod
Normal file
@ -0,0 +1,19 @@
|
||||
module github.com/sdaduanbilei/agent-team
|
||||
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/labstack/echo/v4 v4.12.0 // indirect
|
||||
github.com/labstack/gommon v0.4.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/sashabaranov/go-openai v1.36.1 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
golang.org/x/crypto v0.28.0 // indirect
|
||||
golang.org/x/net v0.30.0 // indirect
|
||||
golang.org/x/sys v0.26.0 // indirect
|
||||
golang.org/x/text v0.19.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
44
go.sum
Normal file
44
go.sum
Normal file
@ -0,0 +1,44 @@
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
|
||||
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
|
||||
github.com/labstack/echo/v4 v4.15.1 h1:S9keusg26gZpjMmPqB5hOEvNKnmd1lNmcHrbbH2lnFs=
|
||||
github.com/labstack/echo/v4 v4.15.1/go.mod h1:xmw1clThob0BSVRX1CRQkGQ/vjwcpOMjQZSZa9fKA/c=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/sashabaranov/go-openai v1.36.1 h1:EVfRXwIlW2rUzpx6vR+aeIKCK/xylSrVYAx1TMTSX3g=
|
||||
github.com/sashabaranov/go-openai v1.36.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
|
||||
github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
|
||||
github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
|
||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
113
internal/agent/agent.go
Normal file
113
internal/agent/agent.go
Normal file
@ -0,0 +1,113 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/sdaduanbilei/agent-team/internal/llm"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description"`
|
||||
Provider string `yaml:"provider"`
|
||||
Model string `yaml:"model"`
|
||||
BaseURL string `yaml:"base_url"`
|
||||
APIKeyEnv string `yaml:"api_key_env"`
|
||||
Skills []string `yaml:"skills"`
|
||||
}
|
||||
|
||||
type Agent struct {
|
||||
Config Config
|
||||
Soul string // system prompt from SOUL.md
|
||||
Dir string // agents/<name>/
|
||||
client *llm.Client
|
||||
}
|
||||
|
||||
func Load(dir string) (*Agent, error) {
|
||||
agentMD, err := os.ReadFile(filepath.Join(dir, "AGENT.md"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := parseFrontmatter(agentMD)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse AGENT.md: %w", err)
|
||||
}
|
||||
soul, _ := os.ReadFile(filepath.Join(dir, "SOUL.md"))
|
||||
|
||||
if cfg.Provider == "" {
|
||||
cfg.Provider = "deepseek"
|
||||
}
|
||||
if cfg.APIKeyEnv == "" {
|
||||
cfg.APIKeyEnv = "DEEPSEEK_API_KEY"
|
||||
}
|
||||
|
||||
client, err := llm.New(cfg.Provider, cfg.Model, cfg.BaseURL, cfg.APIKeyEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Agent{Config: cfg, Soul: string(soul), Dir: dir, client: client}, nil
|
||||
}
|
||||
|
||||
func parseFrontmatter(data []byte) (Config, error) {
|
||||
var cfg Config
|
||||
if !bytes.HasPrefix(data, []byte("---")) {
|
||||
return cfg, fmt.Errorf("missing frontmatter")
|
||||
}
|
||||
parts := bytes.SplitN(data, []byte("---"), 3)
|
||||
if len(parts) < 3 {
|
||||
return cfg, fmt.Errorf("invalid frontmatter")
|
||||
}
|
||||
return cfg, yaml.Unmarshal(parts[1], &cfg)
|
||||
}
|
||||
|
||||
// Memory returns concatenated memory files content.
|
||||
func (a *Agent) Memory() string {
|
||||
memDir := filepath.Join(a.Dir, "memory")
|
||||
entries, err := os.ReadDir(memDir)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), ".md") {
|
||||
data, _ := os.ReadFile(filepath.Join(memDir, e.Name()))
|
||||
sb.Write(data)
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// SaveMemory appends/updates a memory file.
|
||||
func (a *Agent) SaveMemory(filename, content string) error {
|
||||
memDir := filepath.Join(a.Dir, "memory")
|
||||
os.MkdirAll(memDir, 0755)
|
||||
return os.WriteFile(filepath.Join(memDir, filename), []byte(content), 0644)
|
||||
}
|
||||
|
||||
// Chat sends messages and streams response tokens via onToken callback.
|
||||
func (a *Agent) Chat(ctx context.Context, msgs []llm.Message, onToken func(string)) (string, error) {
|
||||
return a.client.Stream(ctx, msgs, onToken)
|
||||
}
|
||||
|
||||
// BuildSystemPrompt constructs the full system prompt with soul + memory + injected context.
|
||||
func (a *Agent) BuildSystemPrompt(extraContext string) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(a.Soul)
|
||||
if mem := a.Memory(); mem != "" {
|
||||
sb.WriteString("\n\n<memory>\n")
|
||||
sb.WriteString(mem)
|
||||
sb.WriteString("</memory>")
|
||||
}
|
||||
if extraContext != "" {
|
||||
sb.WriteString("\n\n")
|
||||
sb.WriteString(extraContext)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
296
internal/api/server.go
Normal file
296
internal/api/server.go
Normal file
@ -0,0 +1,296 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/sdaduanbilei/agent-team/internal/hub"
|
||||
"github.com/sdaduanbilei/agent-team/internal/room"
|
||||
"github.com/sdaduanbilei/agent-team/internal/skill"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
e *echo.Echo
|
||||
agentsDir string
|
||||
skillsDir string
|
||||
roomsDir string
|
||||
rooms map[string]*room.Room
|
||||
mu sync.RWMutex
|
||||
clients map[string]map[*websocket.Conn]bool // roomID -> conns
|
||||
clientsMu sync.Mutex
|
||||
upgrader websocket.Upgrader
|
||||
}
|
||||
|
||||
func New(agentsDir, skillsDir, roomsDir string) *Server {
|
||||
s := &Server{
|
||||
e: echo.New(),
|
||||
agentsDir: agentsDir,
|
||||
skillsDir: skillsDir,
|
||||
roomsDir: roomsDir,
|
||||
rooms: make(map[string]*room.Room),
|
||||
clients: make(map[string]map[*websocket.Conn]bool),
|
||||
upgrader: websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }},
|
||||
}
|
||||
s.loadRooms()
|
||||
s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start(addr string) error {
|
||||
return s.e.Start(addr)
|
||||
}
|
||||
|
||||
func (s *Server) routes() {
|
||||
s.e.Static("/", "web/dist")
|
||||
|
||||
g := s.e.Group("/api")
|
||||
g.GET("/rooms", s.listRooms)
|
||||
g.POST("/rooms", s.createRoom)
|
||||
g.GET("/agents", s.listAgents)
|
||||
g.GET("/agents/:name/files/:file", s.readAgentFile)
|
||||
g.PUT("/agents/:name/files/:file", s.writeAgentFile)
|
||||
g.POST("/agents", s.createAgent)
|
||||
g.DELETE("/agents/:name", s.deleteAgent)
|
||||
g.GET("/skills", s.listSkills)
|
||||
g.GET("/skills/:name", s.getSkill)
|
||||
g.POST("/hub/install", s.hubInstall)
|
||||
g.GET("/rooms/:id/workspace", s.listWorkspace)
|
||||
g.GET("/rooms/:id/tasks", s.getTasks)
|
||||
g.GET("/rooms/:id/history", s.listHistory)
|
||||
|
||||
s.e.GET("/ws/:roomID", s.wsHandler)
|
||||
}
|
||||
|
||||
func (s *Server) loadRooms() {
|
||||
entries, _ := os.ReadDir(s.roomsDir)
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
r, err := room.Load(filepath.Join(s.roomsDir, e.Name()), s.agentsDir, s.skillsDir)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
r.Broadcast = func(ev room.Event) { s.broadcast(ev.RoomID, ev) }
|
||||
s.rooms[e.Name()] = r
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) broadcast(roomID string, ev room.Event) {
|
||||
s.clientsMu.Lock()
|
||||
defer s.clientsMu.Unlock()
|
||||
data, _ := json.Marshal(ev)
|
||||
for conn := range s.clients[roomID] {
|
||||
conn.WriteMessage(websocket.TextMessage, data)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) wsHandler(c echo.Context) error {
|
||||
roomID := c.Param("roomID")
|
||||
conn, err := s.upgrader.Upgrade(c.Response(), c.Request(), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.clientsMu.Lock()
|
||||
if s.clients[roomID] == nil {
|
||||
s.clients[roomID] = make(map[*websocket.Conn]bool)
|
||||
}
|
||||
s.clients[roomID][conn] = true
|
||||
s.clientsMu.Unlock()
|
||||
|
||||
defer func() {
|
||||
s.clientsMu.Lock()
|
||||
delete(s.clients[roomID], conn)
|
||||
s.clientsMu.Unlock()
|
||||
conn.Close()
|
||||
}()
|
||||
|
||||
for {
|
||||
_, msg, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
var ev struct {
|
||||
Type string `json:"type"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if json.Unmarshal(msg, &ev) != nil || ev.Type != "user_message" {
|
||||
continue
|
||||
}
|
||||
s.mu.RLock()
|
||||
r := s.rooms[roomID]
|
||||
s.mu.RUnlock()
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
go r.Handle(context.Background(), ev.Content)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- REST handlers ---
|
||||
|
||||
func (s *Server) listRooms(c echo.Context) error {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
type roomInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Status room.Status `json:"status"`
|
||||
Master string `json:"master"`
|
||||
}
|
||||
var list []roomInfo
|
||||
for id, r := range s.rooms {
|
||||
list = append(list, roomInfo{ID: id, Name: r.Config.Name, Type: string(r.Config.Type), Status: r.Status, Master: r.Config.Master})
|
||||
}
|
||||
return c.JSON(200, list)
|
||||
}
|
||||
|
||||
func (s *Server) createRoom(c echo.Context) error {
|
||||
var cfg room.Config
|
||||
if err := c.Bind(&cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Join(s.roomsDir, cfg.Name)
|
||||
os.MkdirAll(filepath.Join(dir, "workspace"), 0755)
|
||||
os.MkdirAll(filepath.Join(dir, "history"), 0755)
|
||||
|
||||
content := "---\nname: " + cfg.Name + "\ntype: " + string(cfg.Type) + "\nmaster: " + cfg.Master + "\nmembers:\n"
|
||||
for _, m := range cfg.Members {
|
||||
content += " - " + m + "\n"
|
||||
}
|
||||
content += "---\n"
|
||||
os.WriteFile(filepath.Join(dir, "room.md"), []byte(content), 0644)
|
||||
|
||||
r, err := room.Load(dir, s.agentsDir, s.skillsDir)
|
||||
if err != nil {
|
||||
return c.JSON(500, map[string]string{"error": err.Error()})
|
||||
}
|
||||
r.Broadcast = func(ev room.Event) { s.broadcast(ev.RoomID, ev) }
|
||||
s.mu.Lock()
|
||||
s.rooms[cfg.Name] = r
|
||||
s.mu.Unlock()
|
||||
return c.JSON(201, map[string]string{"id": cfg.Name})
|
||||
}
|
||||
|
||||
func (s *Server) listAgents(c echo.Context) error {
|
||||
entries, _ := os.ReadDir(s.agentsDir)
|
||||
type agentInfo struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
var list []agentInfo
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
list = append(list, agentInfo{Name: e.Name()})
|
||||
}
|
||||
}
|
||||
return c.JSON(200, list)
|
||||
}
|
||||
|
||||
func (s *Server) readAgentFile(c echo.Context) error {
|
||||
name := c.Param("name")
|
||||
file := c.Param("file") // AGENT.md or SOUL.md
|
||||
data, err := os.ReadFile(filepath.Join(s.agentsDir, name, file))
|
||||
if err != nil {
|
||||
return c.JSON(404, map[string]string{"error": "not found"})
|
||||
}
|
||||
return c.JSON(200, map[string]string{"content": string(data)})
|
||||
}
|
||||
|
||||
func (s *Server) writeAgentFile(c echo.Context) error {
|
||||
name := c.Param("name")
|
||||
file := c.Param("file")
|
||||
var body struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := c.Bind(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Join(s.agentsDir, name)
|
||||
os.MkdirAll(dir, 0755)
|
||||
return os.WriteFile(filepath.Join(dir, file), []byte(body.Content), 0644)
|
||||
}
|
||||
|
||||
func (s *Server) createAgent(c echo.Context) error {
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := c.Bind(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Join(s.agentsDir, body.Name)
|
||||
os.MkdirAll(filepath.Join(dir, "memory"), 0755)
|
||||
agentMD := "---\nname: " + body.Name + "\ndescription: \nprovider: deepseek\nmodel: deepseek-chat\napi_key_env: DEEPSEEK_API_KEY\nskills: []\n---\n"
|
||||
os.WriteFile(filepath.Join(dir, "AGENT.md"), []byte(agentMD), 0644)
|
||||
os.WriteFile(filepath.Join(dir, "SOUL.md"), []byte("You are "+body.Name+"."), 0644)
|
||||
return c.JSON(201, map[string]string{"name": body.Name})
|
||||
}
|
||||
|
||||
func (s *Server) deleteAgent(c echo.Context) error {
|
||||
name := c.Param("name")
|
||||
return os.RemoveAll(filepath.Join(s.agentsDir, name))
|
||||
}
|
||||
|
||||
func (s *Server) listSkills(c echo.Context) error {
|
||||
metas, _ := skill.Discover(s.skillsDir)
|
||||
return c.JSON(200, metas)
|
||||
}
|
||||
|
||||
func (s *Server) getSkill(c echo.Context) error {
|
||||
name := c.Param("name")
|
||||
sk, err := skill.Load(filepath.Join(s.skillsDir, name))
|
||||
if err != nil {
|
||||
return c.JSON(404, map[string]string{"error": "not found"})
|
||||
}
|
||||
return c.JSON(200, sk)
|
||||
}
|
||||
|
||||
func (s *Server) hubInstall(c echo.Context) error {
|
||||
var body struct {
|
||||
Repo string `json:"repo"`
|
||||
}
|
||||
if err := c.Bind(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := hub.Install(body.Repo, s.agentsDir, s.skillsDir); err != nil {
|
||||
return c.JSON(500, map[string]string{"error": err.Error()})
|
||||
}
|
||||
s.loadRooms()
|
||||
return c.JSON(200, map[string]string{"status": "installed"})
|
||||
}
|
||||
|
||||
func (s *Server) listWorkspace(c echo.Context) error {
|
||||
id := c.Param("id")
|
||||
dir := filepath.Join(s.roomsDir, id, "workspace")
|
||||
entries, _ := os.ReadDir(dir)
|
||||
var files []string
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
files = append(files, e.Name())
|
||||
}
|
||||
}
|
||||
return c.JSON(200, files)
|
||||
}
|
||||
|
||||
func (s *Server) getTasks(c echo.Context) error {
|
||||
id := c.Param("id")
|
||||
data, _ := os.ReadFile(filepath.Join(s.roomsDir, id, "tasks.md"))
|
||||
return c.JSON(200, map[string]string{"content": string(data)})
|
||||
}
|
||||
|
||||
func (s *Server) listHistory(c echo.Context) error {
|
||||
id := c.Param("id")
|
||||
entries, _ := os.ReadDir(filepath.Join(s.roomsDir, id, "history"))
|
||||
var files []string
|
||||
for _, e := range entries {
|
||||
files = append(files, e.Name())
|
||||
}
|
||||
return c.JSON(200, files)
|
||||
}
|
||||
70
internal/hub/hub.go
Normal file
70
internal/hub/hub.go
Normal file
@ -0,0 +1,70 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Install clones a GitHub repo (owner/repo or full URL) and installs the team.
|
||||
func Install(repoRef, agentsDir, skillsDir string) error {
|
||||
url := repoRef
|
||||
if !strings.HasPrefix(repoRef, "http") {
|
||||
url = "https://github.com/" + repoRef
|
||||
}
|
||||
|
||||
tmp, err := os.MkdirTemp("", "agent-team-hub-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
|
||||
cmd := exec.Command("git", "clone", "--depth=1", url, tmp)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("git clone: %w", err)
|
||||
}
|
||||
|
||||
// Copy agents/
|
||||
if err := copyDir(filepath.Join(tmp, "agents"), agentsDir); err != nil {
|
||||
return fmt.Errorf("install agents: %w", err)
|
||||
}
|
||||
// Copy skills/
|
||||
if err := copyDir(filepath.Join(tmp, "skills"), skillsDir); err != nil {
|
||||
return fmt.Errorf("install skills: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func copyDir(src, dst string) error {
|
||||
if _, err := os.Stat(src); os.IsNotExist(err) {
|
||||
return nil // optional dir, skip
|
||||
}
|
||||
os.MkdirAll(dst, 0755)
|
||||
entries, err := os.ReadDir(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
srcPath := filepath.Join(src, e.Name())
|
||||
dstPath := filepath.Join(dst, e.Name())
|
||||
if e.IsDir() {
|
||||
if err := copyDir(srcPath, dstPath); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
data, err := os.ReadFile(srcPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
os.MkdirAll(filepath.Dir(dstPath), 0755)
|
||||
if err := os.WriteFile(dstPath, data, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
85
internal/llm/client.go
Normal file
85
internal/llm/client.go
Normal file
@ -0,0 +1,85 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
var providers = map[string]string{
|
||||
"deepseek": "https://api.deepseek.com/v1",
|
||||
"kimi": "https://api.moonshot.cn/v1",
|
||||
"ollama": "http://localhost:11434/v1",
|
||||
"openai": "https://api.openai.com/v1",
|
||||
}
|
||||
|
||||
var defaultModels = map[string]string{
|
||||
"deepseek": "deepseek-chat",
|
||||
"kimi": "moonshot-v1-8k",
|
||||
"ollama": "qwen2.5",
|
||||
"openai": "gpt-4o",
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
c *openai.Client
|
||||
model string
|
||||
}
|
||||
|
||||
func New(provider, model, baseURL, apiKeyEnv string) (*Client, error) {
|
||||
if baseURL == "" {
|
||||
var ok bool
|
||||
baseURL, ok = providers[provider]
|
||||
if !ok {
|
||||
baseURL = providers["deepseek"]
|
||||
}
|
||||
}
|
||||
if model == "" {
|
||||
model = defaultModels[provider]
|
||||
if model == "" {
|
||||
model = "deepseek-chat"
|
||||
}
|
||||
}
|
||||
apiKey := os.Getenv(apiKeyEnv)
|
||||
if apiKey == "" {
|
||||
apiKey = "ollama" // ollama doesn't need a real key
|
||||
}
|
||||
cfg := openai.DefaultConfig(apiKey)
|
||||
cfg.BaseURL = baseURL
|
||||
return &Client{c: openai.NewClientWithConfig(cfg), model: model}, nil
|
||||
}
|
||||
|
||||
type Message = openai.ChatCompletionMessage
|
||||
|
||||
func NewMsg(role, content string) Message {
|
||||
return Message{Role: role, Content: content}
|
||||
}
|
||||
|
||||
// Stream calls the LLM and streams tokens to the callback. Returns full response.
|
||||
func (c *Client) Stream(ctx context.Context, msgs []Message, onToken func(string)) (string, error) {
|
||||
req := openai.ChatCompletionRequest{
|
||||
Model: c.model,
|
||||
Messages: msgs,
|
||||
Stream: true,
|
||||
}
|
||||
stream, err := c.c.CreateChatCompletionStream(ctx, req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm stream: %w", err)
|
||||
}
|
||||
defer stream.Close()
|
||||
|
||||
var full string
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
delta := resp.Choices[0].Delta.Content
|
||||
full += delta
|
||||
if onToken != nil {
|
||||
onToken(delta)
|
||||
}
|
||||
}
|
||||
return full, nil
|
||||
}
|
||||
265
internal/room/room.go
Normal file
265
internal/room/room.go
Normal file
@ -0,0 +1,265 @@
|
||||
package room
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sdaduanbilei/agent-team/internal/agent"
|
||||
"github.com/sdaduanbilei/agent-team/internal/llm"
|
||||
"github.com/sdaduanbilei/agent-team/internal/skill"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type RoomType string
|
||||
|
||||
const (
|
||||
TypeDept RoomType = "dept"
|
||||
TypeLeader RoomType = "leader"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusPending Status = "pending"
|
||||
StatusThinking Status = "thinking"
|
||||
StatusWorking Status = "working"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Name string `yaml:"name"`
|
||||
Type RoomType `yaml:"type"`
|
||||
Master string `yaml:"master"` // agent name
|
||||
Members []string `yaml:"members"` // agent names
|
||||
}
|
||||
|
||||
type Room struct {
|
||||
Config Config
|
||||
Dir string
|
||||
master *agent.Agent
|
||||
members map[string]*agent.Agent
|
||||
skillMeta []skill.Meta
|
||||
Status Status
|
||||
ActiveAgent string // for working status display
|
||||
Broadcast func(Event) // set by api layer
|
||||
}
|
||||
|
||||
type EventType string
|
||||
|
||||
const (
|
||||
EvtAgentMessage EventType = "agent_message"
|
||||
EvtTaskAssign EventType = "task_assign"
|
||||
EvtReview EventType = "review"
|
||||
EvtRoomStatus EventType = "room_status"
|
||||
EvtTasksUpdate EventType = "tasks_update"
|
||||
EvtWorkspaceFile EventType = "workspace_file"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
Type EventType `json:"type"`
|
||||
RoomID string `json:"room_id"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Role string `json:"role,omitempty"` // master | member
|
||||
Content string `json:"content,omitempty"`
|
||||
Streaming bool `json:"streaming,omitempty"`
|
||||
From string `json:"from,omitempty"`
|
||||
To string `json:"to,omitempty"`
|
||||
Task string `json:"task,omitempty"`
|
||||
Feedback string `json:"feedback,omitempty"`
|
||||
Status Status `json:"status,omitempty"`
|
||||
ActiveAgent string `json:"active_agent,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Filename string `json:"filename,omitempty"`
|
||||
}
|
||||
|
||||
func Load(roomDir string, agentsDir string, skillsDir string) (*Room, error) {
|
||||
data, err := os.ReadFile(filepath.Join(roomDir, "room.md"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := parseRoomConfig(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
r := &Room{Config: cfg, Dir: roomDir, members: make(map[string]*agent.Agent)}
|
||||
|
||||
r.master, err = agent.Load(filepath.Join(agentsDir, cfg.Master))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load master %s: %w", cfg.Master, err)
|
||||
}
|
||||
for _, name := range cfg.Members {
|
||||
a, err := agent.Load(filepath.Join(agentsDir, name))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load member %s: %w", name, err)
|
||||
}
|
||||
r.members[name] = a
|
||||
}
|
||||
|
||||
r.skillMeta, _ = skill.Discover(skillsDir)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *Room) emit(e Event) {
|
||||
e.RoomID = r.Config.Name
|
||||
if r.Broadcast != nil {
|
||||
r.Broadcast(e)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Room) setStatus(s Status, activeAgent, action string) {
|
||||
r.Status = s
|
||||
r.ActiveAgent = activeAgent
|
||||
r.emit(Event{Type: EvtRoomStatus, Status: s, ActiveAgent: activeAgent, Action: action})
|
||||
}
|
||||
|
||||
// Handle processes a user message through master orchestration.
|
||||
func (r *Room) Handle(ctx context.Context, userMsg string) error {
|
||||
r.setStatus(StatusThinking, "", "")
|
||||
|
||||
// Build master context
|
||||
teamXML := r.buildTeamXML()
|
||||
skillXML := skill.ToXML(r.skillMeta)
|
||||
systemPrompt := r.master.BuildSystemPrompt(teamXML + "\n\n" + skillXML)
|
||||
|
||||
masterMsgs := []llm.Message{
|
||||
llm.NewMsg("system", systemPrompt+"\n\nYou are the master of this team. When you need a team member to do something, output a line like: ASSIGN:<member_name>:<task description>. When you are done reviewing and satisfied, output DONE:<summary>."),
|
||||
llm.NewMsg("user", userMsg),
|
||||
}
|
||||
|
||||
// Master planning loop
|
||||
for iteration := 0; iteration < 5; iteration++ {
|
||||
var masterReply strings.Builder
|
||||
_, err := r.master.Chat(ctx, masterMsgs, func(token string) {
|
||||
masterReply.WriteString(token)
|
||||
r.emit(Event{Type: EvtAgentMessage, Agent: r.master.Config.Name, Role: "master", Content: token, Streaming: true})
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply := masterReply.String()
|
||||
masterMsgs = append(masterMsgs, llm.NewMsg("assistant", reply))
|
||||
|
||||
// Parse assignments
|
||||
assignments := parseAssignments(reply)
|
||||
if len(assignments) == 0 {
|
||||
// No assignments, master is done
|
||||
break
|
||||
}
|
||||
|
||||
// Execute assignments
|
||||
var results strings.Builder
|
||||
for memberName, task := range assignments {
|
||||
member, ok := r.members[memberName]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
r.setStatus(StatusWorking, member.Config.Name, task)
|
||||
r.emit(Event{Type: EvtTaskAssign, From: r.master.Config.Name, To: memberName, Task: task})
|
||||
|
||||
memberSystem := member.BuildSystemPrompt(skillXML)
|
||||
memberMsgs := []llm.Message{
|
||||
llm.NewMsg("system", memberSystem),
|
||||
llm.NewMsg("user", task),
|
||||
}
|
||||
var memberReply strings.Builder
|
||||
_, err := member.Chat(ctx, memberMsgs, func(token string) {
|
||||
memberReply.WriteString(token)
|
||||
r.emit(Event{Type: EvtAgentMessage, Agent: memberName, Role: "member", Content: token, Streaming: true})
|
||||
})
|
||||
if err != nil {
|
||||
results.WriteString(fmt.Sprintf("[%s] error: %v\n", memberName, err))
|
||||
continue
|
||||
}
|
||||
result := memberReply.String()
|
||||
results.WriteString(fmt.Sprintf("[%s] %s\n", memberName, result))
|
||||
|
||||
// Save workspace file if member produced a document
|
||||
if strings.Contains(result, "# ") {
|
||||
filename := fmt.Sprintf("%s-%s.md", memberName, time.Now().Format("20060102-150405"))
|
||||
r.saveWorkspace(filename, result)
|
||||
r.emit(Event{Type: EvtWorkspaceFile, Filename: filename, Content: result})
|
||||
}
|
||||
}
|
||||
|
||||
// Feed results back to master for review
|
||||
r.setStatus(StatusThinking, "", "")
|
||||
masterMsgs = append(masterMsgs, llm.NewMsg("user", "Team results:\n"+results.String()+"\nPlease review. If satisfied output DONE:<summary>, otherwise output ASSIGN instructions for revisions."))
|
||||
|
||||
// Update tasks
|
||||
r.updateTasks(masterMsgs)
|
||||
|
||||
if strings.Contains(reply, "DONE:") {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.setStatus(StatusPending, "", "")
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseAssignments(text string) map[string]string {
|
||||
result := make(map[string]string)
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
if strings.HasPrefix(line, "ASSIGN:") {
|
||||
parts := strings.SplitN(strings.TrimPrefix(line, "ASSIGN:"), ":", 2)
|
||||
if len(parts) == 2 {
|
||||
result[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *Room) buildTeamXML() string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<team_members>\n")
|
||||
for name, a := range r.members {
|
||||
fmt.Fprintf(&sb, " <member>\n <name>%s</name>\n <description>%s</description>\n </member>\n", name, a.Config.Description)
|
||||
}
|
||||
sb.WriteString("</team_members>")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (r *Room) saveWorkspace(filename, content string) {
|
||||
dir := filepath.Join(r.Dir, "workspace")
|
||||
os.MkdirAll(dir, 0755)
|
||||
os.WriteFile(filepath.Join(dir, filename), []byte(content), 0644)
|
||||
}
|
||||
|
||||
func (r *Room) updateTasks(msgs []llm.Message) {
|
||||
// Extract task list from conversation and save
|
||||
var tasks strings.Builder
|
||||
tasks.WriteString("# Tasks\n\n")
|
||||
for _, m := range msgs {
|
||||
if m.Role == "assistant" && strings.Contains(m.Content, "ASSIGN:") {
|
||||
for _, line := range strings.Split(m.Content, "\n") {
|
||||
if strings.HasPrefix(line, "ASSIGN:") {
|
||||
parts := strings.SplitN(strings.TrimPrefix(line, "ASSIGN:"), ":", 2)
|
||||
if len(parts) == 2 {
|
||||
tasks.WriteString(fmt.Sprintf("- [ ] [%s] %s\n", strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
content := tasks.String()
|
||||
os.WriteFile(filepath.Join(r.Dir, "tasks.md"), []byte(content), 0644)
|
||||
r.emit(Event{Type: EvtTasksUpdate, Content: content})
|
||||
}
|
||||
|
||||
func parseRoomConfig(data []byte) (Config, error) {
|
||||
var cfg Config
|
||||
if !bytes.HasPrefix(data, []byte("---")) {
|
||||
return cfg, fmt.Errorf("missing frontmatter")
|
||||
}
|
||||
parts := bytes.SplitN(data, []byte("---"), 3)
|
||||
if len(parts) < 3 {
|
||||
return cfg, fmt.Errorf("invalid frontmatter")
|
||||
}
|
||||
return cfg, yaml.Unmarshal(parts[1], &cfg)
|
||||
}
|
||||
95
internal/skill/skill.go
Normal file
95
internal/skill/skill.go
Normal file
@ -0,0 +1,95 @@
|
||||
package skill
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Meta struct {
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description"`
|
||||
Path string `yaml:"-"`
|
||||
}
|
||||
|
||||
type Skill struct {
|
||||
Meta
|
||||
Body string // full SKILL.md body (instructions)
|
||||
}
|
||||
|
||||
// Discover scans skillsDir and returns metadata for all valid skills.
|
||||
func Discover(skillsDir string) ([]Meta, error) {
|
||||
entries, err := os.ReadDir(skillsDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var metas []Meta
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(skillsDir, e.Name(), "SKILL.md")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
meta, err := parseMeta(data)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
meta.Path = filepath.Join(skillsDir, e.Name())
|
||||
metas = append(metas, meta)
|
||||
}
|
||||
return metas, nil
|
||||
}
|
||||
|
||||
// Load returns a fully loaded skill including body.
|
||||
func Load(skillDir string) (*Skill, error) {
|
||||
data, err := os.ReadFile(filepath.Join(skillDir, "SKILL.md"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, err := parseMeta(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta.Path = skillDir
|
||||
body := extractBody(data)
|
||||
return &Skill{Meta: meta, Body: body}, nil
|
||||
}
|
||||
|
||||
// ToXML generates <available_skills> XML for agent system prompts.
|
||||
func ToXML(metas []Meta) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<available_skills>\n")
|
||||
for _, m := range metas {
|
||||
fmt.Fprintf(&sb, " <skill>\n <name>%s</name>\n <description>%s</description>\n <location>%s/SKILL.md</location>\n </skill>\n",
|
||||
m.Name, m.Description, m.Path)
|
||||
}
|
||||
sb.WriteString("</available_skills>")
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func parseMeta(data []byte) (Meta, error) {
|
||||
var meta Meta
|
||||
if !bytes.HasPrefix(data, []byte("---")) {
|
||||
return meta, fmt.Errorf("missing frontmatter")
|
||||
}
|
||||
parts := bytes.SplitN(data, []byte("---"), 3)
|
||||
if len(parts) < 3 {
|
||||
return meta, fmt.Errorf("invalid frontmatter")
|
||||
}
|
||||
return meta, yaml.Unmarshal(parts[1], &meta)
|
||||
}
|
||||
|
||||
func extractBody(data []byte) string {
|
||||
parts := bytes.SplitN(data, []byte("---"), 3)
|
||||
if len(parts) < 3 {
|
||||
return string(data)
|
||||
}
|
||||
return strings.TrimSpace(string(parts[2]))
|
||||
}
|
||||
18
skills/example/SKILL.md
Normal file
18
skills/example/SKILL.md
Normal file
@ -0,0 +1,18 @@
|
||||
---
|
||||
name: example-skill
|
||||
description: 示例 skill,展示 agentskills.io 标准格式
|
||||
---
|
||||
|
||||
# Example Skill
|
||||
|
||||
这是一个示例 skill,展示如何按照 agentskills.io 标准编写 skill。
|
||||
|
||||
## 使用场景
|
||||
|
||||
当用户需要示例功能时使用此 skill。
|
||||
|
||||
## 步骤
|
||||
|
||||
1. 分析用户需求
|
||||
2. 执行相应操作
|
||||
3. 返回结果
|
||||
24
web/.gitignore
vendored
Normal file
24
web/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
73
web/README.md
Normal file
73
web/README.md
Normal file
@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
web/eslint.config.js
Normal file
23
web/eslint.config.js
Normal file
@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
web/index.html
Normal file
13
web/index.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>web</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
5567
web/package-lock.json
generated
Normal file
5567
web/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
39
web/package.json
Normal file
39
web/package.json
Normal file
@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@tailwindcss/vite": "^4.2.1",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"autoprefixer": "^10.4.27",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"postcss": "^8.5.8",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.48.0",
|
||||
"vite": "^7.3.1"
|
||||
}
|
||||
}
|
||||
1
web/public/vite.svg
Normal file
1
web/public/vite.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
42
web/src/App.css
Normal file
42
web/src/App.css
Normal file
@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
32
web/src/App.tsx
Normal file
32
web/src/App.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import { useStore } from './store'
|
||||
import { RoomSidebar } from './components/RoomSidebar'
|
||||
import { ChatView } from './components/ChatView'
|
||||
import { AgentsPage } from './components/AgentsPage'
|
||||
import { MarketPage } from './components/MarketPage'
|
||||
|
||||
export default function App() {
|
||||
const { page, setPage } = useStore()
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-gray-800 text-gray-100 overflow-hidden">
|
||||
<div className="flex flex-col w-12 bg-gray-900 border-r border-gray-700 items-center py-3 gap-3">
|
||||
<NavBtn icon="💬" label="群聊" active={page === 'chat'} onClick={() => setPage('chat')} />
|
||||
<NavBtn icon="🤖" label="Agents" active={page === 'agents'} onClick={() => setPage('agents')} />
|
||||
<NavBtn icon="🛒" label="市场" active={page === 'market'} onClick={() => setPage('market')} />
|
||||
</div>
|
||||
|
||||
{page === 'chat' && <><RoomSidebar /><ChatView /></>}
|
||||
{page === 'agents' && <AgentsPage />}
|
||||
{page === 'market' && <MarketPage />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NavBtn({ icon, label, active, onClick }: { icon: string; label: string; active: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button onClick={onClick} title={label}
|
||||
className={`w-9 h-9 rounded-lg flex items-center justify-center text-lg ${active ? 'bg-indigo-600' : 'hover:bg-gray-700'}`}>
|
||||
{icon}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
1
web/src/assets/react.svg
Normal file
1
web/src/assets/react.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
87
web/src/components/AgentsPage.tsx
Normal file
87
web/src/components/AgentsPage.tsx
Normal file
@ -0,0 +1,87 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import Editor from '@monaco-editor/react'
|
||||
import { useStore } from '../store'
|
||||
|
||||
const API = '/api'
|
||||
|
||||
export function AgentsPage() {
|
||||
const { agents, fetchAgents } = useStore()
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
const [tab, setTab] = useState<'AGENT.md' | 'SOUL.md'>('AGENT.md')
|
||||
const [content, setContent] = useState('')
|
||||
const [newName, setNewName] = useState('')
|
||||
|
||||
useEffect(() => { fetchAgents() }, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) return
|
||||
fetch(`${API}/agents/${selected}/files/${tab}`).then(r => r.json()).then(d => setContent(d.content || ''))
|
||||
}, [selected, tab])
|
||||
|
||||
const save = async () => {
|
||||
if (!selected) return
|
||||
await fetch(`${API}/agents/${selected}/files/${tab}`, {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content })
|
||||
})
|
||||
}
|
||||
|
||||
const create = async () => {
|
||||
if (!newName.trim()) return
|
||||
await fetch(`${API}/agents`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName.trim() }) })
|
||||
setNewName('')
|
||||
fetchAgents()
|
||||
}
|
||||
|
||||
const del = async (name: string) => {
|
||||
await fetch(`${API}/agents/${name}`, { method: 'DELETE' })
|
||||
if (selected === name) setSelected(null)
|
||||
fetchAgents()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Agent list */}
|
||||
<div className="w-48 border-r border-gray-700 flex flex-col">
|
||||
<div className="p-3 border-b border-gray-700">
|
||||
<div className="flex gap-1">
|
||||
<input className="flex-1 bg-gray-700 rounded px-2 py-1 text-xs" placeholder="新 agent 名" value={newName} onChange={e => setNewName(e.target.value)} onKeyDown={e => e.key === 'Enter' && create()} />
|
||||
<button onClick={create} className="bg-indigo-600 hover:bg-indigo-500 px-2 py-1 rounded text-xs">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{agents.map(a => (
|
||||
<div key={a.name} onClick={() => setSelected(a.name)}
|
||||
className={`flex items-center justify-between px-3 py-2 cursor-pointer text-sm hover:bg-gray-700 ${selected === a.name ? 'bg-gray-700' : ''}`}>
|
||||
<span className="truncate">{a.name}</span>
|
||||
<button onClick={e => { e.stopPropagation(); del(a.name) }} className="text-gray-500 hover:text-red-400 text-xs">✕</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Editor */}
|
||||
<div className="flex-1 flex flex-col overflow-hidden">
|
||||
{selected ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2 px-4 py-2 border-b border-gray-700">
|
||||
<span className="font-semibold text-sm">{selected}</span>
|
||||
<div className="flex gap-1 ml-2">
|
||||
{(['AGENT.md', 'SOUL.md'] as const).map(t => (
|
||||
<button key={t} onClick={() => setTab(t)}
|
||||
className={`text-xs px-3 py-1 rounded ${tab === t ? 'bg-indigo-600' : 'bg-gray-700 hover:bg-gray-600'}`}>{t}</button>
|
||||
))}
|
||||
</div>
|
||||
<button onClick={save} className="ml-auto bg-green-700 hover:bg-green-600 px-3 py-1 rounded text-xs">保存</button>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<Editor height="100%" defaultLanguage="markdown" theme="vs-dark" value={content} onChange={v => setContent(v || '')} options={{ minimap: { enabled: false }, wordWrap: 'on', fontSize: 13 }} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex-1 flex items-center justify-center text-gray-400 text-sm">选择一个 agent 编辑</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
156
web/src/components/ChatView.tsx
Normal file
156
web/src/components/ChatView.tsx
Normal file
@ -0,0 +1,156 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { useStore } from '../store'
|
||||
import { Message } from '../types'
|
||||
|
||||
export function ChatView() {
|
||||
const { activeRoomId, rooms, messages, tasks, workspace, sendMessage } = useStore()
|
||||
const [input, setInput] = useState('')
|
||||
const [drawer, setDrawer] = useState<null | 'skills' | 'history' | 'workspace'>(null)
|
||||
const bottomRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const room = rooms.find(r => r.id === activeRoomId)
|
||||
const msgs: Message[] = activeRoomId ? (messages[activeRoomId] || []) : []
|
||||
const tasksMd = activeRoomId ? (tasks[activeRoomId] || '') : ''
|
||||
const files = activeRoomId ? (workspace[activeRoomId] || []) : []
|
||||
|
||||
useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [msgs])
|
||||
|
||||
if (!room) return <div className="flex-1 flex items-center justify-center text-gray-400">选择一个群开始</div>
|
||||
|
||||
const statusLabel = room.status === 'working' && room.activeAgent
|
||||
? `working · ${room.activeAgent} ${room.action || ''}`
|
||||
: room.status
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Chat area */}
|
||||
<div className="flex flex-col flex-1 overflow-hidden">
|
||||
<div className="px-4 py-2 border-b border-gray-700 flex items-center gap-2">
|
||||
<span className="font-semibold">{room.name}</span>
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full ${
|
||||
room.status === 'pending' ? 'bg-gray-600 text-gray-300' :
|
||||
room.status === 'thinking' ? 'bg-yellow-600 text-yellow-100' :
|
||||
'bg-green-700 text-green-100'
|
||||
}`}>{statusLabel}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-3">
|
||||
{msgs.map(msg => <MessageBubble key={msg.id} msg={msg} />)}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
|
||||
<div className="p-3 border-t border-gray-700 flex gap-2">
|
||||
<input
|
||||
className="flex-1 bg-gray-700 rounded px-3 py-2 text-sm outline-none"
|
||||
placeholder="输入消息..."
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && input.trim()) { sendMessage(room.id, input.trim()); setInput('') } }}
|
||||
/>
|
||||
<button
|
||||
className="bg-indigo-600 hover:bg-indigo-500 px-4 py-2 rounded text-sm"
|
||||
onClick={() => { if (input.trim()) { sendMessage(room.id, input.trim()); setInput('') } }}
|
||||
>发送</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right panel */}
|
||||
<div className="w-64 border-l border-gray-700 flex flex-col overflow-hidden">
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-4">
|
||||
{/* Members */}
|
||||
<section>
|
||||
<h3 className="text-xs font-semibold text-gray-400 uppercase mb-2">Members</h3>
|
||||
<MemberItem name={room.master} role="master" status={room.status === 'thinking' ? 'thinking' : 'pending'} />
|
||||
{msgs.filter(m => m.role === 'member').map(m => m.agent).filter((v, i, a) => a.indexOf(v) === i).map(name => (
|
||||
<MemberItem key={name} name={name} role="member"
|
||||
status={room.status === 'working' && room.activeAgent === name ? 'working' : 'pending'} />
|
||||
))}
|
||||
</section>
|
||||
|
||||
{/* Tasks */}
|
||||
{tasksMd && (
|
||||
<section>
|
||||
<h3 className="text-xs font-semibold text-gray-400 uppercase mb-2">Tasks</h3>
|
||||
<div className="text-xs prose prose-invert max-w-none">
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>{tasksMd}</ReactMarkdown>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Workspace files */}
|
||||
{files.length > 0 && (
|
||||
<section>
|
||||
<h3 className="text-xs font-semibold text-gray-400 uppercase mb-2">产物</h3>
|
||||
{files.map(f => (
|
||||
<div key={f} className="flex items-center gap-1 text-xs text-indigo-300 hover:text-indigo-200 cursor-pointer py-0.5">
|
||||
<span>📄</span><span className="truncate">{f}</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Drawer buttons */}
|
||||
<div className="p-2 border-t border-gray-700 flex gap-1">
|
||||
{(['skills', 'history', 'workspace'] as const).map(d => (
|
||||
<button key={d} onClick={() => setDrawer(drawer === d ? null : d)}
|
||||
className={`flex-1 text-xs py-1 rounded ${drawer === d ? 'bg-indigo-600' : 'bg-gray-700 hover:bg-gray-600'}`}>
|
||||
{d === 'skills' ? 'Skills' : d === 'history' ? 'History' : 'Workspace'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Drawer overlay */}
|
||||
{drawer && (
|
||||
<div className="absolute right-64 top-0 bottom-0 w-80 bg-gray-800 border-l border-gray-700 p-4 overflow-y-auto z-10">
|
||||
<div className="flex justify-between items-center mb-3">
|
||||
<h3 className="font-semibold capitalize">{drawer}</h3>
|
||||
<button onClick={() => setDrawer(null)} className="text-gray-400 hover:text-white">✕</button>
|
||||
</div>
|
||||
{drawer === 'workspace' && files.map(f => (
|
||||
<div key={f} className="text-sm text-indigo-300 py-1 cursor-pointer hover:text-indigo-200">📄 {f}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageBubble({ msg }: { msg: Message }) {
|
||||
const isUser = msg.role === 'user'
|
||||
const isMaster = msg.role === 'master'
|
||||
return (
|
||||
<div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
|
||||
{!isUser && (
|
||||
<div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold mr-2 flex-shrink-0 mt-1 ${isMaster ? 'bg-yellow-600' : 'bg-gray-600'}`}>
|
||||
{isMaster ? '👑' : msg.agent[0]?.toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className={`max-w-[75%] rounded-lg px-3 py-2 text-sm ${
|
||||
isUser ? 'bg-indigo-600 text-white' :
|
||||
isMaster ? 'bg-gray-700 border border-yellow-600/40' :
|
||||
'bg-gray-700'
|
||||
}`}>
|
||||
{!isUser && <div className="text-xs text-gray-400 mb-1">{msg.agent}</div>}
|
||||
<div className="prose prose-invert prose-sm max-w-none">
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>{msg.content}</ReactMarkdown>
|
||||
</div>
|
||||
{msg.streaming && <span className="inline-block w-1.5 h-3 bg-gray-400 animate-pulse ml-0.5" />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MemberItem({ name, role, status }: { name: string; role: string; status: string }) {
|
||||
const dot = status === 'thinking' ? 'bg-yellow-400' : status === 'working' ? 'bg-green-400 animate-pulse' : 'bg-gray-500'
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-1">
|
||||
<div className={`w-2 h-2 rounded-full ${dot}`} />
|
||||
<span className="text-sm">{role === 'master' ? '👑 ' : ''}{name}</span>
|
||||
<span className="text-xs text-gray-500 ml-auto">{status}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
65
web/src/components/MarketPage.tsx
Normal file
65
web/src/components/MarketPage.tsx
Normal file
@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useStore } from '../store'
|
||||
|
||||
const API = '/api'
|
||||
|
||||
export function MarketPage() {
|
||||
const { fetchAgents } = useStore()
|
||||
const [repo, setRepo] = useState('')
|
||||
const [status, setStatus] = useState<'idle' | 'loading' | 'done' | 'error'>('idle')
|
||||
const [errMsg, setErrMsg] = useState('')
|
||||
|
||||
const install = async () => {
|
||||
if (!repo.trim()) return
|
||||
setStatus('loading')
|
||||
try {
|
||||
const r = await fetch(`${API}/hub/install`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repo: repo.trim() })
|
||||
})
|
||||
if (!r.ok) { const d = await r.json(); throw new Error(d.error) }
|
||||
setStatus('done')
|
||||
fetchAgents()
|
||||
} catch (e: any) {
|
||||
setErrMsg(e.message)
|
||||
setStatus('error')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 p-8 overflow-y-auto">
|
||||
<h2 className="text-xl font-bold mb-2">人才市场</h2>
|
||||
<p className="text-gray-400 text-sm mb-6">从 GitHub 一键雇佣社区团队,或发布自己的团队供他人使用。</p>
|
||||
|
||||
<div className="bg-gray-800 rounded-lg p-6 max-w-lg mb-8">
|
||||
<h3 className="font-semibold mb-3">雇佣团队</h3>
|
||||
<p className="text-xs text-gray-400 mb-3">输入 GitHub repo(如 <code className="bg-gray-700 px-1 rounded">username/legal-team</code>)</p>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
className="flex-1 bg-gray-700 rounded px-3 py-2 text-sm outline-none"
|
||||
placeholder="username/repo 或完整 URL"
|
||||
value={repo}
|
||||
onChange={e => setRepo(e.target.value)}
|
||||
onKeyDown={e => e.key === 'Enter' && install()}
|
||||
/>
|
||||
<button onClick={install} disabled={status === 'loading'}
|
||||
className="bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 px-4 py-2 rounded text-sm">
|
||||
{status === 'loading' ? '安装中...' : '雇佣'}
|
||||
</button>
|
||||
</div>
|
||||
{status === 'done' && <p className="text-green-400 text-xs mt-2">✓ 安装成功</p>}
|
||||
{status === 'error' && <p className="text-red-400 text-xs mt-2">✗ {errMsg}</p>}
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-800 rounded-lg p-6 max-w-lg">
|
||||
<h3 className="font-semibold mb-3">发布团队</h3>
|
||||
<div className="text-sm text-gray-300 space-y-2">
|
||||
<p>1. 将你的 <code className="bg-gray-700 px-1 rounded">agents/</code> 和 <code className="bg-gray-700 px-1 rounded">skills/</code> 目录推送到 GitHub</p>
|
||||
<p>2. 在 repo 根目录添加 <code className="bg-gray-700 px-1 rounded">team.md</code> 描述团队</p>
|
||||
<p>3. 给 repo 添加 topic: <code className="bg-gray-700 px-1 rounded">agent-team</code></p>
|
||||
<p className="text-gray-400 text-xs mt-3">社区可通过 GitHub topic 发现你的团队</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
76
web/src/components/RoomSidebar.tsx
Normal file
76
web/src/components/RoomSidebar.tsx
Normal file
@ -0,0 +1,76 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useStore } from '../store'
|
||||
|
||||
const API = '/api'
|
||||
|
||||
export function RoomSidebar() {
|
||||
const { rooms, activeRoomId, setActiveRoom, fetchRooms, agents } = useStore()
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', type: 'dept', master: '', members: '' })
|
||||
|
||||
useEffect(() => { fetchRooms() }, [])
|
||||
|
||||
const create = async () => {
|
||||
await fetch(`${API}/rooms`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: form.name, type: form.type, master: form.master, members: form.members.split(',').map(s => s.trim()).filter(Boolean) })
|
||||
})
|
||||
setCreating(false)
|
||||
fetchRooms()
|
||||
}
|
||||
|
||||
const statusColor = (status: string) => {
|
||||
if (status === 'thinking') return 'bg-yellow-400'
|
||||
if (status === 'working') return 'bg-green-400 animate-pulse'
|
||||
return 'bg-gray-500'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-56 bg-gray-900 border-r border-gray-700 flex flex-col">
|
||||
<div className="p-3 border-b border-gray-700 flex items-center justify-between">
|
||||
<span className="font-bold text-sm">Agent Team</span>
|
||||
<button onClick={() => setCreating(!creating)} className="text-gray-400 hover:text-white text-lg leading-none">+</button>
|
||||
</div>
|
||||
|
||||
{creating && (
|
||||
<div className="p-3 border-b border-gray-700 space-y-2 text-xs">
|
||||
<input className="w-full bg-gray-700 rounded px-2 py-1" placeholder="群名称" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} />
|
||||
<select className="w-full bg-gray-700 rounded px-2 py-1" value={form.type} onChange={e => setForm(f => ({ ...f, type: e.target.value }))}>
|
||||
<option value="dept">部门群</option>
|
||||
<option value="leader">Leader 群</option>
|
||||
</select>
|
||||
<input className="w-full bg-gray-700 rounded px-2 py-1" placeholder="master agent 名" value={form.master} onChange={e => setForm(f => ({ ...f, master: e.target.value }))} />
|
||||
<input className="w-full bg-gray-700 rounded px-2 py-1" placeholder="成员(逗号分隔)" value={form.members} onChange={e => setForm(f => ({ ...f, members: e.target.value }))} />
|
||||
<button onClick={create} className="w-full bg-indigo-600 hover:bg-indigo-500 rounded py-1">创建</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-y-auto py-2">
|
||||
<div className="px-3 py-1 text-xs text-gray-500 uppercase">部门群</div>
|
||||
{rooms.filter(r => r.type === 'dept').map(r => (
|
||||
<RoomItem key={r.id} room={r} active={r.id === activeRoomId} onClick={() => setActiveRoom(r.id)} statusColor={statusColor(r.status)} />
|
||||
))}
|
||||
<div className="px-3 py-1 text-xs text-gray-500 uppercase mt-2">Leader 群</div>
|
||||
{rooms.filter(r => r.type === 'leader').map(r => (
|
||||
<RoomItem key={r.id} room={r} active={r.id === activeRoomId} onClick={() => setActiveRoom(r.id)} statusColor={statusColor(r.status)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RoomItem({ room, active, onClick, statusColor }: any) {
|
||||
return (
|
||||
<div onClick={onClick} className={`flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-700 ${active ? 'bg-gray-700' : ''}`}>
|
||||
<div className={`w-2 h-2 rounded-full flex-shrink-0 ${statusColor}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm truncate">{room.name}</div>
|
||||
{room.status !== 'pending' && (
|
||||
<div className="text-xs text-gray-400 truncate">
|
||||
{room.status === 'working' && room.activeAgent ? `${room.activeAgent} ${room.action || ''}` : room.status}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
3
web/src/index.css
Normal file
3
web/src/index.css
Normal file
@ -0,0 +1,3 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
body { margin: 0; }
|
||||
10
web/src/main.tsx
Normal file
10
web/src/main.tsx
Normal file
@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
105
web/src/store.ts
Normal file
105
web/src/store.ts
Normal file
@ -0,0 +1,105 @@
|
||||
import { create } from 'zustand'
|
||||
import { Room, Message, AgentInfo, SkillMeta, WsEvent } from './types'
|
||||
|
||||
interface AppState {
|
||||
rooms: Room[]
|
||||
activeRoomId: string | null
|
||||
messages: Record<string, Message[]>
|
||||
tasks: Record<string, string>
|
||||
workspace: Record<string, string[]>
|
||||
agents: AgentInfo[]
|
||||
skills: SkillMeta[]
|
||||
page: 'chat' | 'agents' | 'skills' | 'market'
|
||||
ws: Record<string, WebSocket>
|
||||
|
||||
setPage: (p: AppState['page']) => void
|
||||
setActiveRoom: (id: string) => void
|
||||
fetchRooms: () => Promise<void>
|
||||
fetchAgents: () => Promise<void>
|
||||
fetchSkills: () => Promise<void>
|
||||
sendMessage: (roomId: string, content: string) => void
|
||||
connectRoom: (roomId: string) => void
|
||||
}
|
||||
|
||||
const API = '/api'
|
||||
|
||||
export const useStore = create<AppState>((set, get) => ({
|
||||
rooms: [],
|
||||
activeRoomId: null,
|
||||
messages: {},
|
||||
tasks: {},
|
||||
workspace: {},
|
||||
agents: [],
|
||||
skills: [],
|
||||
page: 'chat',
|
||||
ws: {},
|
||||
|
||||
setPage: (page) => set({ page }),
|
||||
setActiveRoom: (id) => {
|
||||
set({ activeRoomId: id })
|
||||
get().connectRoom(id)
|
||||
fetch(`${API}/rooms/${id}/tasks`).then(r => r.json()).then(d => {
|
||||
set(s => ({ tasks: { ...s.tasks, [id]: d.content } }))
|
||||
})
|
||||
fetch(`${API}/rooms/${id}/workspace`).then(r => r.json()).then(files => {
|
||||
set(s => ({ workspace: { ...s.workspace, [id]: files || [] } }))
|
||||
})
|
||||
},
|
||||
|
||||
fetchRooms: async () => {
|
||||
const rooms = await fetch(`${API}/rooms`).then(r => r.json())
|
||||
set({ rooms: rooms || [] })
|
||||
},
|
||||
|
||||
fetchAgents: async () => {
|
||||
const agents = await fetch(`${API}/agents`).then(r => r.json())
|
||||
set({ agents: agents || [] })
|
||||
},
|
||||
|
||||
fetchSkills: async () => {
|
||||
const skills = await fetch(`${API}/skills`).then(r => r.json())
|
||||
set({ skills: skills || [] })
|
||||
},
|
||||
|
||||
connectRoom: (roomId) => {
|
||||
const { ws } = get()
|
||||
if (ws[roomId]) return
|
||||
const socket = new WebSocket(`ws://${location.host}/ws/${roomId}`)
|
||||
socket.onmessage = (e) => {
|
||||
const ev: WsEvent = JSON.parse(e.data)
|
||||
if (ev.type === 'agent_message') {
|
||||
set(s => {
|
||||
const msgs = [...(s.messages[roomId] || [])]
|
||||
const last = msgs[msgs.length - 1]
|
||||
if (last?.streaming && last.agent === ev.agent) {
|
||||
msgs[msgs.length - 1] = { ...last, content: last.content + ev.content, streaming: ev.streaming }
|
||||
} else {
|
||||
msgs.push({ id: Date.now().toString(), agent: ev.agent, role: ev.role, content: ev.content, streaming: ev.streaming })
|
||||
}
|
||||
return { messages: { ...s.messages, [roomId]: msgs } }
|
||||
})
|
||||
} else if (ev.type === 'room_status') {
|
||||
set(s => ({
|
||||
rooms: s.rooms.map(r => r.id === roomId
|
||||
? { ...r, status: ev.status, activeAgent: ev.active_agent, action: ev.action }
|
||||
: r)
|
||||
}))
|
||||
} else if (ev.type === 'tasks_update') {
|
||||
set(s => ({ tasks: { ...s.tasks, [roomId]: ev.content } }))
|
||||
} else if (ev.type === 'workspace_file') {
|
||||
set(s => ({
|
||||
workspace: { ...s.workspace, [roomId]: [...(s.workspace[roomId] || []), ev.filename] }
|
||||
}))
|
||||
}
|
||||
}
|
||||
set(s => ({ ws: { ...s.ws, [roomId]: socket } }))
|
||||
},
|
||||
|
||||
sendMessage: (roomId, content) => {
|
||||
const { ws, messages } = get()
|
||||
// Add user message locally
|
||||
const userMsg = { id: Date.now().toString(), agent: 'user', role: 'user' as const, content }
|
||||
set(s => ({ messages: { ...s.messages, [roomId]: [...(s.messages[roomId] || []), userMsg] } }))
|
||||
ws[roomId]?.send(JSON.stringify({ type: 'user_message', content }))
|
||||
},
|
||||
}))
|
||||
37
web/src/types.ts
Normal file
37
web/src/types.ts
Normal file
@ -0,0 +1,37 @@
|
||||
export type RoomStatus = 'pending' | 'thinking' | 'working'
|
||||
export type RoomType = 'dept' | 'leader'
|
||||
|
||||
export interface Room {
|
||||
id: string
|
||||
name: string
|
||||
type: RoomType
|
||||
status: RoomStatus
|
||||
master: string
|
||||
activeAgent?: string
|
||||
action?: string
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: string
|
||||
agent: string
|
||||
role: 'user' | 'master' | 'member'
|
||||
content: string
|
||||
streaming?: boolean
|
||||
}
|
||||
|
||||
export interface AgentInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface SkillMeta {
|
||||
name: string
|
||||
description: string
|
||||
path: string
|
||||
}
|
||||
|
||||
export type WsEvent =
|
||||
| { type: 'agent_message'; agent: string; role: 'master' | 'member'; content: string; streaming: boolean }
|
||||
| { type: 'room_status'; status: RoomStatus; active_agent?: string; action?: string }
|
||||
| { type: 'task_assign'; from: string; to: string; task: string }
|
||||
| { type: 'tasks_update'; content: string }
|
||||
| { type: 'workspace_file'; filename: string; content: string }
|
||||
28
web/tsconfig.app.json
Normal file
28
web/tsconfig.app.json
Normal file
@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
web/tsconfig.json
Normal file
7
web/tsconfig.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
web/tsconfig.node.json
Normal file
26
web/tsconfig.node.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
13
web/vite.config.ts
Normal file
13
web/vite.config.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
'/ws': { target: 'ws://localhost:8080', ws: true },
|
||||
}
|
||||
}
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user