Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(assistant): install shared skills on every conversation turn (#902)
crispinhu271535886effb8
diff --git a/internal/httpapi/assistant_subagents.go b/internal/httpapi/assistant_subagents.goindex 32d9cb06..c407ebe2 100644--- a/internal/httpapi/assistant_subagents.go+++ b/internal/httpapi/assistant_subagents.go@@ -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@@ -202,16 +205,21 @@ func (h *assistantHandlers) writeConversationAssets(root string, req assistantRefiles[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 {@@ -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 = niladd(skill, contents)}engine, _ := assistantModelEngine(req.Model)diff --git a/internal/httpapi/assistant_subagents_test.go b/internal/httpapi/assistant_subagents_test.goindex 6990565a..1b6f3f9f 100644--- a/internal/httpapi/assistant_subagents_test.go+++ b/internal/httpapi/assistant_subagents_test.go@@ -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")@@ -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")@@ -174,7 +186,9 @@ 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"} {@@ -182,6 +196,9 @@ func TestSkillMentionsAreScopedHintedAndWrittenToHome(t *testing.T) {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)@@ -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" {diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.goindex 2e8b9a20..353be25b 100644--- a/internal/httpapi/assistant_task_engines_test.go+++ b/internal/httpapi/assistant_task_engines_test.go@@ -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/shskills=$(ls "$HOME/.codebuddy/skills" 2>/dev/null | tr '\n' ' ')@@ -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)}}diff --git a/web/app/assets.js b/web/app/assets.jsindex 7207bca8..495e08a6 100644--- a/web/app/assets.js+++ b/web/app/assets.js@@ -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))}@@ -237,9 +237,13 @@ 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)});@@ -247,7 +251,7 @@ async function toggleAssetShare(id){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]||''}diff --git a/web/app/sops.js b/web/app/sops.jsindex 84ea05e9..e59d38b9 100644--- a/web/app/sops.js+++ b/web/app/sops.js@@ -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})}diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 0da428f2..34ff798b 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -180,3 +180,4 @@ Object.assign(window.LF_I18N_EN,{"外部原单会保留,后续同步可能重新导入。":"The original external record is kept, and a later sync may import it again.","需求已有执行记录或已完成,请确认强制删除":"This requirement has execution history or is already completed. Confirm force deletion."});+Object.assign(window.LF_I18N_EN,{"查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。": "Skills shared by other projects. Shared Skills are read-only, are installed automatically into every conversation and scheduled task on the platform, and can be bound to Roles in this project.", "共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?": "Once shared, this Skill is installed automatically into every user's conversations and scheduled tasks on the platform (including other projects and conversations without a project), and the model can call it directly. Continue?", "共享这个角色会同时共享它绑定的技能:": "Sharing this Role also shares the Skills bound to it: ", "已共享,所有对话和定时任务会自动装入": "Shared. Every conversation and scheduled task will install it automatically", "其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话": "Other projects can pick it under Shared roles; the project Skills bound to it are shared too and installed into every conversation automatically", "共享技能": "Share Skill"});diff --git a/web/index.html b/web/index.htmlindex 22fa1233..4d3fe37e 100644--- a/web/index.html+++ b/web/index.html@@ -893,7 +893,7 @@</div></div><label class="as-field" id="agentModelCustomField" hidden><span>自定义模型 ID <small>使用自定义 Base URL 时,填服务商提供的模型名</small></span><input name="model" placeholder="例如:gpt-5.6-terra"></label>- <label class="as-switch-row agent-edit-only"><span><b>共享给其他项目</b><small>其他项目可在「共享角色」里选用</small></span><input name="shared" type="checkbox" role="switch"></label>+ <label class="as-switch-row agent-edit-only"><span><b>共享给其他项目</b><small>其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话</small></span><input name="shared" type="checkbox" role="switch"></label></div></section><section class="as-pane wizard-pane" data-agent-pane="create-review">