From d9bd19750c414db28b48bb7f6ae23438a129c730 Mon Sep 17 00:00:00 2001 From: Robert0622 <53806540+Robert0622@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:28:51 +0800 Subject: [PATCH 1/4] feat(assets): add project asset bundle import and export --- docs/api/README.md | 3 + docs/api/openapi.yaml | 169 +++++++++++ docs/api/registry.md | 24 ++ internal/domain/asset_bundle.go | 47 +++ internal/engine/workflow_graph.go | 5 + internal/httpapi/asset_bundle.go | 137 +++++++++ internal/httpapi/asset_bundle_test.go | 248 ++++++++++++++++ internal/httpapi/server.go | 7 +- internal/repo/asset_bundle_export.go | 251 ++++++++++++++++ internal/repo/asset_bundle_import.go | 413 ++++++++++++++++++++++++++ web/app/asset-bundle.css | 56 ++++ web/app/asset-bundle.js | 180 +++++++++++ web/i18n-en.js | 10 + web/index.html | 24 +- 14 files changed, 1572 insertions(+), 2 deletions(-) create mode 100644 internal/domain/asset_bundle.go create mode 100644 internal/httpapi/asset_bundle.go create mode 100644 internal/httpapi/asset_bundle_test.go create mode 100644 internal/repo/asset_bundle_export.go create mode 100644 internal/repo/asset_bundle_import.go create mode 100644 web/app/asset-bundle.css create mode 100644 web/app/asset-bundle.js diff --git a/docs/api/README.md b/docs/api/README.md index b559fbf69..4c65cb1fe 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -107,6 +107,9 @@ curl -H "Authorization: Bearer $AGENTFLOW_TOKEN" "$AGENTFLOW_URL/api/health" | `GET`, `PUT`, `DELETE` | `/api/skills` | | `GET`, `PUT` | `/api/mcp-servers` | | `POST` | `/api/mcp-servers/import` | +| `POST` | `/api/projects/{id}/asset-bundles/export` | +| `POST` | `/api/projects/{id}/asset-bundles/preview` | +| `POST` | `/api/projects/{id}/asset-bundles/import` | | `GET` | `/api/executors` | | `GET`, `PUT`, `DELETE` | `/api/sandboxes` | diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index 310154d92..f19de971d 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -1935,6 +1935,117 @@ paths: $ref: "#/components/responses/NotFound" "409": $ref: "#/components/responses/Conflict" + /api/projects/{projectId}/asset-bundles/export: + parameters: + - name: projectId + in: path + required: true + schema: {type: string} + post: + tags: [Assets] + operationId: exportProjectAssetBundle + description: Export the selected assets and their project-owned dependencies. Requires a project owner, maintainer, or platform administrator. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [assets] + properties: + assets: + type: array + minItems: 1 + maxItems: 200 + items: + type: object + required: [kind, id] + properties: + kind: {type: string, enum: [skill, mcp, agent, sop]} + id: {type: string} + responses: + "200": + description: Versioned JSON bundle including asset definitions and attachments + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectAssetBundle" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + "404": + $ref: "#/components/responses/NotFound" + "413": + description: Bundle exceeds the size limit + /api/projects/{projectId}/asset-bundles/preview: + parameters: + - name: projectId + in: path + required: true + schema: {type: string} + post: + tags: [Assets] + operationId: previewProjectAssetBundle + description: Validate a bundle and preview assets and connection setup without writing to the project. Requires a project owner, maintainer, or platform administrator. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectAssetBundle" + responses: + "200": + description: Asset list and connections to configure + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectAssetBundleResult" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + "404": + $ref: "#/components/responses/NotFound" + "413": + description: Bundle exceeds the size limit + /api/projects/{projectId}/asset-bundles/import: + parameters: + - name: projectId + in: path + required: true + schema: {type: string} + post: + tags: [Assets] + operationId: importProjectAssetBundle + description: Create the project-owned copies in one transaction and rebind their references. LOOPs start as drafts. Requires a project owner, maintainer, or platform administrator. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectAssetBundle" + responses: + "201": + description: Asset list and connections to configure + content: + application/json: + schema: + $ref: "#/components/schemas/ProjectAssetBundleResult" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + "404": + $ref: "#/components/responses/NotFound" + "413": + description: Bundle exceeds the size limit /api/projects/{projectId}/restore: parameters: - name: projectId @@ -5159,6 +5270,64 @@ components: model: {type: string, description: Concrete model ID on the executor.} effort: {type: string, description: The selected model's reasoning effort.} approval: {type: string, enum: [confirm, assisted, auto], description: Initial confirmation mode for new conversations.} + ProjectAssetBundle: + type: object + required: [format] + properties: + format: + const: loopforge.project-assets/v1 + skills: + type: array + items: + $ref: "#/components/schemas/OpenObject" + mcpServers: + type: array + items: + $ref: "#/components/schemas/OpenObject" + agents: + type: array + items: + $ref: "#/components/schemas/OpenObject" + workflows: + type: array + items: + $ref: "#/components/schemas/OpenObject" + rules: + type: array + items: + $ref: "#/components/schemas/OpenObject" + sandboxes: + type: array + items: + $ref: "#/components/schemas/OpenObject" + bindings: + type: array + items: + $ref: "#/components/schemas/ProjectAssetBundleBinding" + ProjectAssetBundleBinding: + type: object + required: [kind, assetId] + properties: + kind: {type: string} + assetId: {type: string} + ProjectAssetBundleResult: + type: object + required: [assets] + properties: + assets: + type: array + items: + type: object + required: [kind, id, name] + properties: + kind: {type: string} + id: {type: string} + name: {type: string} + targetId: {type: string} + bindings: + type: [array, "null"] + items: + $ref: "#/components/schemas/ProjectAssetBundleBinding" OpenObject: type: object additionalProperties: true diff --git a/docs/api/registry.md b/docs/api/registry.md index 0608cdfb9..0c5b839f9 100644 --- a/docs/api/registry.md +++ b/docs/api/registry.md @@ -169,6 +169,30 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \ "$AGENTFLOW_URL/api/mcp-servers/import" ``` +## 项目资产包 + +LOOP 库右上角的「资产包」可单选或批量选择本项目的 Skill、MCP、角色和 LOOP。项目所有者、项目管理员和平台管理员可以导入导出。 + +### `POST /api/projects/{id}/asset-bundles/export` + +请求体的 `assets` 为所选资产数组。`kind` 支持 `skill`、`mcp`、`agent`、`sop`。 + +```json +{"assets":[{"kind":"sop","id":"review-sop"},{"kind":"skill","id":"check-rules"}]} +``` + +返回 `loopforge.project-assets/v1` JSON 文件,包含当前定义、附件和同项目依赖,包括角色引用的规则、LOOP 引用的子 LOOP,以及自定义沙箱及其 Dockerfile 构建上下文。平台内置沙箱使用目标环境中的对应配置。其他项目资产和平台通用模板需要先复制到当前项目。 + +### `POST /api/projects/{id}/asset-bundles/preview` + +请求体为整个资产包。成功时返回 `assets` 清单和 `bindings` 重配项(包含 `kind` 和 `assetId`),此请求不写入项目。附件校验 SHA‑256 和路径。包最多包含 200 项资产及依赖、64 MiB 附件和 96 MiB JSON。 + +### `POST /api/projects/{id}/asset-bundles/import` + +请求体与预览相同。成功返回 `201`,`assets` 中包含各项的 `targetId`。资产包整体导入为项目私有副本并自动重绑包内引用。LOOP 保存为草稿,有子 LOOP 时按依赖顺序重配连接和发布。每次导入创建一套新副本。 + +项目 MCP 的 Headers、环境变量值、URL 中的认证信息和查询参数,以及项目凭据、知识库和通知绑定需要在目标项目重配。Skill 与 MCP 附件按原始字节导出。只在受信任项目间交付经过审查的资产包,正文和可执行文件中的自带内容会随包迁移。 + ## 执行器 ### `GET /api/executors` diff --git a/internal/domain/asset_bundle.go b/internal/domain/asset_bundle.go new file mode 100644 index 000000000..7ba4bf2a7 --- /dev/null +++ b/internal/domain/asset_bundle.go @@ -0,0 +1,47 @@ +package domain + +const ProjectAssetBundleFormat = "loopforge.project-assets/v1" + +type BundleAssetRef struct { + Kind string `json:"kind"` + ID string `json:"id"` +} + +type BundleAssetFile struct { + Path string `json:"path"` + Content []byte `json:"content"` + Mode uint32 `json:"mode"` + SHA256 string `json:"sha256"` +} + +type BundleSkill struct { + SkillDefinition + Attachments []BundleAssetFile `json:"attachments,omitempty"` +} + +type BundleMCPServer struct { + MCPServerDefinition + Attachments []BundleAssetFile `json:"attachments,omitempty"` +} + +type ProjectAssetBundle struct { + Format string `json:"format"` + Skills []BundleSkill `json:"skills,omitempty"` + MCPServers []BundleMCPServer `json:"mcpServers,omitempty"` + Agents []AgentDefinition `json:"agents,omitempty"` + Workflows []WorkflowDefinition `json:"workflows,omitempty"` + Rules []RuleDefinition `json:"rules,omitempty"` + Sandboxes []SandboxProfile `json:"sandboxes,omitempty"` + Bindings []BundleBinding `json:"bindings,omitempty"` +} + +type BundleBinding struct { + Kind string `json:"kind"` + AssetID string `json:"assetId"` +} + +type BundleAssetSummary struct { + BundleAssetRef + Name string `json:"name"` + TargetID string `json:"targetId,omitempty"` +} diff --git a/internal/engine/workflow_graph.go b/internal/engine/workflow_graph.go index f0f20000f..3105746b8 100644 --- a/internal/engine/workflow_graph.go +++ b/internal/engine/workflow_graph.go @@ -152,6 +152,11 @@ func hasFailed(wf domain.WorkflowDefinition, r domain.Run) bool { return ok } +// ValidateWorkflowGraph applies the runtime graph checks to a portable definition. +func ValidateWorkflowGraph(wf domain.WorkflowDefinition) error { + return validate(wf) +} + func validate(wf domain.WorkflowDefinition) error { if err := domain.ValidateWorkflowKnowledge(wf); err != nil { return err diff --git a/internal/httpapi/asset_bundle.go b/internal/httpapi/asset_bundle.go new file mode 100644 index 000000000..286cc26e4 --- /dev/null +++ b/internal/httpapi/asset_bundle.go @@ -0,0 +1,137 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/engine" + "agentflow/internal/repo" + + "github.com/gin-gonic/gin" +) + +type assetBundleHandlers struct{ *deps } + +const maxAssetBundleRequest = 96 << 20 + +func (h *assetBundleHandlers) requireProjectManager(c *gin.Context) (string, bool) { + user, authenticated := h.requestUser(c.Request, true) + if !authenticated || user == nil || user.IsGuest { + c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"}) + return "", false + } + id := strings.TrimSpace(c.Param("id")) + project, ok := h.repo.Project(id) + if !ok || project.ArchivedAt != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "项目不存在"}) + return "", false + } + if _, manage := domain.ProjectCredentialAccess(project, user.ID, h.isPlatformAdmin(c.Request)); manage { + return id, true + } + c.JSON(http.StatusForbidden, gin.H{"error": "资产包需要项目管理员权限"}) + return "", false +} + +func (h *assetBundleHandlers) export(c *gin.Context) { + project, allowed := h.requireProjectManager(c) + if !allowed { + return + } + var input struct { + Assets []domain.BundleAssetRef `json:"assets"` + } + if !readAssetBundleJSON(c, &input, 128<<10) { + return + } + bundle, err := h.repo.ExportProjectAssetBundle(project, input.Assets) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + raw, err := json.Marshal(bundle) + if err != nil { + respond(c, err) + return + } + if len(raw) > maxAssetBundleRequest { + c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "资产包超过 96 MiB"}) + return + } + c.Header("Cache-Control", "private, no-store") + c.Header("Content-Disposition", `attachment; filename="loopforge-assets.json"`) + c.Data(http.StatusOK, "application/json", raw) +} + +func (h *assetBundleHandlers) preview(c *gin.Context) { + h.importBundle(c, false) +} + +func (h *assetBundleHandlers) importAssets(c *gin.Context) { + h.importBundle(c, true) +} + +func (h *assetBundleHandlers) importBundle(c *gin.Context, save bool) { + project, allowed := h.requireProjectManager(c) + if !allowed { + return + } + var bundle domain.ProjectAssetBundle + if !readAssetBundleJSON(c, &bundle, maxAssetBundleRequest) { + return + } + for i := range bundle.Agents { + if err := validateCatalogAgentExecutor(&bundle.Agents[i]); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + } + for _, workflow := range bundle.Workflows { + if strings.TrimSpace(workflow.SandboxProfileID) == "" { + workflow.SandboxProfileID = repo.DefaultSandboxProfileID + } + if err := engine.ValidateWorkflowGraph(workflow); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + } + status := http.StatusOK + var assets []domain.BundleAssetSummary + var err error + if save { + status = http.StatusCreated + assets, err = h.repo.ImportProjectAssetBundle(project, bundle) + } else { + assets, err = h.repo.PreviewProjectAssetBundle(project, bundle) + } + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + c.Header("Cache-Control", "private, no-store") + c.JSON(status, gin.H{"assets": assets, "bindings": bundle.Bindings}) +} + +func readAssetBundleJSON(c *gin.Context, value any, limit int64) bool { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit) + decoder := json.NewDecoder(c.Request.Body) + decoder.DisallowUnknownFields() + err := decoder.Decode(value) + if err == nil { + err = decoder.Decode(new(json.RawMessage)) + if err == io.EOF { + return true + } + } + var limitErr *http.MaxBytesError + if errors.As(err, &limitErr) { + c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "资产包超过上传限制"}) + } else { + c.JSON(http.StatusBadRequest, gin.H{"error": "无法读取资产包 JSON,请确认格式和版本"}) + } + return false +} diff --git a/internal/httpapi/asset_bundle_test.go b/internal/httpapi/asset_bundle_test.go new file mode 100644 index 000000000..cd02f97e3 --- /dev/null +++ b/internal/httpapi/asset_bundle_test.go @@ -0,0 +1,248 @@ +package httpapi + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +func TestProjectAssetBundleRoundTrip(t *testing.T) { + f := cvBNewHTTPFixture(t) + store := f.s + save := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + save(store.PutProject(domain.Project{ID: "bundle-source", Name: "Source", OwnerID: f.user.ID})) + save(store.PutProject(domain.Project{ID: "bundle-target", Name: "Target", OwnerID: f.user.ID})) + markdown := []byte("---\nname: original\n---\n# Exact bytes\n") + binary := []byte{0, 0xff, '\n'} + save(store.PutSkillSnapshot(domain.SkillDefinition{ + ID: "company-skill", Name: "Company skill", ProjectID: "bundle-source", + }, []repo.SkillFileInput{ + {Path: "SKILL.md", Content: markdown, Mode: 0644}, + {Path: "scripts/tool.bin", Content: binary, Mode: 0755}, + }, true)) + save(store.PutMCPServer(domain.MCPServerDefinition{ + ID: "company-mcp", Name: "Example MCP", ProjectID: "bundle-source", Scope: "project", + Transport: "stdio", Command: "node", Args: []string{"server.js"}, Environment: map[string]string{"API_KEY": "binding-test-secret"}, + })) + save(store.PutMCPFiles("company-mcp", []repo.SkillFileInput{{Path: "server.js", Content: []byte("console.log('adapter')")}})) + save(store.PutAgent(domain.AgentDefinition{ + ID: "company-role", Name: "Reviewer", ProjectID: "bundle-source", ExecutorID: "codebuddy", + Skills: []string{"company-skill"}, MCPServers: []string{"company-mcp"}, Rules: []string{"company-rule"}, + Prompt: "Read .agentflow/company-role/skills/company-skill/SKILL.md", + PlatformMCP: true, + })) + save(store.PutRule(domain.RuleDefinition{ + ID: "company-rule", Name: "Rule", ProjectID: "bundle-source", Global: true, WorkflowIDs: []string{"company-sop"}, + Content: "Cite source evidence.", + })) + save(store.PutSandbox(domain.SandboxProfile{ + ID: "company-sandbox", Name: "Sandbox", ProjectID: "bundle-source", Driver: "docker", + Dockerfile: &domain.SandboxDockerfile{ + Content: "FROM python:3.12-slim", Files: map[string]string{"config/defaults.txt": "mode=review\n"}, + }, + Environment: map[string]string{"TOKEN": "sandbox-test-secret"}, + })) + save(store.PutWorkflow(domain.WorkflowDefinition{ + ID: "company-sop", Name: "Review", ProjectID: "bundle-source", SandboxProfileID: "company-sandbox", Status: "published", + ProjectCredentialIDs: []string{"source-connection-id"}, + Nodes: []domain.WorkflowNode{ + {ID: "review", Name: "Review", Type: "agent", AgentID: "company-role", + KnowledgeRefs: []domain.KnowledgeRef{{ConnectorID: "source-knowledge-id", Mode: "all"}}}, + {ID: "verify", Name: "Verify", Type: "script", ScriptLanguage: "python", + Script: "CODE_SKILL = \"company-skill\"\nprint(CODE_SKILL)", RejectTo: "review", OnFailure: "reject"}, + }, + Edges: []domain.WorkflowEdge{{ID: "e1", Source: "review", Target: "verify", When: "success"}}, + })) + + exportPath := "/api/projects/bundle-source/asset-bundles/export" + selection := map[string]any{"assets": []domain.BundleAssetRef{ + {Kind: "sop", ID: "company-sop"}, {Kind: "skill", ID: "company-skill"}, + {Kind: "mcp", ID: "company-mcp"}, {Kind: "agent", ID: "company-role"}, + }} + res := cvBRequest(t, f, "POST", exportPath, selection, true) + if res.Code != http.StatusOK { + t.Fatalf("export: %d %s", res.Code, res.Body.String()) + } + if strings.Contains(res.Body.String(), "test-secret") || strings.Contains(res.Body.String(), "source-connection-id") || strings.Contains(res.Body.String(), "source-knowledge-id") { + t.Fatal("the bundle exported a credential") + } + var bundle domain.ProjectAssetBundle + if err := json.Unmarshal(res.Body.Bytes(), &bundle); err != nil { + t.Fatal(err) + } + if len(bundle.Skills) != 1 || len(bundle.MCPServers) != 1 || len(bundle.Workflows) != 1 || + len(bundle.Sandboxes) != 1 || len(bundle.Bindings) < 3 { + t.Fatalf("bundle failed to include and deduplicate dependencies: %+v", bundle) + } + target := "/api/projects/bundle-target/asset-bundles/" + res = cvBRequest(t, f, "POST", target+"preview", bundle, true) + if res.Code != http.StatusOK { + t.Fatalf("preview: %d %s", res.Code, res.Body.String()) + } + for _, skill := range store.Skills() { + if skill.ProjectID == "bundle-target" { + t.Fatal("preview persisted a skill") + } + } + res = cvBRequest(t, f, "POST", target+"import", bundle, true) + if res.Code != http.StatusCreated { + t.Fatalf("import: %d %s", res.Code, res.Body.String()) + } + var result struct{ Assets []domain.BundleAssetSummary } + if err := json.Unmarshal(res.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + ids := make(map[string]string) + for _, item := range result.Assets { + ids[item.Kind] = item.TargetID + if item.ID == item.TargetID { + t.Fatal("import reused source ID") + } + } + role, _ := store.Agent(ids["agent"]) + skill, _ := store.Skill(ids["skill"]) + workflow, _ := store.Workflow(ids["sop"]) + server, _ := store.MCPServer(ids["mcp"]) + sandbox, _ := store.Sandbox(ids["sandbox"]) + rule, _ := store.Rule(ids["rule"]) + if role.ProjectID != "bundle-target" || role.Shared || role.PlatformMCP || + len(role.Skills) != 1 || role.Skills[0] != ids["skill"] || len(role.MCPServers) != 1 || role.MCPServers[0] != ids["mcp"] || + len(role.Rules) != 1 || role.Rules[0] != ids["rule"] || + workflow.ProjectID != "bundle-target" || workflow.Status != "draft" || workflow.Shared || workflow.Nodes[0].AgentID != role.ID || + workflow.Nodes[1].RejectTo != "review" || !strings.Contains(workflow.Nodes[1].Script, ids["skill"]) || + workflow.SandboxProfileID != sandbox.ID || sandbox.Dockerfile == nil || sandbox.Dockerfile.Content != "FROM python:3.12-slim" || + sandbox.Dockerfile.Files["config/defaults.txt"] != "mode=review\n" || + len(workflow.ProjectCredentialIDs) != 0 || len(workflow.Nodes[0].KnowledgeRefs) != 0 || + len(rule.WorkflowIDs) != 1 || rule.WorkflowIDs[0] != workflow.ID || + !strings.Contains(role.Prompt, ".agentflow/"+role.ID+"/skills/"+skill.ID+"/SKILL.md") || + len(server.Environment) != 0 || server.Scope != "project" || len(sandbox.Environment) != 0 { + t.Fatal("references or project visibility were not safely remapped") + } + for path, expected := range map[string][]byte{"SKILL.md": markdown, "scripts/tool.bin": binary} { + raw, ok := store.SkillFileContent(skill.ID, path) + if !ok || !bytes.Equal(raw, expected) { + t.Fatalf("file %q changed during round trip", path) + } + } + if len(skill.FileRefs) != 2 || skill.FileRefs[1].Mode != 0755 { + t.Fatalf("executable mode not preserved: %+v", skill.FileRefs) + } + if raw, ok := store.MCPFileContent(server.ID, "server.js"); !ok || string(raw) != "console.log('adapter')" { + t.Fatal("missing MCP package bytes") + } +} + +func TestProjectAssetBundleRejectsBadFilesAndRollsBack(t *testing.T) { + f := cvBNewHTTPFixture(t) + if err := f.s.PutProject(domain.Project{ID: "bundle-rollback", Name: "Rollback", OwnerID: f.user.ID}); err != nil { + t.Fatal(err) + } + tgt := "/api/projects/bundle-rollback/asset-bundles/" + content := []byte("regular asset") + bundle := domain.ProjectAssetBundle{ + Format: domain.ProjectAssetBundleFormat, + Skills: []domain.BundleSkill{{ + SkillDefinition: domain.SkillDefinition{ID: "a-skill", Name: "Test skill"}, + Attachments: []domain.BundleAssetFile{{ + Path: "../outside", Content: content, SHA256: fmt.Sprintf("%x", sha256.Sum256(content)), + }}, + }}, + } + res := cvBRequest(t, f, "POST", tgt+"import", bundle, true) + if res.Code != http.StatusBadRequest { + t.Fatalf("unsafe path: %d %s", res.Code, res.Body.String()) + } + bundle.Skills[0].Attachments[0].Path = "SKILL.md" + bundle.Sandboxes = []domain.SandboxProfile{{ID: "wrong-driver", Name: "Malconfigured", Driver: "invalid"}} + res = cvBRequest(t, f, "POST", tgt+"preview", bundle, true) + if res.Code != http.StatusBadRequest { + t.Fatalf("preview accepted an unsupported sandbox: %d %s", res.Code, res.Body.String()) + } + bundle.Sandboxes[0].Driver = "native" + if err := f.s.DB.Exec("CREATE TRIGGER bundle_reject_sandbox BEFORE INSERT ON sandboxes BEGIN SELECT RAISE(FAIL, 'forced sandbox insert'); END").Error; err != nil { + t.Fatal(err) + } + res = cvBRequest(t, f, "POST", tgt+"import", bundle, true) + if res.Code != http.StatusBadRequest || !strings.Contains(res.Body.String(), "forced sandbox insert") { + t.Fatalf("expected final write validation failure: %d %s", res.Code, res.Body.String()) + } + for _, skill := range f.s.Skills() { + if skill.ProjectID == "bundle-rollback" { + t.Fatal("partial write survived failed import") + } + } +} + +func TestProjectAssetBundleScope(t *testing.T) { + f := cvBNewHTTPFixture(t) + otherID := f.user.ID + 99 + if err := f.s.PutProject(domain.Project{ID: "bundle-acl", Name: "ACL", OwnerID: f.user.ID}); err != nil { + t.Fatal(err) + } + if err := f.s.PutSkill(domain.SkillDefinition{ID: "unrelated-private", Name: "Other", ProjectID: "other-project"}); err != nil { + t.Fatal(err) + } + path := "/api/projects/bundle-acl/asset-bundles/export" + input := map[string]any{"assets": []domain.BundleAssetRef{{Kind: "skill", ID: "unrelated-private"}}} + request := cvBRequest(t, f, "POST", path, input, false) + if request.Code != http.StatusUnauthorized { + t.Fatalf("anonymous export: %d %s", request.Code, request.Body.String()) + } + request = cvBMiscRequestAs(t, f, domain.User{ID: otherID, LoginName: "bundle-outsider"}, "POST", path, input) + if request.Code != http.StatusForbidden { + t.Fatalf("outsider export: %d %s", request.Code, request.Body.String()) + } + request = cvBRequest(t, f, "POST", path, input, true) + if request.Code != http.StatusBadRequest { + t.Fatalf("cross-project export: %d %s", request.Code, request.Body.String()) + } +} + +func TestProjectAssetBundlePreservesAutomaticExecutionSettings(t *testing.T) { + f := cvBNewHTTPFixture(t) + if err := f.s.PutProject(domain.Project{ID: "bundle-auto", Name: "Auto", OwnerID: f.user.ID}); err != nil { + t.Fatal(err) + } + bundle := domain.ProjectAssetBundle{ + Format: domain.ProjectAssetBundleFormat, + Agents: []domain.AgentDefinition{{ID: "reviewer", Name: "Reviewer"}}, + Workflows: []domain.WorkflowDefinition{{ + ID: "review", Name: "Review LOOP", AutoSelectSandbox: true, + Nodes: []domain.WorkflowNode{{ID: "review", Name: "Review", Type: "agent", AgentID: "reviewer"}}, + }}, + } + res := cvBRequest(t, f, "POST", "/api/projects/bundle-auto/asset-bundles/import", bundle, true) + if res.Code != http.StatusCreated { + t.Fatalf("import: %d %s", res.Code, res.Body.String()) + } + var result struct{ Assets []domain.BundleAssetSummary } + if err := json.Unmarshal(res.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + for _, asset := range result.Assets { + switch asset.Kind { + case "agent": + v, ok := f.s.Agent(asset.TargetID) + if !ok || v.ExecutorID != "" { + t.Fatal("the imported role must follow the user's executor") + } + case "sop": + v, ok := f.s.Workflow(asset.TargetID) + if !ok || !v.AutoSelectSandbox || v.SandboxProfileID != "" { + t.Fatal("the imported LOOP must select its sandbox at run time") + } + } + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 94625f789..71aa31a9f 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -82,7 +82,8 @@ type Server struct { credentials *projectCredentialsHandlers insights *insightsHandlers businessDomains *businessDomainsHandlers - catalog *catalogHandlers // catalog.go + catalog *catalogHandlers // catalog.go + assetBundles *assetBundleHandlers mcp *mcpHandlers // mcp.go market *marketHandlers // mcp_market.go skillhub *skillhubHandlers // skillhub_market.go @@ -173,6 +174,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv platformSetting: &platformSettingsHandlers{deps: d, envPublicURL: func() string { return notifications.PublicURL }}, httpHostTrust: &gitHTTPHostTrustHandlers{deps: d, hosts: s.GitHTTPHostTrustRepo}, catalog: &catalogHandlers{deps: d}, + assetBundles: &assetBundleHandlers{deps: d}, businessDomains: &businessDomainsHandlers{deps: d}, insights: &insightsHandlers{deps: d}, projects: &projectsHandlers{deps: d}, @@ -422,6 +424,9 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.PUT("/api/projects", api.projects.projects) g.POST("/api/projects", api.projects.projects) g.GET("/api/projects/:id", api.projects.project) + g.POST("/api/projects/:id/asset-bundles/export", api.assetBundles.export) + g.POST("/api/projects/:id/asset-bundles/preview", api.assetBundles.preview) + g.POST("/api/projects/:id/asset-bundles/import", api.assetBundles.importAssets) g.GET("/api/projects/:id/credentials", api.credentials.list) g.POST("/api/projects/:id/credentials", api.credentials.save) g.PUT("/api/projects/:id/credentials/:credentialId", api.credentials.save) diff --git a/internal/repo/asset_bundle_export.go b/internal/repo/asset_bundle_export.go new file mode 100644 index 000000000..ed84c09cc --- /dev/null +++ b/internal/repo/asset_bundle_export.go @@ -0,0 +1,251 @@ +package repo + +import ( + "crypto/sha256" + "fmt" + "net/url" + "slices" + "strings" + + "agentflow/internal/domain" + + "gorm.io/gorm" +) + +const maxBundleAssets = 200 +const maxBundleFileBytes = 64 << 20 + +type bundleExport struct { + catalog *CatalogRepo + project string + seen map[domain.BundleAssetRef]bool + bundle domain.ProjectAssetBundle + bytes int64 +} + +// ExportProjectAssetBundle snapshots the selected assets and their project-owned +// dependencies. A reference to a platform sandbox is resolved on import. +func (r *CatalogRepo) ExportProjectAssetBundle(project string, selection []domain.BundleAssetRef) (domain.ProjectAssetBundle, error) { + if project == "" || len(selection) == 0 || len(selection) > maxBundleAssets { + return domain.ProjectAssetBundle{}, fmt.Errorf("请选择 1 至 %d 项项目资产", maxBundleAssets) + } + var bundle domain.ProjectAssetBundle + err := r.DB.Transaction(func(tx *gorm.DB) error { + catalog := *r + catalog.deps = &deps{DB: tx} + x := bundleExport{catalog: &catalog, project: project, seen: make(map[domain.BundleAssetRef]bool)} + x.bundle.Format = domain.ProjectAssetBundleFormat + for _, ref := range selection { + switch ref.Kind { + case "skill", "mcp", "agent", "sop": + default: + return fmt.Errorf("无法选择 %q 类型作为资产包入口", ref.Kind) + } + if err := x.add(ref.Kind, ref.ID); err != nil { + return err + } + } + for i := range x.bundle.Rules { + rule := &x.bundle.Rules[i] + rule.WorkflowIDs = slices.DeleteFunc(slices.Clone(rule.WorkflowIDs), func(id string) bool { + return !x.seen[assetRef("sop", id)] + }) + } + bundle = x.bundle + return nil + }) + return bundle, err +} + +func assetRef(kind, id string) domain.BundleAssetRef { + return domain.BundleAssetRef{Kind: kind, ID: id} +} + +func builtinBundleSandbox(id string) bool { + return strings.TrimSpace(id) == "" || isDefaultSandboxID(id) +} + +func (x *bundleExport) add(kind, id string) error { + ref := assetRef(kind, id) + if x.seen[ref] { + return nil + } + if len(x.seen) >= maxBundleAssets { + return fmt.Errorf("资产与依赖总数超过 %d 项", maxBundleAssets) + } + x.seen[ref] = true + missing := fmt.Errorf("资产或依赖 %s/%s 不属于当前项目或已不存在", kind, id) + r := x.catalog + switch kind { + case "skill": + v, ok := r.Skill(id) + if !ok || v.ProjectID != x.project { + return missing + } + files, err := collectBundleFiles(x, v.FileRefs, r.SkillFileContents(id), func(ref domain.SkillFileRef) (string, string, uint32) { + return ref.Path, ref.SHA256, ref.Mode + }) + if err != nil { + return err + } + v.FileRefs, v.Source, v.ProjectID, v.Shared = nil, nil, "", false + x.bundle.Skills = append(x.bundle.Skills, domain.BundleSkill{SkillDefinition: v, Attachments: files}) + case "mcp": + v, ok := r.MCPServer(id) + if !ok || v.ProjectID != x.project || v.Scope == "personal" { + return missing + } + files, err := collectBundleFiles(x, v.FileRefs, r.MCPFileContents(id), func(ref domain.MCPFileRef) (string, string, uint32) { + return ref.Path, ref.SHA256, ref.Mode + }) + if err != nil { + return err + } + if removeBundleMCPBindings(&v) { + x.binding("mcp-connection", id) + } + v.FileRefs, v.MarketID, v.IconURL, v.ProjectID = nil, "", "", "" + x.bundle.MCPServers = append(x.bundle.MCPServers, domain.BundleMCPServer{MCPServerDefinition: v, Attachments: files}) + case "agent": + v, ok := r.Agent(id) + if !ok || v.ProjectID != x.project { + return missing + } + for _, dependencies := range []struct { + kind string + ids []string + }{ + {"skill", v.Skills}, {"mcp", v.MCPServers}, {"rule", v.Rules}, + } { + for _, dependency := range dependencies.ids { + if err := x.add(dependencies.kind, dependency); err != nil { + return err + } + } + } + if removeBundleAgentBindings(&v) { + x.binding("role-integrations", id) + } + v.ProjectID, v.Shared = "", false + x.bundle.Agents = append(x.bundle.Agents, v) + case "sop": + v, ok := r.Workflow(id) + if !ok || v.ProjectID != x.project || v.Generic { + return missing + } + if !v.AutoSelectSandbox && !builtinBundleSandbox(v.SandboxProfileID) { + if err := x.add("sandbox", v.SandboxProfileID); err != nil { + return err + } + } + for _, node := range v.Nodes { + if node.AgentID != "" && !domain.IsPreviewBuildAgent(node.AgentID) { + if err := x.add("agent", node.AgentID); err != nil { + return err + } + } + if node.SOPWorkflowID != "" { + if err := x.add("sop", node.SOPWorkflowID); err != nil { + return err + } + } + } + for _, rule := range r.Rules() { + if rule.Global && slices.Contains(rule.WorkflowIDs, id) { + if err := x.add("rule", rule.ID); err != nil { + return err + } + } + } + if removeBundleWorkflowBindings(&v) { + x.binding("loop-integrations", id) + } + v.ProjectID, v.Shared = "", false + x.bundle.Workflows = append(x.bundle.Workflows, v) + case "rule": + v, ok := r.Rule(id) + if !ok || v.ProjectID != x.project { + return missing + } + v.ProjectID, v.Shared = "", false + x.bundle.Rules = append(x.bundle.Rules, v) + case "sandbox": + v, ok := r.Sandbox(id) + if !ok || v.ProjectID != x.project { + return missing + } + if len(v.Environment) != 0 { + x.binding("sandbox-environment", id) + } + if v.Privileged { + x.binding("sandbox-privileged", id) + } + v.Environment, v.ProjectID, v.Shared, v.DockerfileID = nil, "", false, "" + x.bundle.Sandboxes = append(x.bundle.Sandboxes, v) + default: + return missing + } + return nil +} + +func (x *bundleExport) binding(kind, id string) { + x.bundle.Bindings = append(x.bundle.Bindings, domain.BundleBinding{Kind: kind, AssetID: id}) +} + +func collectBundleFiles[T any](x *bundleExport, refs []T, contents map[string][]byte, fields func(T) (string, string, uint32)) ([]domain.BundleAssetFile, error) { + if len(refs) != len(contents) { + return nil, fmt.Errorf("资产文件清单与存储内容不一致") + } + files := make([]domain.BundleAssetFile, 0, len(refs)) + for _, ref := range refs { + path, digest, mode := fields(ref) + content, ok := contents[path] + sum := fmt.Sprintf("%x", sha256.Sum256(content)) + if !ok || (digest != "" && sum != digest) { + return nil, fmt.Errorf("资产文件 %q 校验失败", path) + } + x.bytes += int64(len(content)) + if x.bytes > maxBundleFileBytes { + return nil, fmt.Errorf("资产包附件超过 64 MiB") + } + files = append(files, domain.BundleAssetFile{Path: path, Content: content, Mode: mode, SHA256: sum}) + } + return files, nil +} + +func removeBundleMCPBindings(v *domain.MCPServerDefinition) bool { + removed := len(v.Headers) > 0 || len(v.Environment) > 0 || v.AuthType != "" || v.CredentialKind != "" + v.Headers, v.Environment, v.OwnerUserID = nil, nil, 0 + v.AuthType, v.CredentialKind = "", "" + if u, err := url.Parse(v.URL); err != nil { + v.URL = "" + removed = true + } else if u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.ForceQuery { + u.User, u.RawQuery, u.Fragment, u.RawFragment, u.ForceQuery = nil, "", "", "", false + v.URL = u.String() + removed = true + } + return removed +} + +func removeBundleAgentBindings(v *domain.AgentDefinition) bool { + removed := v.PlatformMCP || v.KnowledgeBase + v.PlatformMCP, v.KnowledgeBase = false, false + return removed +} + +func removeBundleWorkflowBindings(v *domain.WorkflowDefinition) bool { + removed := len(v.Notifications) != 0 || len(v.ProjectCredentialIDs) != 0 + v.Notifications, v.SandboxSnapshot, v.ExecutorDefaults = nil, nil, nil + v.ProjectCredentialIDs = nil + v.GroupSOPHandoff, v.GroupCompletion, v.SOPCheckpoint = nil, nil, nil + v.GroupMembers, v.GroupHistory, v.GroupPlan = nil, nil, nil + v.Owner, v.TaskTitle, v.CollaborationMode = "", "", "" + for i := range v.Nodes { + n := &v.Nodes[i] + removed = removed || len(n.Notifications) > 0 || len(n.CredentialEnv) > 0 || len(n.KnowledgeRefs) > 0 + n.Notifications, n.CredentialEnv, n.KnowledgeRefs = nil, nil, nil + n.RequestedBy, n.RequestID, n.PlanItemID, n.ClaimedFiles = "", "", "", nil + } + return removed +} diff --git a/internal/repo/asset_bundle_import.go b/internal/repo/asset_bundle_import.go new file mode 100644 index 000000000..679b4a589 --- /dev/null +++ b/internal/repo/asset_bundle_import.go @@ -0,0 +1,413 @@ +package repo + +import ( + "crypto/rand" + "crypto/sha256" + "fmt" + "path" + "regexp" + "strings" + + "agentflow/internal/domain" + + "gorm.io/gorm" +) + +var bundleIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) +var bundleSkillPath = regexp.MustCompile(`\.agentflow/(?:[A-Za-z0-9._-]+/)?skills/[A-Za-z0-9._-]+`) +var bundleSkillConstant = regexp.MustCompile(`(?m)^[A-Z0-9_]*SKILL(?:_ID)?[\t ]*=[\t ]*["'][A-Za-z0-9._-]+["']`) + +type bundleImport struct { + target string + ids map[domain.BundleAssetRef]string + summary []domain.BundleAssetSummary + fileSize int64 +} + +func (r *CatalogRepo) PreviewProjectAssetBundle(project string, bundle domain.ProjectAssetBundle) ([]domain.BundleAssetSummary, error) { + plan, err := r.prepareProjectAssetBundle(project, bundle, "preview") + if err != nil { + return nil, err + } + for i := range plan.summary { + plan.summary[i].TargetID = "" + } + return plan.summary, nil +} + +func (r *CatalogRepo) ImportProjectAssetBundle(project string, bundle domain.ProjectAssetBundle) ([]domain.BundleAssetSummary, error) { + var nonce [12]byte + if _, err := rand.Read(nonce[:]); err != nil { + return nil, err + } + plan, err := r.prepareProjectAssetBundle(project, bundle, fmt.Sprintf("bundle-%x", nonce)) + if err != nil { + return nil, err + } + return plan.summary, r.DB.Transaction(func(tx *gorm.DB) error { + catalog := *r + catalog.deps = &deps{DB: tx} + return plan.save(&catalog, bundle) + }) +} + +func (r *CatalogRepo) prepareProjectAssetBundle(project string, b domain.ProjectAssetBundle, prefix string) (*bundleImport, error) { + if b.Format != domain.ProjectAssetBundleFormat { + return nil, fmt.Errorf("不支持的资产包格式") + } + p := &bundleImport{target: project, ids: make(map[domain.BundleAssetRef]string)} + for _, groups := range [][]domain.BundleAssetSummary{ + bundleSummaries("skill", b.Skills, func(v domain.BundleSkill) (string, string) { return v.ID, v.Name }), + bundleSummaries("mcp", b.MCPServers, func(v domain.BundleMCPServer) (string, string) { return v.ID, v.Name }), + bundleSummaries("agent", b.Agents, func(v domain.AgentDefinition) (string, string) { return v.ID, v.Name }), + bundleSummaries("sop", b.Workflows, func(v domain.WorkflowDefinition) (string, string) { return v.ID, v.Name }), + bundleSummaries("rule", b.Rules, func(v domain.RuleDefinition) (string, string) { return v.ID, v.Name }), + bundleSummaries("sandbox", b.Sandboxes, func(v domain.SandboxProfile) (string, string) { return v.ID, v.Name }), + } { + for _, summary := range groups { + if !bundleIDPattern.MatchString(summary.ID) || strings.TrimSpace(summary.Name) == "" { + return nil, fmt.Errorf("%s 需要合法的标识和名称", summary.Kind) + } + if _, exists := p.ids[summary.BundleAssetRef]; exists { + return nil, fmt.Errorf("资产包重复声明 %s/%s", summary.Kind, summary.ID) + } + summary.TargetID = fmt.Sprintf("%s-%d", prefix, len(p.summary)+1) + p.ids[summary.BundleAssetRef] = summary.TargetID + p.summary = append(p.summary, summary) + } + } + if count := len(p.summary); count == 0 || count > maxBundleAssets { + return nil, fmt.Errorf("资产包需要 1 至 %d 项资产与依赖", maxBundleAssets) + } + for _, v := range b.Skills { + if len(v.Attachments)+len(v.Files) > domain.SkillMaxFileCount { + return nil, fmt.Errorf("技能 %q 文件数超出限制", v.ID) + } + if err := p.checkFiles(v.Files, v.Attachments); err != nil { + return nil, err + } + } + for _, v := range b.MCPServers { + removeBundleMCPBindings(&v.MCPServerDefinition) + v.ProjectID, v.Scope, v.FileRefs = project, "project", nil + if err := domain.ValidateMCPServer(v.MCPServerDefinition); err != nil { + return nil, err + } + if len(v.Attachments) > domain.MCPMaxFileCount { + return nil, fmt.Errorf("MCP %q 文件数超出限制", v.ID) + } + if len(v.Attachments) > 0 && v.Transport == "http" { + return nil, fmt.Errorf("MCP %q 的附件仅适用于 stdio", v.ID) + } + if err := p.checkFiles(nil, v.Attachments); err != nil { + return nil, err + } + } + for _, v := range b.Agents { + if v.ExecutorID != "" { + ex, exists := BuiltInExecutor(v.ExecutorID) + if !exists { + return nil, fmt.Errorf("角色 %q 的执行器 %q 不可用", v.ID, v.ExecutorID) + } + if err := domain.ValidateAgentEffort(v.Effort, ex.Kind); err != nil { + return nil, err + } + } + if err := domain.ValidateVerificationGates(v.Verification); err != nil { + return nil, err + } + for _, refs := range []struct { + kind string + ids []string + }{ + {"rule", v.Rules}, {"skill", v.Skills}, {"mcp", v.MCPServers}, + } { + if err := p.checkRefs(refs.kind, refs.ids); err != nil { + return nil, err + } + } + } + for _, w := range b.Workflows { + if err := domain.ValidateWorkflowPreparation(w); err != nil { + return nil, err + } + if err := domain.ValidateWorkflowMetricStages(w); err != nil { + return nil, err + } + for _, n := range w.Nodes { + if !domain.IsPreviewBuildAgent(n.AgentID) { + if err := p.checkOptionalRef("agent", n.AgentID); err != nil { + return nil, err + } + } + if err := p.checkOptionalRef("sop", n.SOPWorkflowID); err != nil { + return nil, err + } + } + if !w.AutoSelectSandbox && !builtinBundleSandbox(w.SandboxProfileID) { + if err := p.checkRefs("sandbox", []string{w.SandboxProfileID}); err != nil { + return nil, err + } + } + } + if err := validateBundleSOPDependencies(b.Workflows); err != nil { + return nil, err + } + for _, s := range b.Sandboxes { + s.Environment = nil + if err := domain.ValidateSandboxAssets(s); err != nil { + return nil, fmt.Errorf("沙箱 %q:%w", s.ID, err) + } + if s.Dockerfile != nil { + if err := p.checkFiles(s.Dockerfile.Files, nil); err != nil { + return nil, err + } + } + } + for _, rule := range b.Rules { + if err := p.checkRefs("sop", rule.WorkflowIDs); err != nil { + return nil, err + } + } + return p, nil +} + +func validateBundleSOPDependencies(workflows []domain.WorkflowDefinition) error { + graph := make(map[string][]string, len(workflows)) + for _, w := range workflows { + for _, node := range w.Nodes { + if node.SOPWorkflowID != "" { + graph[w.ID] = append(graph[w.ID], node.SOPWorkflowID) + } + } + } + active := make(map[string]bool) + done := make(map[string]bool) + var visit func(string) error + visit = func(id string) error { + if active[id] { + return fmt.Errorf("SOP 依赖形成循环:%s", id) + } + if done[id] { + return nil + } + active[id] = true + for _, child := range graph[id] { + if err := visit(child); err != nil { + return err + } + } + delete(active, id) + done[id] = true + return nil + } + for _, w := range workflows { + if err := visit(w.ID); err != nil { + return err + } + } + return nil +} + +func bundleSummaries[T any](kind string, items []T, identity func(T) (string, string)) []domain.BundleAssetSummary { + out := make([]domain.BundleAssetSummary, 0, len(items)) + for _, item := range items { + id, name := identity(item) + out = append(out, domain.BundleAssetSummary{BundleAssetRef: assetRef(kind, id), Name: name}) + } + return out +} + +func (p *bundleImport) checkFiles(inline map[string]string, files []domain.BundleAssetFile) error { + paths := make(map[string]bool, len(inline)+len(files)) + addPath := func(name string) error { + if err := domain.ValidateRelativeFilePath(name); err != nil { + return err + } + if name != strings.TrimSpace(name) || strings.ContainsAny(name, "\\\x00") || paths[name] { + return fmt.Errorf("无效或重复的附件路径 %q", name) + } + paths[name] = true + return nil + } + for name := range inline { + if err := addPath(name); err != nil { + return err + } + } + for _, f := range files { + if err := addPath(f.Path); err != nil { + return err + } + if int64(len(f.Content)) > domain.SkillFileMaxBytes || f.SHA256 != fmt.Sprintf("%x", sha256.Sum256(f.Content)) { + return fmt.Errorf("附件 %q 的大小或校验值无效", f.Path) + } + p.fileSize += int64(len(f.Content)) + if p.fileSize > maxBundleFileBytes { + return fmt.Errorf("资产包附件超过 64 MiB") + } + } + for rel := range paths { + for dir := path.Dir(rel); dir != "."; dir = path.Dir(dir) { + if paths[dir] { + return fmt.Errorf("附件路径 %q 同时作为文件及目录", dir) + } + } + } + return nil +} + +func (p *bundleImport) checkRefs(kind string, ids []string) error { + for _, id := range ids { + if p.id(kind, id) == "" { + return fmt.Errorf("资产包缺少依赖 %s/%s", kind, id) + } + } + return nil +} + +func (p *bundleImport) checkOptionalRef(kind, id string) error { + if id == "" { + return nil + } + return p.checkRefs(kind, []string{id}) +} + +func (p *bundleImport) id(kind, id string) string { + return p.ids[assetRef(kind, id)] +} + +func (p *bundleImport) mapIDs(kind string, ids []string) []string { + if len(ids) == 0 { + return nil + } + out := make([]string, len(ids)) + for i, id := range ids { + out[i] = p.id(kind, id) + } + return out +} + +func (p *bundleImport) sandboxID(workflow domain.WorkflowDefinition) string { + if workflow.AutoSelectSandbox { + return "" + } + if builtinBundleSandbox(workflow.SandboxProfileID) { + return DefaultSandboxProfileID + } + return p.id("sandbox", workflow.SandboxProfileID) +} + +// Rebind the platform's Skill mount paths and explicit SKILL constants. +// Free text and packaged Skill/MCP files retain their original bytes. +func (p *bundleImport) rebindSkillReferences(text string) string { + text = bundleSkillPath.ReplaceAllStringFunc(text, func(match string) string { + parts := strings.Split(match, "/") + if len(parts) == 4 { + if id := p.id("agent", parts[1]); id != "" { + parts[1] = id + } + } + last := len(parts) - 1 + if id := p.id("skill", parts[last]); id != "" { + parts[last] = id + } + return strings.Join(parts, "/") + }) + return bundleSkillConstant.ReplaceAllStringFunc(text, func(match string) string { + start := strings.IndexAny(match, "\"'") + 1 + end := len(match) - 1 + if id := p.id("skill", match[start:end]); id != "" { + return match[:start] + id + match[end:] + } + return match + }) +} + +func (p *bundleImport) save(r *CatalogRepo, b domain.ProjectAssetBundle) error { + for _, v := range b.Skills { + v.ID, v.ProjectID, v.Shared, v.Source, v.FileRefs = p.id("skill", v.ID), p.target, false, nil, nil + var err error + if len(v.Attachments) > 0 { + err = r.PutSkillSnapshot(v.SkillDefinition, bundleFileInputs(v.Attachments), true) + } else { + err = r.PutSkill(v.SkillDefinition) + } + if err != nil { + return err + } + } + for _, v := range b.MCPServers { + removeBundleMCPBindings(&v.MCPServerDefinition) + v.ID, v.ProjectID, v.Scope = p.id("mcp", v.ID), p.target, "project" + v.FileRefs, v.MarketID, v.IconURL = nil, "", "" + if err := r.PutMCPServer(v.MCPServerDefinition); err != nil { + return err + } + if len(v.Attachments) > 0 { + if err := r.PutMCPFiles(v.ID, bundleFileInputs(v.Attachments)); err != nil { + return err + } + } + } + for _, v := range b.Rules { + v.ID, v.ProjectID, v.Shared = p.id("rule", v.ID), p.target, false + v.WorkflowIDs = p.mapIDs("sop", v.WorkflowIDs) + if err := r.PutRule(v); err != nil { + return err + } + } + for _, v := range b.Sandboxes { + v.ID, v.ProjectID, v.Shared = p.id("sandbox", v.ID), p.target, false + v.Environment, v.DockerfileID = nil, "" + if err := r.PutSandbox(v); err != nil { + return err + } + } + for _, v := range b.Agents { + removeBundleAgentBindings(&v) + v.ID, v.ProjectID, v.Shared, v.Version = p.id("agent", v.ID), p.target, false, 1 + v.Rules = p.mapIDs("rule", v.Rules) + v.Skills = p.mapIDs("skill", v.Skills) + v.MCPServers = p.mapIDs("mcp", v.MCPServers) + v.Prompt = p.rebindSkillReferences(v.Prompt) + for i := range v.Hooks { + v.Hooks[i].Script = p.rebindSkillReferences(v.Hooks[i].Script) + } + for i := range v.Verification { + for j, command := range v.Verification[i].Commands { + v.Verification[i].Commands[j] = p.rebindSkillReferences(command) + } + } + if err := r.PutAgent(v); err != nil { + return err + } + } + for _, v := range b.Workflows { + removeBundleWorkflowBindings(&v) + v.ID, v.ProjectID, v.Shared, v.Generic = p.id("sop", v.ID), p.target, false, false + v.Status, v.Version, v.Revision, v.PublishedRevision = "draft", 1, 0, 0 + v.SandboxProfileID = p.sandboxID(v) + for i := range v.Nodes { + n := &v.Nodes[i] + if !domain.IsPreviewBuildAgent(n.AgentID) { + n.AgentID = p.id("agent", n.AgentID) + } + n.SOPWorkflowID = p.id("sop", n.SOPWorkflowID) + n.Script = p.rebindSkillReferences(n.Script) + n.Command = p.rebindSkillReferences(n.Command) + } + if err := r.PutWorkflow(v); err != nil { + return err + } + } + return nil +} + +func bundleFileInputs(files []domain.BundleAssetFile) []SkillFileInput { + out := make([]SkillFileInput, 0, len(files)) + for _, f := range files { + out = append(out, SkillFileInput{Path: f.Path, Content: f.Content, Mode: f.Mode}) + } + return out +} diff --git a/web/app/asset-bundle.css b/web/app/asset-bundle.css new file mode 100644 index 000000000..31d1a1d83 --- /dev/null +++ b/web/app/asset-bundle.css @@ -0,0 +1,56 @@ +.asset-bundle-dialog { + width: min(36rem, calc(100vw - 2rem)); + max-height: calc(100dvh - 2rem); + padding: 1.25rem; + border: 1px solid var(--hui-border); + border-radius: 1rem; + color: var(--hui-text); + background: var(--hui-surface); +} +.asset-bundle-dialog::backdrop { background: rgb(0 0 0 / 42%); } +.asset-bundle-head { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; +} +.asset-bundle-dialog h2, .asset-bundle-dialog h3 { margin: 0; } +.asset-bundle-project { + margin: 0 auto 0 0; + overflow-wrap: anywhere; + color: var(--hui-muted); +} +.asset-bundle-dialog section { + display: grid; + justify-items: start; + gap: .625rem; + margin-top: 1rem; +} +.asset-bundle-choices { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); + width: 100%; + max-height: 14rem; + overflow: auto; + gap: .5rem; +} +.asset-bundle-choices fieldset { + min-width: 0; + margin: 0; + border: 1px solid var(--hui-border); + border-radius: .5rem; +} +.asset-bundle-choices label, .asset-bundle-file { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: .4rem .55rem; + overflow-wrap: anywhere; +} +.asset-bundle-notes { + white-space: pre-wrap; + overflow-wrap: anywhere; + max-height: 11rem; + overflow: auto; +} +.asset-bundle-notes:empty { display: none; } diff --git a/web/app/asset-bundle.js b/web/app/asset-bundle.js new file mode 100644 index 000000000..ea64c45c7 --- /dev/null +++ b/web/app/asset-bundle.js @@ -0,0 +1,180 @@ +(function () { + const dialog = document.querySelector('#assetBundleDialog'); + const trigger = document.querySelector('#assetBundleButton'); + const list = dialog.querySelector('#assetBundleChoices'); + const upload = dialog.querySelector('#assetBundleFile'); + const exportButton = dialog.querySelector('#exportAssetBundle'); + const importButton = dialog.querySelector('#importAssetBundle'); + const notes = dialog.querySelector('#assetBundleNotes'); + const selection = [ + ['sop', 'workflows'], + ['agent', 'agents'], + ['skill', 'skills'], + ['mcp', 'mcpServers'], + ]; + const copy = (zh, en) => window.lfT?.(zh, en) ?? zh; + let project = ''; + let bundle = null; + let working = false; + + function endpoint(action) { + return '/api/projects/' + encodeURIComponent(project) + '/asset-bundles/' + action; + } + + function synchronize() { + dialog.setAttribute('aria-busy', String(working)); + exportButton.disabled = working || !list.querySelector('input:checked'); + importButton.disabled = working || !bundle; + upload.disabled = working; + } + + function show(message) { + notes.textContent = message; + } + + function labelFor(kind) { + return { + sop: 'LOOP', agent: copy('角色', 'Role'), skill: 'Skill', mcp: 'MCP', + rule: copy('规则', 'Rule'), sandbox: copy('沙箱', 'Sandbox'), + }[kind] || kind; + } + + function bindingText({kind, assetId}) { + const label = { + 'mcp-connection': copy('配置 MCP 连接及凭据', 'Configure the MCP connection and credentials'), + 'role-integrations': copy('核对角色的平台 MCP 和知识库绑定', 'Review platform MCP and knowledge bindings for the role'), + 'loop-integrations': copy('重新配置 LOOP 凭据、通知和知识库', 'Configure LOOP credentials, notifications and knowledge'), + 'sandbox-environment': copy('配置沙箱环境变量', 'Configure sandbox environment variables'), + 'sandbox-privileged': copy('确认 Docker 特权运行设置', 'Review privileged Docker execution'), + }[kind]; + return label ? label + ' · ' + assetId : assetId; + } + + function renderChoices() { + list.replaceChildren(); + for (const [kind, collection] of selection) { + const items = (state.data[collection] || []).filter(item => + item.projectId === project && !item.generic && item.scope !== 'personal' + ); + if (!items.length) continue; + const group = document.createElement('fieldset'); + const legend = document.createElement('legend'); + legend.textContent = labelFor(kind); + group.append(legend); + for (const item of items) { + const label = document.createElement('label'); + const checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.value = item.id; + checkbox.dataset.kind = kind; + const name = document.createElement('span'); + name.textContent = item.name || item.id; + label.append(checkbox, name); + group.append(label); + } + list.append(group); + } + if (!list.childElementCount) list.textContent = copy('本项目暂无可导出的资产。', 'This project has no exportable assets.'); + } + + function download(value) { + const file = new Blob([JSON.stringify(value)], {type: 'application/json'}); + const url = URL.createObjectURL(file); + const link = document.createElement('a'); + link.download = 'loopforge-assets.json'; + link.href = url; + link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } + + async function work(action) { + if (working || !project) return; + working = true; + synchronize(); + try { + await action(); + } catch (error) { + bundle = null; + upload.value = ''; + show(error.message || String(error)); + } finally { + working = false; + synchronize(); + } + } + + trigger.addEventListener('click', () => { + const current = state.data?.projects?.find(item => item.id === state.projectFilter); + if (!current) { + toast(copy('请选择一个项目', 'Choose a project')); + return; + } + const user = state.currentUser; + const canManage = user && !user.isGuest && (user.isPlatformAdmin || + Number(current.ownerId) === Number(user.id) || + (current.members || []).some(member => Number(member.userId) === Number(user.id) && + member.role?.trim().toLowerCase() === 'maintainer')); + if (!canManage) { + toast(copy('资产包需要项目管理员权限', 'Asset bundles require project manager access')); + return; + } + project = current.id; + dialog.querySelector('#assetBundleProject').textContent = current.name || project; + bundle = null; + upload.value = ''; + show(''); + renderChoices(); + synchronize(); + dialog.showModal(); + }); + list.addEventListener('change', synchronize); + exportButton.addEventListener('click', () => work(async () => { + const assets = Array.from(list.querySelectorAll('input:checked'), input => + ({kind: input.dataset.kind, id: input.value}) + ); + const result = await api(endpoint('export'), {method: 'POST', body: JSON.stringify({assets})}); + download(result); + const bindings = result.bindings || []; + show([copy('已导出所选资产及项目内依赖。', 'Exported the selected assets and project dependencies.'), ...bindings.map(bindingText)].join('\n')); + })); + upload.addEventListener('change', () => work(async () => { + bundle = null; + const file = upload.files?.[0]; + if (!file) { + show(''); + return; + } + if (file.size > 96 * 1024 * 1024) throw new Error(copy('资产包超过 96 MiB。', 'The asset bundle exceeds 96 MiB.')); + const text = await file.text(); + const preview = await api(endpoint('preview'), {method: 'POST', body: text}); + const assets = preview.assets || []; + const bindings = preview.bindings || []; + show([ + copy('将导入 ' + assets.length + ' 项资产,LOOP 保存为项目私有草稿。', + 'Importing ' + assets.length + ' assets. LOOPs will be saved as project drafts.'), + ...assets.map(item => labelFor(item.kind) + ' · ' + item.name), + ...bindings.map(bindingText), + ].join('\n')); + bundle = text; + })); + importButton.addEventListener('click', () => work(async () => { + const result = await api(endpoint('import'), {method: 'POST', body: bundle}); + bundle = null; + upload.value = ''; + show(copy('已导入 ' + result.assets.length + ' 项私有资产。', 'Imported ' + result.assets.length + ' project assets.')); + try { + const fresh = await api('/api/bootstrap', {silent: true}); + Object.assign(state.data, fresh); + renderAll(); + renderChoices(); + } catch { + toast(copy('导入已完成。刷新页面后可查看新资产。', 'Import finished. Refresh to see the new assets.')); + } + })); + dialog.addEventListener('cancel', event => { + if (working) event.preventDefault(); + }); + dialog.querySelector('#closeAssetBundle').addEventListener('click', () => { + if (!working) dialog.close(); + }); +})(); diff --git a/web/i18n-en.js b/web/i18n-en.js index bcbb89c8d..f462d1903 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -1095,3 +1095,13 @@ Object.assign(window.LF_I18N_EN, { "在对话里澄清和改代码": "Clarify and change code in chat", "这条需求不使用 LOOP,在对话里澄清需求、直接改代码;定时任务不会自动认领它。": "This requirement uses no LOOP: clarify and change code in chat; scheduled jobs won't pick it up.", }); + +Object.assign(window.LF_I18N_EN, { + "资产包": "Asset bundles", + "项目资产包": "Project asset bundles", + "导出资产": "Export assets", + "下载资产包": "Download bundle", + "导入资产": "Import assets", + "选择 LoopForge 资产包": "Choose a LoopForge bundle", + "导入为项目私有副本": "Import as project copies", +}); diff --git a/web/index.html b/web/index.html index 1608a1709..80f4e58da 100644 --- a/web/index.html +++ b/web/index.html @@ -47,6 +47,7 @@ + @@ -408,7 +409,7 @@

