Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(skills): import skills from a .skill/.zip archive (#4735)

Bohan Jiangb90816264ed0
diff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.go
index 23da0a03e4..0d62925fd3 100644
--- a/server/cmd/multica/cmd_skill.go
+++ b/server/cmd/multica/cmd_skill.go
@@ -9,6 +9,7 @@ import (
"io"
"net/url"
"os"
+ "path/filepath"
"strings"
"time"
"unicode/utf8"
@@ -58,7 +59,7 @@ var skillDeleteCmd = &cobra.Command{
var skillImportCmd = &cobra.Command{
Use: "import",
- Short: "Import a skill from a URL (clawhub.ai, skills.sh, or github.com)",
+ Short: "Import a skill from a URL (clawhub.ai, skills.sh, github.com) or a local .skill/.zip archive",
RunE: runSkillImport,
}
@@ -139,7 +140,8 @@ func init() {
skillDeleteCmd.Flags().Bool("yes", false, "Skip confirmation prompt")
// skill import
- skillImportCmd.Flags().String("url", "", "URL to import from (required)")
+ skillImportCmd.Flags().String("url", "", "URL to import from (clawhub.ai, skills.sh, or github.com). Mutually exclusive with --file.")
+ skillImportCmd.Flags().String("file", "", "Path to a local skill archive (.skill or .zip) to import. Mutually exclusive with --url.")
skillImportCmd.Flags().String("on-conflict", "fail", "Conflict strategy when a skill with the same name exists: fail, overwrite, rename, or skip")
skillImportCmd.Flags().String("output", "json", "Output format: table or json")
@@ -416,23 +418,40 @@ func runSkillImport(cmd *cobra.Command, _ []string) error {
}
importURL, _ := cmd.Flags().GetString("url")
- if importURL == "" {
- return fmt.Errorf("--url is required")
+ importFile, _ := cmd.Flags().GetString("file")
+ switch {
+ case importURL == "" && importFile == "":
+ return fmt.Errorf("either --url or --file is required")
+ case importURL != "" && importFile != "":
+ return fmt.Errorf("--url and --file are mutually exclusive")
}
onConflict, _ := cmd.Flags().GetString("on-conflict")
if !validSkillImportConflictStrategy(onConflict) {
return fmt.Errorf("--on-conflict must be one of: fail, overwrite, rename, skip")
}
- body := map[string]any{
- "url": importURL,
- "on_conflict": onConflict,
- }
-
ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))
defer cancel()
var result map[string]any
+ if importFile != "" {
+ fileData, readErr := os.ReadFile(importFile)
+ if readErr != nil {
+ return fmt.Errorf("read skill archive: %w", readErr)
+ }
+ if err := client.ImportSkillFile(ctx, fileData, filepath.Base(importFile), onConflict, &result); err != nil {
+ if handledErr := handleSkillImportError(cmd, err); handledErr != nil {
+ return handledErr
+ }
+ return fmt.Errorf("import skill: %w", err)
+ }
+ return printSkillImportResult(cmd, result)
+ }
+
+ body := map[string]any{
+ "url": importURL,
+ "on_conflict": onConflict,
+ }
if err := client.PostJSON(ctx, "/api/skills/import", body, &result); err != nil {
if handledErr := handleSkillImportError(cmd, err); handledErr != nil {
return handledErr
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index 575610692b..d73e95a037 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -529,6 +529,64 @@ func (c *APIClient) UploadFileWithURL(ctx context.Context, fileData []byte, file
return result.ID, result.URL, nil
}
+// ImportSkillFile imports a skill from a local archive (.skill / .zip) by
+// POSTing it as multipart/form-data to /api/skills/import, alongside the
+// on_conflict strategy. The structured import result is decoded into out.
+func (c *APIClient) ImportSkillFile(ctx context.Context, fileData []byte, filename, onConflict string, out any) error {
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+
+ part, err := writer.CreateFormFile("file", filepath.Base(filename))
+ if err != nil {
+ return fmt.Errorf("create form file: %w", err)
+ }
+ if _, err := part.Write(fileData); err != nil {
+ return fmt.Errorf("write file data: %w", err)
+ }
+ if onConflict != "" {
+ if err := writer.WriteField("on_conflict", onConflict); err != nil {
+ return fmt.Errorf("write on_conflict field: %w", err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ return fmt.Errorf("close multipart writer: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/api/skills/import", &body)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ c.setHeaders(req)
+
+ // Respect a longer context deadline for slow uploads, mirroring
+ // UploadFileWithURL: the default client timeout would otherwise shadow it.
+ httpClient := c.HTTPClient
+ if deadline, ok := ctx.Deadline(); ok {
+ remaining := time.Until(deadline)
+ if remaining > httpClient.Timeout {
+ clientCopy := *httpClient
+ clientCopy.Timeout = remaining
+ httpClient = &clientCopy
+ }
+ }
+
+ resp, err := httpClient.Do(req)
+ err = wrapTransport(req, err)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ return newHTTPError(http.MethodPost, "/api/skills/import", resp)
+ }
+ if out == nil {
+ return nil
+ }
+ return json.NewDecoder(resp.Body).Decode(out)
+}
+
// DownloadFile downloads a file from the given URL and returns the response body.
// This is used for downloading attachments via their signed download_url.
// Downloads are limited to 100 MB to match the upload size limit.
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 56e0ca6926..971fea9cac 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -1918,6 +1918,14 @@ func (h *Handler) ImportSkill(w http.ResponseWriter, r *http.Request) {
}
creatorUUID := parseUUID(creatorID)
+ // An uploaded skill archive (.skill / .zip) arrives as multipart/form-data;
+ // a hosted-URL import arrives as JSON. Both converge on the same create +
+ // conflict tail via finishSkillImport.
+ if isMultipartForm(r) {
+ h.importSkillFromArchive(w, r, workspaceID, workspaceUUID, creatorUUID, creatorID)
+ return
+ }
+
var req ImportSkillRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -1955,6 +1963,15 @@ func (h *Handler) ImportSkill(w http.ResponseWriter, r *http.Request) {
return
}
+ h.finishSkillImport(w, r, workspaceID, workspaceUUID, creatorUUID, creatorID, strategy, structuredResult, imported)
+}
+
+// finishSkillImport runs the shared tail of every skill import — whether the
+// bundle came from a hosted URL or an uploaded archive (.skill / .zip). It maps
+// the extracted files onto CreateSkillFileRequest, records provenance into
+// config.origin, and creates the skill, routing same-name collisions through
+// the on_conflict strategy.
+func (h *Handler) finishSkillImport(w http.ResponseWriter, r *http.Request, workspaceID string, workspaceUUID, creatorUUID pgtype.UUID, creatorID, strategy string, structuredResult bool, imported *importedSkill) {
files := make([]CreateSkillFileRequest, 0, len(imported.files))
for _, f := range imported.files {
if !validateFilePath(f.path) {
diff --git a/server/internal/handler/skill_import_archive.go b/server/internal/handler/skill_import_archive.go
new file mode 100644
index 0000000000..196a337622
--- /dev/null
+++ b/server/internal/handler/skill_import_archive.go
@@ -0,0 +1,255 @@
+package handler
+
+import (
+ "archive/zip"
+ "bytes"
+ "fmt"
+ "io"
+ "net/http"
+ "path"
+ "sort"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ skillpkg "github.com/multica-ai/multica/server/internal/skill"
+)
+
+// maxImportArchiveUploadSize bounds the compressed upload accepted by the
+// archive import path. The decompressed bundle is still held to the existing
+// per-file / total / file-count caps (maxImportFileSize, maxImportTotalSize,
+// maxImportFileCount); this outer cap just stops a client from streaming an
+// unbounded compressed body before those decompression limits can apply.
+const maxImportArchiveUploadSize = 16 << 20 // 16 MiB
+
+// isMultipartForm reports whether the request carries a multipart/form-data
+// body (an uploaded skill archive) rather than the JSON URL-import body.
+func isMultipartForm(r *http.Request) bool {
+ return strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data")
+}
+
+// importSkillFromArchive handles POST /api/skills/import when the body is an
+// uploaded skill archive (.skill / .zip). It reads the file plus the optional
+// on_conflict form field, decompresses the archive into an importedSkill, and
+// hands off to the shared finishSkillImport tail. The archive path always
+// produces structured (status / skill / existing_skill) results — there is no
+// legacy pre-on_conflict client for it to stay compatible with.
+func (h *Handler) importSkillFromArchive(w http.ResponseWriter, r *http.Request, workspaceID string, workspaceUUID, creatorUUID pgtype.UUID, creatorID string) {
+ r.Body = http.MaxBytesReader(w, r.Body, maxImportArchiveUploadSize)
+ if err := r.ParseMultipartForm(maxImportArchiveUploadSize); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid multipart upload or file exceeds the size limit")
+ return
+ }
+ defer func() {
+ if r.MultipartForm != nil {
+ _ = r.MultipartForm.RemoveAll()
+ }
+ }()
+
+ onConflict := r.FormValue("on_conflict")
+ if !validImportOnConflict(onConflict) {
+ writeError(w, http.StatusBadRequest, "on_conflict must be one of: fail, overwrite, rename, skip")
+ return
+ }
+ strategy := onConflict
+ if strategy == "" {
+ strategy = importOnConflictFail
+ }
+
+ file, header, err := r.FormFile("file")
+ if err != nil {
+ writeError(w, http.StatusBadRequest, `a skill archive file is required (form field "file")`)
+ return
+ }
+ defer file.Close()
+
+ data, err := io.ReadAll(file)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "failed to read uploaded file")
+ return
+ }
+
+ filename := ""
+ if header != nil {
+ filename = header.Filename
+ }
+ imported, err := parseSkillArchive(data, filename)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+
+ h.finishSkillImport(w, r, workspaceID, workspaceUUID, creatorUUID, creatorID, strategy, true, imported)
+}
+
+// parseSkillArchive decompresses an uploaded skill archive (.skill / .zip) into
+// an importedSkill. A .skill file is a standard zip whose entries sit either at
+// the archive root (SKILL.md, scripts/...) or nested under a single top-level
+// directory (my-skill/SKILL.md, my-skill/scripts/...) — the layout produced by
+// Anthropic's package_skill. Both are accepted by rooting on the shallowest
+// SKILL.md found.
+//
+// Safety: every entry is validated against traversal / absolute paths
+// (zip-slip), the reserved SKILL.md supporting path is dropped, per-file size is
+// bounded while reading (so a lying zip header can't blow up memory), and the
+// shared addFile enforces the per-bundle byte and file-count caps.
+func parseSkillArchive(data []byte, filename string) (*importedSkill, error) {
+ zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return nil, fmt.Errorf("uploaded file is not a valid .skill/.zip archive")
+ }
+
+ // Locate the skill root: the directory of the shallowest SKILL.md. This
+ // accepts both a root-level SKILL.md and the common single-wrapper layout.
+ // The candidate path is validated up front (absolute / traversal entries are
+ // rejected) so a malicious archive cannot smuggle an unsafe path in as the
+ // primary content — keeping every accepted entry zip-slip-safe.
+ var skillMd *zip.File
+ rootPrefix := ""
+ for _, f := range zr.File {
+ if f.FileInfo().IsDir() {
+ continue
+ }
+ clean := path.Clean(f.Name)
+ if !strings.EqualFold(path.Base(clean), skillpkg.ContentFilename) {
+ continue
+ }
+ if !validateFilePath(clean) {
+ continue
+ }
+ prefix := archiveEntryPrefix(clean)
+ if skillMd == nil || len(prefix) < len(rootPrefix) {
+ skillMd = f
+ rootPrefix = prefix
+ }
+ }
+ if skillMd == nil {
+ return nil, fmt.Errorf("archive does not contain a SKILL.md")
+ }
+
+ content, err := readZipFile(skillMd, maxImportFileSize)
+ if err != nil {
+ return nil, fmt.Errorf("read SKILL.md: %w", err)
+ }
+
+ name, description := skillpkg.ParseSkillFrontmatter(content)
+ if name == "" {
+ name = skillNameFromArchive(rootPrefix, filename)
+ }
+ if name == "" {
+ return nil, fmt.Errorf("could not determine the skill name: SKILL.md has no name field and the archive is unnamed")
+ }
+
+ imported := &importedSkill{
+ name: name,
+ description: description,
+ content: content,
+ }
+
+ for _, f := range zr.File {
+ if f.FileInfo().IsDir() {
+ continue
+ }
+ clean := path.Clean(f.Name)
+ // Only files under the resolved skill root belong to this skill.
+ if rootPrefix != "" && !strings.HasPrefix(clean, rootPrefix) {
+ continue
+ }
+ rel := strings.TrimPrefix(clean, rootPrefix)
+ if rel == "" {
+ continue
+ }
+ // A SKILL.md at any depth is never a supporting file: the top-level one
+ // is the primary content, and a nested one would collide with the
+ // reserved primary-content name. Mirrors the daemon's local-skill rule.
+ if strings.EqualFold(path.Base(rel), skillpkg.ContentFilename) {
+ continue
+ }
+ if isIgnoredArchiveEntry(rel) {
+ continue
+ }
+ // zip-slip / absolute-path guard.
+ if !validateFilePath(rel) {
+ continue
+ }
+ fileContent, ferr := readZipFile(f, maxImportFileSize)
+ if ferr != nil {
+ // An oversize or unreadable individual asset is skipped rather than
+ // failing the whole import, matching the local-runtime importer.
+ continue
+ }
+ // addFile enforces the per-bundle caps and drops binary assets; a cap
+ // breach aborts the import instead of silently truncating it.
+ if err := imported.addFile(rel, fileContent); err != nil {
+ return nil, err
+ }
+ }
+
+ sort.Slice(imported.files, func(i, j int) bool {
+ return imported.files[i].path < imported.files[j].path
+ })
+ return imported, nil
+}
+
+// archiveEntryPrefix returns the directory prefix (with trailing slash) of a
+// cleaned, slash-delimited archive entry: "" for a root entry, "my-skill/" for
+// "my-skill/SKILL.md".
+func archiveEntryPrefix(cleanName string) string {
+ dir := path.Dir(cleanName)
+ if dir == "." || dir == "/" {
+ return ""
+ }
+ return dir + "/"
+}
+
+// skillNameFromArchive derives a fallback skill name when SKILL.md carries no
+// name field: the wrapper directory name if the skill is nested, else the
+// uploaded filename without its extension.
+func skillNameFromArchive(rootPrefix, filename string) string {
+ if rootPrefix != "" {
+ base := path.Base(strings.TrimSuffix(rootPrefix, "/"))
+ if base != "." && base != "/" && base != ".." {
+ return base
+ }
+ }
+ clean := strings.ReplaceAll(filename, "\\", "/")
+ base := path.Base(clean)
+ if ext := path.Ext(base); ext != "" {
+ base = strings.TrimSuffix(base, ext)
+ }
+ return strings.TrimSpace(base)
+}
+
+// isIgnoredArchiveEntry filters editor/OS noise and license files out of the
+// supporting bundle, mirroring the daemon's local-skill discovery rules.
+func isIgnoredArchiveEntry(rel string) bool {
+ for _, seg := range strings.Split(rel, "/") {
+ if seg == "" || seg == "__MACOSX" || strings.HasPrefix(seg, ".") {
+ return true
+ }
+ }
+ switch strings.ToLower(path.Base(rel)) {
+ case "license", "license.md", "license.txt":
+ return true
+ }
+ return false
+}
+
+// readZipFile reads a single zip entry, capping the read at maxSize+1 bytes so a
+// header that under-reports its uncompressed size cannot force an unbounded
+// allocation. Entries larger than maxSize are rejected.
+func readZipFile(f *zip.File, maxSize int64) (string, error) {
+ rc, err := f.Open()
+ if err != nil {
+ return "", err
+ }
+ defer rc.Close()
+
+ data, err := io.ReadAll(io.LimitReader(rc, maxSize+1))
+ if err != nil {
+ return "", err
+ }
+ if int64(len(data)) > maxSize {
+ return "", fmt.Errorf("file %q exceeds %d bytes", f.Name, maxSize)
+ }
+ return string(data), nil
+}
diff --git a/server/internal/handler/skill_import_archive_test.go b/server/internal/handler/skill_import_archive_test.go
new file mode 100644
index 0000000000..0ab1ed052e
--- /dev/null
+++ b/server/internal/handler/skill_import_archive_test.go
@@ -0,0 +1,312 @@
+package handler
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// buildTestZip packs the given path->content map into an in-memory zip and
+// returns its bytes. A path ending in "/" is written as a directory entry.
+func buildTestZip(t *testing.T, entries map[string]string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, content := range entries {
+ if strings.HasSuffix(name, "/") {
+ if _, err := zw.Create(name); err != nil {
+ t.Fatalf("create dir entry %q: %v", name, err)
+ }
+ continue
+ }
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatalf("create entry %q: %v", name, err)
+ }
+ if _, err := w.Write([]byte(content)); err != nil {
+ t.Fatalf("write entry %q: %v", name, err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatalf("close zip: %v", err)
+ }
+ return buf.Bytes()
+}
+
+func filePaths(imported *importedSkill) []string {
+ paths := make([]string, 0, len(imported.files))
+ for _, f := range imported.files {
+ paths = append(paths, f.path)
+ }
+ return paths
+}
+
+func fileContent(imported *importedSkill, path string) (string, bool) {
+ for _, f := range imported.files {
+ if f.path == path {
+ return f.content, true
+ }
+ }
+ return "", false
+}
+
+const testSkillMd = `---
+name: review-helper
+description: Reviews code changes
+---
+
+# Review Helper
+
+Do the review.
+`
+
+func TestParseSkillArchive_NestedWrapper(t *testing.T) {
+ data := buildTestZip(t, map[string]string{
+ "review-helper/": "",
+ "review-helper/SKILL.md": testSkillMd,
+ "review-helper/scripts/run.sh": "echo hi",
+ "review-helper/references/g.md": "guide",
+ })
+
+ imported, err := parseSkillArchive(data, "review-helper.skill")
+ if err != nil {
+ t.Fatalf("parseSkillArchive: %v", err)
+ }
+ if imported.name != "review-helper" {
+ t.Errorf("name = %q, want review-helper", imported.name)
+ }
+ if imported.description != "Reviews code changes" {
+ t.Errorf("description = %q", imported.description)
+ }
+ if !strings.Contains(imported.content, "# Review Helper") {
+ t.Errorf("content missing SKILL.md body: %q", imported.content)
+ }
+ got := filePaths(imported)
+ want := map[string]bool{"scripts/run.sh": true, "references/g.md": true}
+ if len(got) != len(want) {
+ t.Fatalf("files = %v, want keys %v", got, want)
+ }
+ for _, p := range got {
+ if !want[p] {
+ t.Errorf("unexpected file %q (SKILL.md must not be a supporting file)", p)
+ }
+ }
+ if c, ok := fileContent(imported, "scripts/run.sh"); !ok || c != "echo hi" {
+ t.Errorf("scripts/run.sh content = %q, ok=%v", c, ok)
+ }
+}
+
+func TestParseSkillArchive_RootLayout(t *testing.T) {
+ data := buildTestZip(t, map[string]string{
+ "SKILL.md": testSkillMd,
+ "references/doc.md": "doc",
+ })
+ imported, err := parseSkillArchive(data, "anything.zip")
+ if err != nil {
+ t.Fatalf("parseSkillArchive: %v", err)
+ }
+ if imported.name != "review-helper" {
+ t.Errorf("name = %q, want review-helper", imported.name)
+ }
+ if got := filePaths(imported); len(got) != 1 || got[0] != "references/doc.md" {
+ t.Errorf("files = %v, want [references/doc.md]", got)
+ }
+}
+
+func TestParseSkillArchive_NoSkillMd(t *testing.T) {
+ data := buildTestZip(t, map[string]string{
+ "my-skill/notes.md": "hello",
+ })
+ if _, err := parseSkillArchive(data, "x.skill"); err == nil {
+ t.Fatal("expected error when archive has no SKILL.md")
+ }
+}
+
+func TestParseSkillArchive_InvalidZip(t *testing.T) {
+ if _, err := parseSkillArchive([]byte("not a zip"), "x.skill"); err == nil {
+ t.Fatal("expected error for non-zip data")
+ }
+}
+
+func TestParseSkillArchive_RejectsUnsafeSkillMdPath(t *testing.T) {
+ // A SKILL.md whose only candidate path is absolute or traversal must not be
+ // accepted as the primary content; the archive is treated as having none.
+ for _, name := range []string{"../escape/SKILL.md", "/abs/SKILL.md"} {
+ data := buildTestZip(t, map[string]string{name: testSkillMd})
+ if _, err := parseSkillArchive(data, "x.skill"); err == nil {
+ t.Errorf("expected rejection for unsafe SKILL.md path %q", name)
+ }
+ }
+}
+
+func TestParseSkillArchive_DropsTraversalAndJunk(t *testing.T) {
+ data := buildTestZip(t, map[string]string{
+ "s/SKILL.md": testSkillMd,
+ "s/../evil.sh": "pwn", // zip-slip out of the skill root
+ "s/.git/config": "secret", // dotfile dir
+ "s/.DS_Store": "junk", // dotfile
+ "__MACOSX/s/._x": "applemeta", // mac noise (outside root anyway)
+ "s/LICENSE": "MIT", // license excluded
+ "s/keep.md": "real", // legitimate asset
+ })
+ imported, err := parseSkillArchive(data, "s.skill")
+ if err != nil {
+ t.Fatalf("parseSkillArchive: %v", err)
+ }
+ got := filePaths(imported)
+ if len(got) != 1 || got[0] != "keep.md" {
+ t.Fatalf("files = %v, want only [keep.md]", got)
+ }
+}
+
+func TestParseSkillArchive_SkipsBinaryAssets(t *testing.T) {
+ data := buildTestZip(t, map[string]string{
+ "s/SKILL.md": testSkillMd,
+ "s/logo.png": "\x89PNG\x00binary",
+ "s/note.txt": "text",
+ })
+ imported, err := parseSkillArchive(data, "s.skill")
+ if err != nil {
+ t.Fatalf("parseSkillArchive: %v", err)
+ }
+ if got := filePaths(imported); len(got) != 1 || got[0] != "note.txt" {
+ t.Errorf("files = %v, want [note.txt] (binary png dropped)", got)
+ }
+}
+
+func TestParseSkillArchive_NameFallbackToWrapperDir(t *testing.T) {
+ noName := "# Title only\n\nNo frontmatter name here.\n"
+ data := buildTestZip(t, map[string]string{
+ "cool-skill/SKILL.md": noName,
+ })
+ imported, err := parseSkillArchive(data, "ignored.skill")
+ if err != nil {
+ t.Fatalf("parseSkillArchive: %v", err)
+ }
+ if imported.name != "cool-skill" {
+ t.Errorf("name = %q, want cool-skill (wrapper dir fallback)", imported.name)
+ }
+}
+
+func TestParseSkillArchive_NameFallbackToFilename(t *testing.T) {
+ noName := "# Title only\n"
+ data := buildTestZip(t, map[string]string{
+ "SKILL.md": noName,
+ })
+ imported, err := parseSkillArchive(data, "My-Thing.skill")
+ if err != nil {
+ t.Fatalf("parseSkillArchive: %v", err)
+ }
+ if imported.name != "My-Thing" {
+ t.Errorf("name = %q, want My-Thing (filename fallback)", imported.name)
+ }
+}
+
+// --- Handler-level tests: the multipart /api/skills/import archive path ---
+
+func skillMdWithName(name, desc string) string {
+ return "---\nname: " + name + "\ndescription: " + desc + "\n---\n\n# " + name + "\n\nBody.\n"
+}
+
+func newSkillArchiveImportRequest(userID string, archive []byte, filename, onConflict string) *http.Request {
+ var buf bytes.Buffer
+ writer := multipart.NewWriter(&buf)
+ part, _ := writer.CreateFormFile("file", filename)
+ _, _ = part.Write(archive)
+ if onConflict != "" {
+ _ = writer.WriteField("on_conflict", onConflict)
+ }
+ _ = writer.Close()
+
+ req := httptest.NewRequest(http.MethodPost, "/api/skills/import", &buf)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", userID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ return req
+}
+
+func TestImportSkill_ArchiveUploadCreatesSkill(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test DB not configured")
+ }
+ name := "archive-create-" + t.Name()
+ archive := buildTestZip(t, map[string]string{
+ name + "/SKILL.md": skillMdWithName(name, "From archive"),
+ name + "/scripts/run.sh": "echo hi",
+ })
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM skill WHERE workspace_id = $1 AND name = $2`, testWorkspaceID, name)
+ })
+
+ w := httptest.NewRecorder()
+ testHandler.ImportSkill(w, newSkillArchiveImportRequest(testUserID, archive, name+".skill", "fail"))
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201: %s", w.Code, w.Body.String())
+ }
+ var body SkillImportResult
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if body.Status != "created" || body.Skill == nil {
+ t.Fatalf("body = %#v", body)
+ }
+ if body.Skill.Name != name {
+ t.Errorf("name = %q, want %q", body.Skill.Name, name)
+ }
+ found := false
+ for _, f := range body.Skill.Files {
+ if f.Path == "scripts/run.sh" {
+ found = true
+ }
+ }
+ if !found {
+ t.Errorf("scripts/run.sh missing from imported files: %#v", body.Skill.Files)
+ }
+}
+
+func TestImportSkill_ArchiveUploadConflictSkip(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test DB not configured")
+ }
+ namePrefix := "archive-skip"
+ skillName := namePrefix + "-" + t.Name()
+ existingID := insertHandlerTestSkill(t, namePrefix, "# Existing")
+ archive := buildTestZip(t, map[string]string{
+ skillName + "/SKILL.md": skillMdWithName(skillName, "From archive"),
+ })
+
+ w := httptest.NewRecorder()
+ testHandler.ImportSkill(w, newSkillArchiveImportRequest(testUserID, archive, skillName+".skill", "skip"))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var body SkillImportResult
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if body.Status != "skipped" {
+ t.Fatalf("status = %q, want skipped", body.Status)
+ }
+ if body.ExistingSkill == nil || body.ExistingSkill.ID != existingID {
+ t.Fatalf("existing_skill = %#v", body.ExistingSkill)
+ }
+}
+
+func TestImportSkill_ArchiveUploadRejectsNonZip(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test DB not configured")
+ }
+ w := httptest.NewRecorder()
+ testHandler.ImportSkill(w, newSkillArchiveImportRequest(testUserID, []byte("not a zip at all"), "bad.skill", "fail"))
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md b/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
index c38c8bcaa8..b7cadc4dac 100644
--- a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
@@ -22,19 +22,26 @@ Every claim below is traced to source in
A skill is installed for Multica only when it exists in the current workspace's
skill database. The single supported path that puts it there is the workspace
-import endpoint, driven by this CLI:
+import endpoint. It accepts either a hosted URL or an uploaded local archive
+(`.skill` / `.zip`), driven by this CLI:
```bash
-multica skill import --url <url> --output json
+multica skill import --url <url> --output json # hosted source
+multica skill import --file <path-to.skill> --output json # local archive
```
-The CLI defaults to `--on-conflict fail`. Current CLIs send:
+The CLI defaults to `--on-conflict fail`. A URL import sends:
```text
POST /api/skills/import
+Content-Type: application/json
body: { "url": "<url>", "on_conflict": "fail" }
```
+A `--file` import hits the same route as `multipart/form-data` with a `file`
+part (the `.skill` / `.zip` bytes) and an `on_conflict` field. `--url` and
+`--file` are mutually exclusive; exactly one is required.
+
Do not finish with `npx skills add`. That installs into an external/local skill
environment, not the Multica workspace DB, so Multica cannot manage or bind it.
@@ -57,6 +64,29 @@ multica skill import --url github.com/owner/repo/blob/main/path/to/SKILL.md --ou
- A bare ClawHub slug (no host) is accepted and routed to ClawHub.
- Any other host is rejected with a 400 naming the supported sources.
+## Local archive import (`.skill` / `.zip`)
+
+`multica skill import --file <path> --output json` imports a skill from a local
+archive instead of a hosted URL. A `.skill` file is a standard zip — the format
+Anthropic's skill-creator `package_skill` produces — and a plain `.zip` of a
+skill folder works too. The server:
+
+- accepts the upload as `multipart/form-data` (a `file` part plus an optional
+ `on_conflict` field) on the same `POST /api/skills/import` route;
+- decompresses it and roots on the shallowest `SKILL.md`, so both a root-level
+ `SKILL.md` and the nested `my-skill/SKILL.md` wrapper layout are accepted;
+- takes the name/description from `SKILL.md` frontmatter, falling back to the
+ wrapper directory name and then the uploaded filename;
+- carries the supporting files — dropping any `SKILL.md`, dotfiles, `__MACOSX`,
+ license files, and binary assets — under the same per-file (1 MiB),
+ per-bundle (8 MiB), and file-count (128) caps as URL imports, and rejects path
+ traversal (zip-slip);
+- returns the same structured result envelope and honors the same
+ `--on-conflict` strategies as URL imports.
+
+The upload itself is capped at 16 MiB (compressed). Any source that is not a
+local archive still goes through `--url`.
+
## Direct URL flow
1. When the request contains a concrete URL, the import endpoint can be called
diff --git a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
index b24ab662d8..a475ed6e19 100644
--- a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
+++ b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
@@ -28,19 +28,40 @@ grep -n "func IsReservedContentPath" server/internal/skill/reserved.go
| Legacy success: `201 Created` with bare `SkillWithFilesResponse` when `on_conflict` was omitted | `server/internal/handler/skill.go:1990` |
| Route registration `r.Post("/import", h.ImportSkill)` | `server/cmd/server/router.go:874` |
-## CLI: `multica skill import --url`
+Note: `ImportSkill` now branches on content type. A multipart body routes to the
+archive path (below); a JSON body keeps the URL flow. Both converge on the shared
+`finishSkillImport` tail. Line numbers in this table predate that split — re-grep
+`func (h *Handler) ImportSkill` / `finishSkillImport` to re-derive.
+
+## Local archive import (`.skill` / `.zip`)
+
+| Behavior | File:line |
+|---|---|
+| `ImportSkill` branches to the archive path on multipart bodies | `server/internal/handler/skill.go:1924` (`if isMultipartForm(r)`) |
+| Shared create + conflict tail `finishSkillImport` (URL and archive) | `server/internal/handler/skill.go:1974` |
+| `isMultipartForm` content-type check | `server/internal/handler/skill_import_archive.go:26` |
+| `importSkillFromArchive` (multipart parse + `MaxBytesReader` + `on_conflict` + `file`) | `server/internal/handler/skill_import_archive.go:36` |
+| Upload cap `maxImportArchiveUploadSize` (16 MiB compressed) | `server/internal/handler/skill_import_archive.go:22` |
+| `parseSkillArchive` (zip decode, shallowest-`SKILL.md` root, frontmatter name, zip-slip + reserved + ignore filters) | `server/internal/handler/skill_import_archive.go:95` |
+| Reuses per-file / per-bundle / count caps via `importedSkill.addFile` | `server/internal/handler/skill.go:618` (`maxImportFileSize`/`maxImportTotalSize`/`maxImportFileCount` at `:579-583`) |
+| Name fallback (wrapper dir, then filename) | `server/internal/handler/skill_import_archive.go:201` |
+| Ignore filter (dotfiles, `__MACOSX`, license) | `server/internal/handler/skill_import_archive.go:218` |
+| Per-entry size-capped read | `server/internal/handler/skill_import_archive.go:234` |
+| Tests (parser units + handler multipart create/skip/reject) | `server/internal/handler/skill_import_archive_test.go` |
+
+## CLI: `multica skill import --url` / `--file`
| Behavior | File:line |
|---|---|
-| `skill import` command def | `server/cmd/multica/cmd_skill.go:60-64` |
-| `--url` flag | `server/cmd/multica/cmd_skill.go:142` |
-| `--on-conflict` flag (default `fail`) | `server/cmd/multica/cmd_skill.go:143` |
-| `--output` flag (default `json`) | `server/cmd/multica/cmd_skill.go:144` |
+| `skill import` command def | `server/cmd/multica/cmd_skill.go:59-63` |
+| `--url` flag | `server/cmd/multica/cmd_skill.go:143` |
+| `--file` flag (local `.skill` / `.zip`; mutually exclusive with `--url`) | `server/cmd/multica/cmd_skill.go:144` |
+| `--on-conflict` flag (default `fail`) | `server/cmd/multica/cmd_skill.go:145` |
+| `--output` flag (default `json`) | `server/cmd/multica/cmd_skill.go:146` |
| `runSkillImport` | `server/cmd/multica/cmd_skill.go:412` |
-| Requires `--url` | `server/cmd/multica/cmd_skill.go:418-421` |
-| Reads and validates `--on-conflict` | `server/cmd/multica/cmd_skill.go:422-425` |
-| Sends `on_conflict` in the request body | `server/cmd/multica/cmd_skill.go:428-431` |
-| `POST /api/skills/import` | `server/cmd/multica/cmd_skill.go:436` |
+| Requires exactly one of `--url` / `--file` | `server/cmd/multica/cmd_skill.go:420-427` |
+| `--file` reads the archive and posts multipart via `ImportSkillFile` | `server/cmd/multica/cmd_skill.go:436-447`, client method `server/internal/cli/client.go:535` |
+| `POST /api/skills/import` (URL, JSON body) | `server/cmd/multica/cmd_skill.go:455` |
| Structured HTTP error body handling | `server/cmd/multica/cmd_skill.go:437-440`, `handleSkillImportError` at `:454` |
| Prints structured result (`json` or table) | `server/cmd/multica/cmd_skill.go:443`, helper at `:497` |