Skip to content
Merged
54 changes: 37 additions & 17 deletions internal/httpapi/assistant_subagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,14 @@ func subagentRolePrompt(prompt string) string {
var rolePromptPlaceholder = regexp.MustCompile(`\{\{[^{}]+\}\}`)

// writeConversationAssets rewrites the conversation's CLI home each turn:
// .codebuddy/skills holds the project's skills plus those of its roles and
// the mentioned ones, and
// .codebuddy/agents holds one subagent per role, so Main Bot and its
// subagents use them natively. A conversation without a project and without
// mentioned shared roles gets empty directories.
// skills holds the project's own skills and the shared skills, plus those of
// its roles and the mentioned ones, and agents holds one subagent per role,
// so Main Bot and its subagents use them natively. Every shared skill is
// installed on every turn, including a conversation without a project, so a
// scheduled task can call one without mentioning it; it brings only its
// SKILL.md unless it is also the project's own, bound or mentioned. A turn
// with no project, no shared skills and no mentioned roles gets empty
// directories.
func (h *assistantHandlers) writeConversationAssets(root string, req assistantRequest) error {
if err := runtime.ValidateConversationRoot(root); err != nil {
return err
Expand All @@ -202,16 +205,21 @@ func (h *assistantHandlers) writeConversationAssets(root string, req assistantRe
files[skill.ID] = contents
}
}
if project := strings.TrimSpace(req.ProjectID); project != "" {
for _, skill := range h.repo.Skills() {
if skill.ProjectID != project {
continue
}
var contents map[string][]byte
if len(skill.FileRefs) > 0 {
contents = h.repo.SkillFileContents(skill.ID)
}
add(skill, contents)
project := strings.TrimSpace(req.ProjectID)
load := func(skill domain.SkillDefinition) {
var contents map[string][]byte
if len(skill.FileRefs) > 0 {
contents = h.repo.SkillFileContents(skill.ID)
}
add(skill, contents)
}
var shared []domain.SkillDefinition
for _, skill := range h.repo.Skills() {
switch {
case project != "" && skill.ProjectID == project:
load(skill)
case skill.Shared:
shared = append(shared, skill)
}
}
for _, role := range req.roles {
Expand All @@ -220,10 +228,22 @@ func (h *assistantHandlers) writeConversationAssets(root string, req assistantRe
}
}
for _, skill := range req.skills {
load(skill)
}
// A shared skill nobody bound or mentioned gets only its SKILL.md: its
// other files would be copied into every conversation on the platform
// each turn. Mentioning it or binding it to a role installs them.
sort.Slice(shared, func(i, j int) bool { return shared[i].ID < shared[j].ID })
for _, skill := range shared {
if seen[skill.ID] {
continue
}
var contents map[string][]byte
if len(skill.FileRefs) > 0 {
contents = h.repo.SkillFileContents(skill.ID)
if data, ok := h.repo.SkillFileContent(skill.ID, "SKILL.md"); ok {
contents = map[string][]byte{"SKILL.md": data}
}
skill.Files = nil
skill.FileRefs = nil
add(skill, contents)
}
engine, _ := assistantModelEngine(req.Model)
Expand Down
160 changes: 156 additions & 4 deletions internal/httpapi/assistant_subagents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,22 @@ import (
"testing"

"agentflow/internal/domain"
"agentflow/internal/repo"
)

func TestPersonalConversationRunsInItsOwnRootWithProjectSkills(t *testing.T) {
h, u := workbenchFixture(t)
if err := h.repo.PutSkill(domain.SkillDefinition{ID: "notes", Name: "notes", ProjectID: "workbench", Content: "记录要点"}); err != nil {
if err := h.repo.PutProject(domain.Project{ID: "other", Name: "Other", OwnerID: u.ID}); err != nil {
t.Fatal(err)
}
for _, skill := range []domain.SkillDefinition{
{ID: "notes", Name: "notes", ProjectID: "workbench", Content: "记录要点"},
{ID: "shared-notes", Name: "shared-notes", ProjectID: "other", Shared: true, Content: "共享要点"},
} {
if err := h.repo.PutSkill(skill); err != nil {
t.Fatal(err)
}
}
root := t.TempDir()
bin := filepath.Join(root, "codebuddy")
homeFile := filepath.Join(root, "home")
Expand Down Expand Up @@ -53,8 +62,11 @@ printf '%s\n' '{"type":"result","result":"好"}'
if other == home || strings.HasPrefix(other, assistantCLIHome(u.ID)) {
t.Fatalf("conversations share a CLI home: %s", other)
}
if entries, _ := os.ReadDir(filepath.Join(other, ".codebuddy", "skills")); len(entries) != 0 {
t.Fatal("a conversation without a project received project skills")
if _, err := os.Stat(filepath.Join(other, ".codebuddy", "skills", "notes", "SKILL.md")); !os.IsNotExist(err) {
t.Fatal("a conversation without a project received a project skill", err)
}
if _, err := os.Stat(filepath.Join(other, ".codebuddy", "skills", "shared-notes", "SKILL.md")); err != nil {
t.Fatal("a conversation without a project did not receive the shared skill", err)
}
if assistantConversationRoot(u.ID, "same") == assistantConversationRoot(u.ID+1, "same") {
t.Fatal("a reused session ID reaches another user's root")
Expand Down Expand Up @@ -174,14 +186,19 @@ func TestSkillMentionsAreScopedHintedAndWrittenToHome(t *testing.T) {
t.Fatalf("skill hint missing: %s", req.contextText)
}
root := t.TempDir()
if err := h.writeConversationAssets(root, req); err != nil {
// Sharing installs the skill on a project turn that never mentions it.
plain := assistantRequest{ProjectID: "workbench", Messages: []assistantMessage{{Role: "user", Content: "写一下"}}}
if err := h.writeConversationAssets(root, plain); err != nil {
t.Fatal(err)
}
for _, name := range []string{"lint", "shareddoc"} {
if _, err := os.Stat(filepath.Join(root, "home", ".codebuddy", "skills", name, "SKILL.md")); err != nil {
t.Fatalf("skill %s not written: %v", name, err)
}
}
if _, err := os.Stat(filepath.Join(root, "home", ".codebuddy", "skills", "deploy", "SKILL.md")); !os.IsNotExist(err) {
t.Fatalf("another project's private skill was installed: %v", err)
}
req.Messages[0].References = []domain.AssistantReference{{Type: "skill", ID: "deploy"}}
if err := h.prepareWorkbenchContext(c, &req, u); err != errForeignReference {
t.Fatalf("another project's skill accepted: %v", err)
Expand All @@ -193,6 +210,141 @@ func TestSkillMentionsAreScopedHintedAndWrittenToHome(t *testing.T) {
}
}

// Every shared skill on the platform reaches the CLI home, whichever project
// owns it, while private skills of other projects stay out; a conversation
// without a project gets the same shared set. A shared skill nobody mentioned
// brings only its SKILL.md; mentioning it installs its other files too.
func TestEverySharedSkillIsInstalledWithItsSkillMD(t *testing.T) {
h, u := workbenchFixture(t)
for _, project := range []string{"docs", "ops"} {
if err := h.repo.PutProject(domain.Project{ID: project, Name: project, OwnerID: u.ID}); err != nil {
t.Fatal(err)
}
}
runbook := domain.SkillDefinition{ID: "ops-runbook", Name: "ops-runbook", ProjectID: "ops", Shared: true, Content: "runbook", Files: map[string]string{"scripts/check.sh": "echo ok"}}
for _, skill := range []domain.SkillDefinition{
{ID: "own", Name: "own", ProjectID: "workbench", Content: "own"},
{ID: "docs-writer", Name: "docs-writer", ProjectID: "docs", Shared: true, Content: "write"},
{ID: "docs-draft", Name: "docs-draft", ProjectID: "docs", Content: "draft"},
runbook,
{ID: "ops-secret", Name: "ops-secret", ProjectID: "ops", Content: "secret"},
} {
if err := h.repo.PutSkill(skill); err != nil {
t.Fatal(err)
}
}
asset := []byte{0, 1, 2, 255}
skillMD := []byte("---\nname: ops-runbook\ndescription: run the ops checks\n---\nRun scripts/check.sh.\n")
if err := h.repo.PutSkillFiles("ops-runbook", []repo.SkillFileInput{
{Path: "SKILL.md", Content: skillMD, Mode: 0o644},
{Path: "assets/check.bin", Content: asset, Mode: 0o644},
}); err != nil {
t.Fatal(err)
}
stored, ok := h.repo.Skill("ops-runbook")
if !ok {
t.Fatal("ops-runbook not stored")
}
// The test store also seeds the platform's shared skills; they must be
// installed too, so only the skills created here are pinned.
for project, want := range map[string]map[string]bool{
"workbench": {"own": true, "docs-writer": true, "ops-runbook": true, "repository-navigation": true, "docs-draft": false, "ops-secret": false},
"": {"own": false, "docs-writer": true, "ops-runbook": true, "repository-navigation": true, "docs-draft": false, "ops-secret": false},
} {
for _, mentioned := range []bool{false, true} {
req := assistantRequest{ProjectID: project}
if mentioned {
req.skills = []domain.SkillDefinition{stored}
}
root := t.TempDir()
if err := h.writeConversationAssets(root, req); err != nil {
t.Fatal(err)
}
dir := filepath.Join(root, "home", ".codebuddy", "skills")
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, entry := range entries {
got[entry.Name()] = true
}
for name, installed := range want {
if got[name] != installed {
t.Fatalf("project %q skill %s installed=%v, want %v (all: %v)", project, name, got[name], installed, got)
}
}
if data, err := os.ReadFile(filepath.Join(dir, "ops-runbook", "SKILL.md")); err != nil || !bytes.Contains(data, []byte("Run scripts/check.sh.")) {
t.Fatalf("project %q mentioned=%v shared SKILL.md = %q %v", project, mentioned, data, err)
}
for path, content := range map[string][]byte{"assets/check.bin": asset, "scripts/check.sh": []byte("echo ok")} {
data, err := os.ReadFile(filepath.Join(dir, "ops-runbook", filepath.FromSlash(path)))
if mentioned && (err != nil || !bytes.Equal(data, content)) {
t.Fatalf("project %q mentioned shared skill file %s = %v %v", project, path, data, err)
}
if !mentioned && !os.IsNotExist(err) {
t.Fatalf("project %q unmentioned shared skill file %s was installed: %v", project, path, err)
}
}
}
}
}

func TestEverySharedSkillIsInstalledHoweverManyAreShared(t *testing.T) {
h, u := workbenchFixture(t)
if err := h.repo.PutProject(domain.Project{ID: "docs", Name: "docs", OwnerID: u.ID}); err != nil {
t.Fatal(err)
}
if err := h.repo.PutSkill(domain.SkillDefinition{ID: "own", Name: "own", ProjectID: "workbench", Content: "own"}); err != nil {
t.Fatal(err)
}
if err := h.repo.PutSkill(domain.SkillDefinition{ID: "docs-private", Name: "docs-private", ProjectID: "docs", Content: "private"}); err != nil {
t.Fatal(err)
}
// More shared skills than the 50 an earlier revision installed, so a
// skill late in id order (the one a scheduled task needs) is still there.
for i := 0; i < 120; i++ {
id := fmt.Sprintf("zz-shared-%03d", i)
if err := h.repo.PutSkill(domain.SkillDefinition{ID: id, Name: id, ProjectID: "docs", Shared: true, Content: id}); err != nil {
t.Fatal(err)
}
}
var shared []string
for _, skill := range h.repo.Skills() {
if skill.Shared && skill.ProjectID != "workbench" {
shared = append(shared, skill.ID)
}
}
if len(shared) < 120 {
t.Fatalf("fixture has %d shared skills, want at least 120", len(shared))
}
for _, project := range []string{"workbench", ""} {
root := t.TempDir()
if err := h.writeConversationAssets(root, assistantRequest{ProjectID: project}); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(filepath.Join(root, "home", ".codebuddy", "skills"))
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, entry := range entries {
got[entry.Name()] = true
}
if got["own"] != (project == "workbench") {
t.Fatalf("project %q own skill installed=%v", project, got["own"])
}
if got["docs-private"] {
t.Fatalf("project %q installed another project's private skill", project)
}
for _, id := range shared {
if !got[id] {
t.Fatalf("project %q shared skill %s not installed (installed %d of %d)", project, id, len(got), len(shared))
}
}
}
}

func TestSubagentStreamEventsCarryTheirDispatch(t *testing.T) {
dispatch := assistantStreamEvents(`{"type":"assistant","message":{"content":[{"type":"tool_use","id":"call-1","name":"Agent","input":{"subagent_type":"role-qa","description":"补单测","prompt":"x"}}]}}`)
if len(dispatch) != 1 || dispatch[0].Subagent != "role-qa" || dispatch[0].Parent != "" || dispatch[0].Input != "x" {
Expand Down
20 changes: 15 additions & 5 deletions internal/httpapi/assistant_task_engines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,23 @@ func TestScheduleJobAssistantUserNeedsModelCLIKey(t *testing.T) {
}
}

// A scheduled run sees the project's skills in its CLI home, as a chat turn
// does, so the CLI's skill tool can load them.
// A scheduled run sees the project's skills and every shared skill in its CLI
// home, as a chat turn does, so the CLI's skill tool can load them. Another
// project's private skill stays out.
func TestScheduledTaskWritesProjectSkills(t *testing.T) {
h, user := workbenchFixture(t)
if err := h.repo.PutSkill(domain.SkillDefinition{ID: "repo-reader", Name: "repo-reader", ProjectID: "workbench", Description: "读取仓库", Content: "# repo-reader\n读取仓库内容"}); err != nil {
if err := h.repo.PutProject(domain.Project{ID: "other", Name: "Other"}); err != nil {
t.Fatal(err)
}
for _, skill := range []domain.SkillDefinition{
{ID: "repo-reader", Name: "repo-reader", ProjectID: "workbench", Description: "读取仓库", Content: "# repo-reader\n读取仓库内容"},
{ID: "golang-defect-scanner", Name: "golang静态扫描", ProjectID: "other", Shared: true, Content: "# scan\n扫描"},
{ID: "private-scanner", Name: "私有扫描", ProjectID: "other", Content: "# private\n不可见"},
} {
if err := h.repo.PutSkill(skill); err != nil {
t.Fatal(err)
}
}
bin := filepath.Join(t.TempDir(), "codebuddy")
script := `#!/bin/sh
skills=$(ls "$HOME/.codebuddy/skills" 2>/dev/null | tr '\n' ' ')
Expand All @@ -128,8 +138,8 @@ printf '{"type":"result","result":"skills: %s"}\n' "$skills"
if err := h.executeAssistantTask(context.Background(), user, &task); err != nil {
t.Fatalf("run = %v %+v", err, task)
}
if !strings.Contains(task.LastMessage, "repo-reader") {
t.Fatalf("CLI home lacks the project skill: %q", task.LastMessage)
if !strings.Contains(task.LastMessage, "repo-reader") || !strings.Contains(task.LastMessage, "golang-defect-scanner") || strings.Contains(task.LastMessage, "private-scanner") {
t.Fatalf("CLI home skills = %q", task.LastMessage)
}
}

Expand Down
8 changes: 6 additions & 2 deletions web/app/assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function assetPageCopy(type=state.assetType){
sandboxes:{group:'运行环境',page:'环境资产',tab:'沙箱',desc:'维护当前项目的运行隔离方式及环境依赖。',create:'新建沙箱'}
})[type]||{group:'运行环境',page:'环境资产',tab:'Dockerfile',desc:'维护当前项目的容器构建定义。',create:'新建 Dockerfile'};
}
function assetSharedDescription(type=state.assetType){return type==='rules'?'查看其他项目共享的规则;共享规则只读,可直接绑定到本项目角色。':type==='skills'?'查看其他项目共享的技能;共享技能只读,可直接绑定到本项目角色。':'查看其他项目共享的环境资产;共享资产只读,可直接用于本项目。'}
function assetSharedDescription(type=state.assetType){return type==='rules'?'查看其他项目共享的规则;共享规则只读,可直接绑定到本项目角色。':type==='skills'?'查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。':'查看其他项目共享的环境资产;共享资产只读,可直接用于本项目。'}
function assetIconName(type=state.assetType){return ({rules:'gate',skills:'skills',dockerfiles:'layers',environments:'terminal',sandboxes:'server'})[type]||'layers'}
function assetRefIconName(type=state.assetType){return ({rules:'robot',skills:'robot',dockerfiles:'server',environments:'server',sandboxes:'workflow'})[type]||'layers'}
function assetScopeItems(scope){return (state.data[state.assetType]||[]).filter(item=>scope==='shared'?catalogShared(item.projectId,item.shared):catalogOwned(item.projectId))}
Expand Down Expand Up @@ -237,17 +237,21 @@ async function closeAssetDetail({force=false}={}){
scrollAssetTop();
return true;
}
// A shared skill is installed into every conversation and scheduled task on
// the platform, not only offered for binding, so sharing one asks first.
const SHARED_SKILL_NOTICE='共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?';
async function toggleAssetShare(id){
const item=(state.data[state.assetType]||[]).find(x=>x.id===id);
if(!item||!catalogOwned(item.projectId))return toast('只能共享本项目的资产');
if(!item.shared&&state.assetType==='skills'&&!(await afConfirm({title:'共享技能',message:SHARED_SKILL_NOTICE,confirmText:'共享'})))return;
try{
const saved={...item,shared:!item.shared};
await api(`/api/${state.assetType}`,{method:'PUT',body:JSON.stringify(saved)});
Object.assign(item,saved);
if(state.selectedAsset===id){renderAssetDetailHead(item);refreshAssetAside(item)}
else renderAssets();
const agent=state.data.agents.find(a=>a.id===state.selectedAgent)||state.agentDraft;if(agent)renderAgentAssetsPanel(agent);
toast(saved.shared?'已共享,其他项目可绑定':'已取消共享');
toast(saved.shared?(state.assetType==='skills'?'已共享,所有对话和定时任务会自动装入':'已共享,其他项目可绑定'):'已取消共享');
}catch(e){toast(e.message)}
}
function assetEmptyHint(){return ({rules:'规则是写给 Agent 的行为约束,例如编码规范、禁止事项。建好后在「角色定义」里绑定到角色。',skills:'技能是 Agent 可按需加载的说明和附加文件,例如某个框架的操作手册。建好后在「角色定义」里绑定到角色。',dockerfiles:'Dockerfile 定义沙箱容器的镜像。建好后在「沙箱管理」里选用;也可以直接用「共享」里的现成配置。',environments:'安装脚本在沙箱初始化时把工具装进隔离环境,例如指定版本的 Go、PHP、Node。建好后在「沙箱管理」里选用。',sandboxes:'沙箱决定 SOP 节点在什么隔离环境里执行,由 Dockerfile 和安装脚本组合而成。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。'})[state.assetType]||''}
Expand Down
6 changes: 6 additions & 0 deletions web/app/sops.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ async function toggleShare(kind,id){
try{
const full=await catalogItemFull(kind,id);
if(!catalogOwned(full.projectId))return toast('只能共享本项目的内容');
// Sharing a role also shares the project's skills bound to it, and a
// shared skill is installed into every conversation, so name them first.
// The list is reloaded: a skill may have been added since the page loaded.
if(kind==='agent'&&!full.shared&&(full.skills||[]).length)state.data.skills=await api('/api/skills',{silent:true});
const newlyShared=kind==='agent'&&!full.shared?(state.data.skills||[]).filter(s=>(full.skills||[]).includes(s.id)&&s.projectId===full.projectId&&!s.shared):[];
if(newlyShared.length&&!(await afConfirm({title:'共享角色',message:`共享这个角色会同时共享它绑定的技能:${newlyShared.map(s=>s.name||s.id).join('、')}。${SHARED_SKILL_NOTICE}`,confirmText:'共享'})))return;
const saved=await api(kind==='workflow'?'/api/workflows':'/api/agents',{method:'PUT',body:JSON.stringify({...full,shared:!full.shared})});
replaceCatalogItem(kind,saved);
if(kind==='agent'&&saved.shared){(state.data.rules||[]).forEach(item=>{if((saved.rules||[]).includes(item.id)&&item.projectId===saved.projectId)item.shared=true});(state.data.skills||[]).forEach(item=>{if((saved.skills||[]).includes(item.id)&&item.projectId===saved.projectId)item.shared=true})}
Expand Down
Loading
Loading