运行记录生产流程

LOOP 流程

LOOP 是可复用的 AI 协作流程,由 Agent、脚本和人工审批节点组成:输入一条需求,按步骤产出文档、代码或 PR。

「本项目」的 LOOP 只在当前项目里用;共享后,其他项目可以在「团队共享」里选用;「内置」LOOP 由平台提供,复制到本项目后即可运行和修改。

-
+
@@ -1446,6 +1447,27 @@

确认操作

+ +
+

项目资产包

+

+ +
+
+

导出资产

+
+ +
+
+

导入资产

+ + +
+

+
+ From 6aed7446d2e0b2cdd86111501ea40d8ec7d81379 Mon Sep 17 00:00:00 2001 From: Robert0622 <53806540+Robert0622@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:48:52 +0800 Subject: [PATCH 2/4] fix(assets): normalize empty LOOP edges on import --- internal/httpapi/asset_bundle_test.go | 3 +++ internal/repo/asset_bundle_import.go | 3 +++ 2 files changed, 6 insertions(+) diff --git a/internal/httpapi/asset_bundle_test.go b/internal/httpapi/asset_bundle_test.go index cd02f97e3..63bd4079f 100644 --- a/internal/httpapi/asset_bundle_test.go +++ b/internal/httpapi/asset_bundle_test.go @@ -243,6 +243,9 @@ func TestProjectAssetBundlePreservesAutomaticExecutionSettings(t *testing.T) { if !ok || !v.AutoSelectSandbox || v.SandboxProfileID != "" { t.Fatal("the imported LOOP must select its sandbox at run time") } + if v.Edges == nil || len(v.Edges) != 0 { + t.Fatalf("a LOOP without edges must keep an empty array, got %#v", v.Edges) + } } } } diff --git a/internal/repo/asset_bundle_import.go b/internal/repo/asset_bundle_import.go index 679b4a589..1387afc61 100644 --- a/internal/repo/asset_bundle_import.go +++ b/internal/repo/asset_bundle_import.go @@ -388,6 +388,9 @@ func (p *bundleImport) save(r *CatalogRepo, b domain.ProjectAssetBundle) error { v.ID, v.ProjectID, v.Shared, v.Generic = p.id("sop", v.ID), p.target, false, false v.Status, v.Version, v.Revision, v.PublishedRevision = "draft", 1, 0, 0 v.SandboxProfileID = p.sandboxID(v) + if v.Edges == nil { + v.Edges = []domain.WorkflowEdge{} + } for i := range v.Nodes { n := &v.Nodes[i] if !domain.IsPreviewBuildAgent(n.AgentID) { From e2787a7f2aea7ef7cde4af319793c3169af706b0 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Fri, 27 Nov 2026 09:08:41 +0000 Subject: [PATCH 3/4] test(web): allow the page-scoped asset bundle stylesheet after issues-list.css asset-bundle.css only styles the .asset-bundle-* dialog and builds on the shared --hui-* tokens, like the other assets-page sheets the harness already allows after issues-list.css. Without it core failed in TestIssuesListStylesheetLoadsLast. Co-Authored-By: Claude Code --- web/issues_list_harness_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/issues_list_harness_test.go b/web/issues_list_harness_test.go index 80d8bdd85..58c6a7cdd 100644 --- a/web/issues_list_harness_test.go +++ b/web/issues_list_harness_test.go @@ -74,7 +74,7 @@ func TestIssuesListStylesheetLoadsLast(t *testing.T) { links := regexp.MustCompile(` 0 && pageSheets[links[len(links)-1][1]] { links = links[:len(links)-1] } From aaac455193de785dd64c1a6345c6b9a07605fa9b Mon Sep 17 00:00:00 2001 From: roberttwang Date: Fri, 27 Nov 2026 10:03:50 +0000 Subject: [PATCH 4/4] fix(assets): ignore other projects' global rules when exporting a LOOP Another project may bind its own global rule to a shared LOOP. Export walked every rule on the platform, so the source project got a 400 for a rule it can neither see nor remove. Only this project's global rules now travel with the LOOP; runtime injection already ignores the others. Also from review: - Preview runs the full save in a transaction and rolls it back, so role hooks and artifact paths that only PutAgent checks fail the preview too. - A dependency that is another project's shared asset or a platform template says it must be copied into the project first. A private asset of another project still reads like a missing one. - Import returns bindings that point at the new copies, and the dialog lists each asset as name -> new ID with its follow-up items. Co-Authored-By: Claude Code --- docs/api/openapi.yaml | 6 +- docs/api/registry.md | 6 +- internal/httpapi/asset_bundle.go | 6 +- internal/httpapi/asset_bundle_test.go | 140 ++++++++++++++++++++++++++ internal/repo/asset_bundle_export.go | 50 +++++++-- internal/repo/asset_bundle_import.go | 57 +++++++++-- web/app/asset-bundle.js | 37 ++++++- 7 files changed, 278 insertions(+), 24 deletions(-) diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index f19de971d..3c4805f9f 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -1944,7 +1944,7 @@ paths: post: tags: [Assets] operationId: exportProjectAssetBundle - description: Export the selected assets and their project-owned dependencies. Requires a project owner, maintainer, or platform administrator. + description: Export the selected assets and their project-owned dependencies. Global rules that other projects bind to a shared LOOP are not included. Requires a project owner, maintainer, or platform administrator. requestBody: required: true content: @@ -1989,7 +1989,7 @@ paths: post: tags: [Assets] operationId: previewProjectAssetBundle - description: Validate a bundle and preview assets and connection setup without writing to the project. Requires a project owner, maintainer, or platform administrator. + description: Validate a bundle and preview assets and connection setup. The import runs in a transaction that is rolled back, so nothing is written to the project. Requires a project owner, maintainer, or platform administrator. requestBody: required: true content: @@ -2022,7 +2022,7 @@ paths: post: tags: [Assets] operationId: importProjectAssetBundle - description: Create the project-owned copies in one transaction and rebind their references. LOOPs start as drafts. Requires a project owner, maintainer, or platform administrator. + description: Create the project-owned copies in one transaction and rebind their references. LOOPs start as drafts. Each asset reports its new targetId and each binding assetId names the imported copy. Requires a project owner, maintainer, or platform administrator. requestBody: required: true content: diff --git a/docs/api/registry.md b/docs/api/registry.md index 0c5b839f9..f68907ba7 100644 --- a/docs/api/registry.md +++ b/docs/api/registry.md @@ -181,15 +181,15 @@ LOOP 库右上角的「资产包」可单选或批量选择本项目的 Skill、 {"assets":[{"kind":"sop","id":"review-sop"},{"kind":"skill","id":"check-rules"}]} ``` -返回 `loopforge.project-assets/v1` JSON 文件,包含当前定义、附件和同项目依赖,包括角色引用的规则、LOOP 引用的子 LOOP,以及自定义沙箱及其 Dockerfile 构建上下文。平台内置沙箱使用目标环境中的对应配置。其他项目资产和平台通用模板需要先复制到当前项目。 +返回 `loopforge.project-assets/v1` JSON 文件,包含当前定义、附件和同项目依赖,包括角色引用的规则、LOOP 引用的子 LOOP,以及自定义沙箱及其 Dockerfile 构建上下文。平台内置沙箱使用目标环境中的对应配置。其他项目资产和平台通用模板需要先复制到当前项目,否则返回 `400` 并指出是哪一项。LOOP 只带上本项目绑定到它的全局规则,其他项目绑定到共享 LOOP 的全局规则不会进入资产包,也不影响导出。 ### `POST /api/projects/{id}/asset-bundles/preview` -请求体为整个资产包。成功时返回 `assets` 清单和 `bindings` 重配项(包含 `kind` 和 `assetId`),此请求不写入项目。附件校验 SHA‑256 和路径。包最多包含 200 项资产及依赖、64 MiB 附件和 96 MiB JSON。 +请求体为整个资产包。成功时返回 `assets` 清单和 `bindings` 重配项(包含 `kind` 和 `assetId`)。预览会在事务中完整执行一次导入再回滚,导入时会失败的定义(如角色 Hook 语言、产物路径)在预览时同样返回 `400`,此请求不写入项目。附件校验 SHA‑256 和路径。包最多包含 200 项资产及依赖、64 MiB 附件和 96 MiB JSON。 ### `POST /api/projects/{id}/asset-bundles/import` -请求体与预览相同。成功返回 `201`,`assets` 中包含各项的 `targetId`。资产包整体导入为项目私有副本并自动重绑包内引用。LOOP 保存为草稿,有子 LOOP 时按依赖顺序重配连接和发布。每次导入创建一套新副本。 +请求体与预览相同。成功返回 `201`,`assets` 中包含各项的 `targetId`,`bindings` 的 `assetId` 改为导入后副本的新 ID。资产包整体导入为项目私有副本并自动重绑包内引用。LOOP 保存为草稿,有子 LOOP 时按依赖顺序重配连接和发布。每次导入创建一套新副本。 项目 MCP 的 Headers、环境变量值、URL 中的认证信息和查询参数,以及项目凭据、知识库和通知绑定需要在目标项目重配。Skill 与 MCP 附件按原始字节导出。只在受信任项目间交付经过审查的资产包,正文和可执行文件中的自带内容会随包迁移。 diff --git a/internal/httpapi/asset_bundle.go b/internal/httpapi/asset_bundle.go index 286cc26e4..2c37992f2 100644 --- a/internal/httpapi/asset_bundle.go +++ b/internal/httpapi/asset_bundle.go @@ -112,8 +112,12 @@ func (h *assetBundleHandlers) importBundle(c *gin.Context, save bool) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } + bindings := bundle.Bindings + if save { + bindings = repo.ImportedBundleBindings(assets, bindings) + } c.Header("Cache-Control", "private, no-store") - c.JSON(status, gin.H{"assets": assets, "bindings": bundle.Bindings}) + c.JSON(status, gin.H{"assets": assets, "bindings": bindings}) } func readAssetBundleJSON(c *gin.Context, value any, limit int64) bool { diff --git a/internal/httpapi/asset_bundle_test.go b/internal/httpapi/asset_bundle_test.go index 63bd4079f..316967179 100644 --- a/internal/httpapi/asset_bundle_test.go +++ b/internal/httpapi/asset_bundle_test.go @@ -249,3 +249,143 @@ func TestProjectAssetBundlePreservesAutomaticExecutionSettings(t *testing.T) { } } } + +func TestProjectAssetBundleExportIgnoresOtherProjectsGlobalRules(t *testing.T) { + f := cvBNewHTTPFixture(t) + save := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + save(f.s.PutProject(domain.Project{ID: "bundle-shared-src", Name: "Source", OwnerID: f.user.ID})) + save(f.s.PutProject(domain.Project{ID: "bundle-other", Name: "Other", OwnerID: f.user.ID + 99})) + save(f.s.PutAgent(domain.AgentDefinition{ID: "shared-src-role", Name: "Reviewer", ProjectID: "bundle-shared-src"})) + save(f.s.PutWorkflow(domain.WorkflowDefinition{ + ID: "shared-src-loop", Name: "Shared LOOP", ProjectID: "bundle-shared-src", Shared: true, AutoSelectSandbox: true, + Nodes: []domain.WorkflowNode{{ID: "review", Name: "Review", Type: "agent", AgentID: "shared-src-role"}}, + })) + save(f.s.PutRule(domain.RuleDefinition{ + ID: "shared-src-own-rule", Name: "Own", ProjectID: "bundle-shared-src", Global: true, + WorkflowIDs: []string{"shared-src-loop"}, Content: "Own rule.", + })) + // Another project binds its own global rule to the shared LOOP. The source + // project cannot see or remove it, so it must not block or join the export. + save(f.s.PutRule(domain.RuleDefinition{ + ID: "other-global-rule", Name: "Other", ProjectID: "bundle-other", Global: true, + WorkflowIDs: []string{"shared-src-loop"}, Content: "Other project rule.", + })) + res := cvBRequest(t, f, "POST", "/api/projects/bundle-shared-src/asset-bundles/export", + map[string]any{"assets": []domain.BundleAssetRef{{Kind: "sop", ID: "shared-src-loop"}}}, true) + if res.Code != http.StatusOK { + t.Fatalf("export: %d %s", res.Code, res.Body.String()) + } + var bundle domain.ProjectAssetBundle + if err := json.Unmarshal(res.Body.Bytes(), &bundle); err != nil { + t.Fatal(err) + } + if len(bundle.Rules) != 1 || bundle.Rules[0].ID != "shared-src-own-rule" || strings.Contains(res.Body.String(), "other-global-rule") { + t.Fatalf("export must carry only this project's global rules: %+v", bundle.Rules) + } +} + +func TestProjectAssetBundleExplainsForeignDependencies(t *testing.T) { + f := cvBNewHTTPFixture(t) + save := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + save(f.s.PutProject(domain.Project{ID: "bundle-borrower", Name: "Borrower", OwnerID: f.user.ID})) + save(f.s.PutAgent(domain.AgentDefinition{ID: "lender-role", Name: "Shared role", ProjectID: "bundle-lender", Shared: true})) + save(f.s.PutWorkflow(domain.WorkflowDefinition{ + ID: "borrower-loop", Name: "Borrower LOOP", ProjectID: "bundle-borrower", AutoSelectSandbox: true, + Nodes: []domain.WorkflowNode{{ID: "review", Name: "Review", Type: "agent", AgentID: "lender-role"}}, + })) + path := "/api/projects/bundle-borrower/asset-bundles/export" + res := cvBRequest(t, f, "POST", path, map[string]any{"assets": []domain.BundleAssetRef{{Kind: "sop", ID: "borrower-loop"}}}, true) + if res.Code != http.StatusBadRequest || !strings.Contains(res.Body.String(), "agent/lender-role") || + !strings.Contains(res.Body.String(), "请先复制到当前项目") { + t.Fatalf("a shared role from another project needs a copy hint: %d %s", res.Code, res.Body.String()) + } + // A private asset of another project must read exactly like a missing one. + save(f.s.PutSkill(domain.SkillDefinition{ID: "lender-private", Name: "Private", ProjectID: "bundle-lender"})) + errorFor := func(id string) string { + t.Helper() + res := cvBRequest(t, f, "POST", path, map[string]any{"assets": []domain.BundleAssetRef{{Kind: "skill", ID: id}}}, true) + if res.Code != http.StatusBadRequest { + t.Fatalf("export skill %s: %d %s", id, res.Code, res.Body.String()) + } + return strings.ReplaceAll(res.Body.String(), id, "") + } + if hidden, missing := errorFor("lender-private"), errorFor("missing-skill"); hidden != missing || strings.Contains(hidden, "复制") { + t.Fatalf("a private foreign asset is distinguishable from a missing one: %s vs %s", hidden, missing) + } +} + +func TestProjectAssetBundlePreviewRunsTheSave(t *testing.T) { + f := cvBNewHTTPFixture(t) + if err := f.s.PutProject(domain.Project{ID: "bundle-dry-run", Name: "Dry run", OwnerID: f.user.ID}); err != nil { + t.Fatal(err) + } + tgt := "/api/projects/bundle-dry-run/asset-bundles/" + bundle := func(role domain.AgentDefinition) domain.ProjectAssetBundle { + return domain.ProjectAssetBundle{ + Format: domain.ProjectAssetBundleFormat, + Agents: []domain.AgentDefinition{role}, + Workflows: []domain.WorkflowDefinition{{ + ID: "dry-loop", Name: "Dry LOOP", AutoSelectSandbox: true, + Nodes: []domain.WorkflowNode{{ID: "review", Name: "Review", Type: "agent", AgentID: role.ID}}, + }}, + Bindings: []domain.BundleBinding{{Kind: "loop-integrations", AssetID: "dry-loop"}}, + } + } + for name, role := range map[string]domain.AgentDefinition{ + "hook language": {ID: "dry-role", Name: "Role", Hooks: []domain.AgentHook{{ID: "h1", Name: "bad", Event: "Stop", Language: "ruby", Script: "puts 1"}}}, + "artifact path": {ID: "dry-role", Name: "Role", ArtifactOutputs: []domain.ArtifactContract{{Name: "x", Path: "../escape"}}}, + } { + res := cvBRequest(t, f, "POST", tgt+"preview", bundle(role), true) + if res.Code != http.StatusBadRequest { + t.Fatalf("preview accepted an invalid %s: %d %s", name, res.Code, res.Body.String()) + } + } + valid := bundle(domain.AgentDefinition{ID: "dry-role", Name: "Role"}) + res := cvBRequest(t, f, "POST", tgt+"preview", valid, true) + if res.Code != http.StatusOK || strings.Contains(res.Body.String(), "targetId") { + t.Fatalf("preview: %d %s", res.Code, res.Body.String()) + } + for _, workflow := range f.s.Workflows() { + if workflow.ProjectID == "bundle-dry-run" { + t.Fatal("preview persisted a LOOP") + } + } + for _, role := range f.s.Agents() { + if role.ProjectID == "bundle-dry-run" { + t.Fatal("preview persisted a role") + } + } + res = cvBRequest(t, f, "POST", tgt+"import", valid, true) + if res.Code != http.StatusCreated { + t.Fatalf("import: %d %s", res.Code, res.Body.String()) + } + var result struct { + Assets []domain.BundleAssetSummary + Bindings []domain.BundleBinding + } + if err := json.Unmarshal(res.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + loopID := "" + for _, asset := range result.Assets { + if asset.Kind == "sop" { + loopID = asset.TargetID + } + } + if loopID == "" || len(result.Bindings) != 1 || result.Bindings[0].AssetID != loopID { + t.Fatalf("import bindings must point at the imported copy: %+v", result) + } + if workflow, ok := f.s.Workflow(loopID); !ok || workflow.ProjectID != "bundle-dry-run" { + t.Fatal("import did not save the LOOP") + } +} diff --git a/internal/repo/asset_bundle_export.go b/internal/repo/asset_bundle_export.go index ed84c09cc..cd07d18b9 100644 --- a/internal/repo/asset_bundle_export.go +++ b/internal/repo/asset_bundle_export.go @@ -75,13 +75,28 @@ func (x *bundleExport) add(kind, id string) error { } x.seen[ref] = true missing := fmt.Errorf("资产或依赖 %s/%s 不属于当前项目或已不存在", kind, id) + // owned rejects assets of other projects. Only assets this project can + // already see (shared or platform-wide) get the copy hint; a private asset + // of another project reads exactly like a missing one. + owned := func(projectID string, visible bool) error { + if projectID == x.project { + return nil + } + if visible { + return fmt.Errorf("资产或依赖 %s/%s 来自其他项目的共享资产或平台通用模板,请先复制到当前项目再导出", kind, id) + } + return missing + } r := x.catalog switch kind { case "skill": v, ok := r.Skill(id) - if !ok || v.ProjectID != x.project { + if !ok { return missing } + if err := owned(v.ProjectID, v.Shared || v.ProjectID == ""); err != nil { + return err + } files, err := collectBundleFiles(x, v.FileRefs, r.SkillFileContents(id), func(ref domain.SkillFileRef) (string, string, uint32) { return ref.Path, ref.SHA256, ref.Mode }) @@ -92,9 +107,12 @@ func (x *bundleExport) add(kind, id string) error { x.bundle.Skills = append(x.bundle.Skills, domain.BundleSkill{SkillDefinition: v, Attachments: files}) case "mcp": v, ok := r.MCPServer(id) - if !ok || v.ProjectID != x.project || v.Scope == "personal" { + if !ok || v.Scope == "personal" { return missing } + if err := owned(v.ProjectID, v.ProjectID == ""); err != nil { + return err + } files, err := collectBundleFiles(x, v.FileRefs, r.MCPFileContents(id), func(ref domain.MCPFileRef) (string, string, uint32) { return ref.Path, ref.SHA256, ref.Mode }) @@ -108,9 +126,12 @@ func (x *bundleExport) add(kind, id string) error { x.bundle.MCPServers = append(x.bundle.MCPServers, domain.BundleMCPServer{MCPServerDefinition: v, Attachments: files}) case "agent": v, ok := r.Agent(id) - if !ok || v.ProjectID != x.project { + if !ok { return missing } + if err := owned(v.ProjectID, v.Shared || v.ProjectID == ""); err != nil { + return err + } for _, dependencies := range []struct { kind string ids []string @@ -130,9 +151,15 @@ func (x *bundleExport) add(kind, id string) error { x.bundle.Agents = append(x.bundle.Agents, v) case "sop": v, ok := r.Workflow(id) - if !ok || v.ProjectID != x.project || v.Generic { + if !ok { return missing } + if v.Generic { + return owned("", true) + } + if err := owned(v.ProjectID, v.Shared || v.ProjectID == ""); err != nil { + return err + } if !v.AutoSelectSandbox && !builtinBundleSandbox(v.SandboxProfileID) { if err := x.add("sandbox", v.SandboxProfileID); err != nil { return err @@ -150,8 +177,11 @@ func (x *bundleExport) add(kind, id string) error { } } } + // Other projects may bind their own global rules to a shared LOOP. + // Those rules belong to the other project, so only this project's + // global rules travel with the LOOP. for _, rule := range r.Rules() { - if rule.Global && slices.Contains(rule.WorkflowIDs, id) { + if rule.Global && rule.ProjectID == x.project && slices.Contains(rule.WorkflowIDs, id) { if err := x.add("rule", rule.ID); err != nil { return err } @@ -164,16 +194,22 @@ func (x *bundleExport) add(kind, id string) error { x.bundle.Workflows = append(x.bundle.Workflows, v) case "rule": v, ok := r.Rule(id) - if !ok || v.ProjectID != x.project { + if !ok { return missing } + if err := owned(v.ProjectID, v.Shared || v.ProjectID == ""); err != nil { + return err + } v.ProjectID, v.Shared = "", false x.bundle.Rules = append(x.bundle.Rules, v) case "sandbox": v, ok := r.Sandbox(id) - if !ok || v.ProjectID != x.project { + if !ok { return missing } + if err := owned(v.ProjectID, v.Shared || v.ProjectID == ""); err != nil { + return err + } if len(v.Environment) != 0 { x.binding("sandbox-environment", id) } diff --git a/internal/repo/asset_bundle_import.go b/internal/repo/asset_bundle_import.go index 1387afc61..27879091a 100644 --- a/internal/repo/asset_bundle_import.go +++ b/internal/repo/asset_bundle_import.go @@ -3,6 +3,7 @@ package repo import ( "crypto/rand" "crypto/sha256" + "errors" "fmt" "path" "regexp" @@ -24,18 +25,28 @@ type bundleImport struct { fileSize int64 } +// errBundlePreviewRollback discards the dry-run save of a preview. +var errBundlePreviewRollback = errors.New("asset bundle preview rollback") + +// PreviewProjectAssetBundle runs the complete import inside a transaction and +// rolls it back, so the checks that only the save path performs (role hooks, +// artifact paths, sandbox lookups) fail the preview instead of the import. func (r *CatalogRepo) PreviewProjectAssetBundle(project string, bundle domain.ProjectAssetBundle) ([]domain.BundleAssetSummary, error) { - plan, err := r.prepareProjectAssetBundle(project, bundle, "preview") + plan, err := r.importProjectAssetBundle(project, bundle, false) if err != nil { return nil, err } - for i := range plan.summary { - plan.summary[i].TargetID = "" + for i := range plan { + plan[i].TargetID = "" } - return plan.summary, nil + return plan, nil } func (r *CatalogRepo) ImportProjectAssetBundle(project string, bundle domain.ProjectAssetBundle) ([]domain.BundleAssetSummary, error) { + return r.importProjectAssetBundle(project, bundle, true) +} + +func (r *CatalogRepo) importProjectAssetBundle(project string, bundle domain.ProjectAssetBundle, commit bool) ([]domain.BundleAssetSummary, error) { var nonce [12]byte if _, err := rand.Read(nonce[:]); err != nil { return nil, err @@ -44,11 +55,45 @@ func (r *CatalogRepo) ImportProjectAssetBundle(project string, bundle domain.Pro if err != nil { return nil, err } - return plan.summary, r.DB.Transaction(func(tx *gorm.DB) error { + err = r.DB.Transaction(func(tx *gorm.DB) error { catalog := *r catalog.deps = &deps{DB: tx} - return plan.save(&catalog, bundle) + if err := plan.save(&catalog, bundle); err != nil { + return err + } + if !commit { + return errBundlePreviewRollback + } + return nil }) + if errors.Is(err, errBundlePreviewRollback) { + err = nil + } + if err != nil { + return nil, err + } + return plan.summary, nil +} + +// ImportedBundleBindings points each follow-up item at the imported copy, +// so the caller can configure the asset by its new ID. +func ImportedBundleBindings(assets []domain.BundleAssetSummary, bindings []domain.BundleBinding) []domain.BundleBinding { + kinds := map[string]string{ + "mcp-connection": "mcp", "role-integrations": "agent", "loop-integrations": "sop", + "sandbox-environment": "sandbox", "sandbox-privileged": "sandbox", + } + targets := make(map[domain.BundleAssetRef]string, len(assets)) + for _, asset := range assets { + targets[asset.BundleAssetRef] = asset.TargetID + } + out := make([]domain.BundleBinding, 0, len(bindings)) + for _, binding := range bindings { + if id := targets[assetRef(kinds[binding.Kind], binding.AssetID)]; id != "" { + binding.AssetID = id + } + out = append(out, binding) + } + return out } func (r *CatalogRepo) prepareProjectAssetBundle(project string, b domain.ProjectAssetBundle, prefix string) (*bundleImport, error) { diff --git a/web/app/asset-bundle.js b/web/app/asset-bundle.js index ea64c45c7..14b0a8ec6 100644 --- a/web/app/asset-bundle.js +++ b/web/app/asset-bundle.js @@ -39,7 +39,29 @@ }[kind] || kind; } - function bindingText({kind, assetId}) { + const bindingAssetKinds = { + 'mcp-connection': 'mcp', 'role-integrations': 'agent', 'loop-integrations': 'sop', + 'sandbox-environment': 'sandbox', 'sandbox-privileged': 'sandbox', + }; + + // Name the asset a follow-up item points at. Preview bindings carry the + // bundle ID and import bindings carry the new ID of the imported copy. + function bindingTarget({kind, assetId}, assets) { + const assetKind = bindingAssetKinds[kind]; + const asset = (assets || []).find(item => item.kind === assetKind && + (item.targetId ? item.targetId === assetId : item.id === assetId)); + if (!asset) return assetId; + return asset.targetId ? asset.name + ' (' + asset.targetId + ')' : asset.name; + } + + function exportedAssets(value) { + return [['sop', 'workflows'], ['agent', 'agents'], ['mcp', 'mcpServers'], ['sandbox', 'sandboxes']] + .flatMap(([kind, collection]) => (value[collection] || []).map(item => ({kind, id: item.id, name: item.name}))); + } + + function bindingText(binding, assets) { + const {kind} = binding; + const assetId = bindingTarget(binding, assets); const label = { 'mcp-connection': copy('配置 MCP 连接及凭据', 'Configure the MCP connection and credentials'), 'role-integrations': copy('核对角色的平台 MCP 和知识库绑定', 'Review platform MCP and knowledge bindings for the role'), @@ -135,7 +157,7 @@ const result = await api(endpoint('export'), {method: 'POST', body: JSON.stringify({assets})}); download(result); const bindings = result.bindings || []; - show([copy('已导出所选资产及项目内依赖。', 'Exported the selected assets and project dependencies.'), ...bindings.map(bindingText)].join('\n')); + show([copy('已导出所选资产及项目内依赖。', 'Exported the selected assets and project dependencies.'), ...bindings.map(item => bindingText(item, exportedAssets(result)))].join('\n')); })); upload.addEventListener('change', () => work(async () => { bundle = null; @@ -153,7 +175,7 @@ copy('将导入 ' + assets.length + ' 项资产,LOOP 保存为项目私有草稿。', 'Importing ' + assets.length + ' assets. LOOPs will be saved as project drafts.'), ...assets.map(item => labelFor(item.kind) + ' · ' + item.name), - ...bindings.map(bindingText), + ...bindings.map(item => bindingText(item, assets)), ].join('\n')); bundle = text; })); @@ -161,7 +183,14 @@ const result = await api(endpoint('import'), {method: 'POST', body: bundle}); bundle = null; upload.value = ''; - show(copy('已导入 ' + result.assets.length + ' 项私有资产。', 'Imported ' + result.assets.length + ' project assets.')); + const assets = result.assets || []; + const bindings = result.bindings || []; + show([ + copy('已导入 ' + assets.length + ' 项私有资产(名称 → 新 ID):', 'Imported ' + assets.length + ' project assets (name → new ID):'), + ...assets.map(item => labelFor(item.kind) + ' · ' + item.name + ' → ' + item.targetId), + ...(bindings.length ? [copy('导入后需配置:', 'Configure after import:')] : []), + ...bindings.map(item => bindingText(item, assets)), + ].join('\n')); try { const fresh = await api('/api/bootstrap', {silent: true}); Object.assign(state.data, fresh);