Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8493: fix(skills): show skill import limit errors in the CLI and raise the file-count cap to 512 (#9823)
Bohan Jiangf3b434e2d273
diff --git a/packages/core/skills/pack-archive.ts b/packages/core/skills/pack-archive.tsindex abaa79e6c5..61185ab2c1 100644--- a/packages/core/skills/pack-archive.ts+++ b/packages/core/skills/pack-archive.ts@@ -5,7 +5,7 @@ export const MAX_SKILL_FILE_BYTES = 1 << 20; // 1 MiB/** Mirrors server/internal/handler maxImportTotalSize (supporting files). */export const MAX_SKILL_BUNDLE_BYTES = 8 << 20; // 8 MiB/** Mirrors server/internal/handler maxImportFileCount. */-export const MAX_SKILL_FILE_COUNT = 256;+export const MAX_SKILL_FILE_COUNT = 512;/** Mirrors server/internal/handler maxImportArchiveUploadSize. */export const MAX_SKILL_ARCHIVE_BYTES = 16 << 20; // 16 MiBdiff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.goindex 5073368114..a6e94d245f 100644--- a/server/cmd/multica/cmd_skill.go+++ b/server/cmd/multica/cmd_skill.go@@ -7,6 +7,7 @@ import ("errors""fmt""io"+ "net/http""net/url""os""path/filepath"@@ -480,7 +481,7 @@ func runSkillRefresh(cmd *cobra.Command, args []string) error {var result map[string]anyif err := client.PostJSON(ctx, "/api/skills/"+args[0]+"/refresh", map[string]any{}, &result); err != nil {- return fmt.Errorf("refresh skill: %w", err)+ return withSkillSourceMessage("Skill refresh failed: ", fmt.Errorf("refresh skill: %w", err))}output, _ := cmd.Flags().GetString("output")@@ -537,7 +538,7 @@ func runSkillImport(cmd *cobra.Command, _ []string) error {if handledErr := handleSkillImportError(cmd, err); handledErr != nil {return handledErr}- return fmt.Errorf("import skill: %w", err)+ return withSkillSourceMessage("Skill import failed: ", fmt.Errorf("import skill: %w", err))}return printSkillImportResult(cmd, result)@@ -581,6 +582,31 @@ func handleSkillImportError(cmd *cobra.Command, err error) error {return errors.New(reason)}+// withSkillSourceMessage surfaces the server's explanation when fetching a+// skill from its upstream source fails. The import and refresh endpoints answer+// such failures with 502 (source error, e.g. SKILL.md not found at that path),+// 503 (source temporarily unavailable, usually GitHub rate limiting) or 504+// (fetch deadline exceeded), each with a hand-written message. The generic 5xx+// copy says the Multica service is unavailable, which points the user at the+// wrong system. A body without a message (a proxy's own 502/504 page) keeps the+// generic copy.+func withSkillSourceMessage(leadIn string, err error) error {+ var httpErr *cli.HTTPError+ if !errors.As(err, &httpErr) {+ return err+ }+ switch httpErr.StatusCode {+ case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:+ default:+ return err+ }+ msg := cli.ServerMessage(err)+ if msg == "" {+ return err+ }+ return cli.WithUserMessage(leadIn+msg, err)+}+func normalizeLegacySkillImportConflict(body map[string]any) map[string]any {reason := strVal(body, "error")if reason == "" {diff --git a/server/cmd/multica/cmd_skill_test.go b/server/cmd/multica/cmd_skill_test.goindex 6c4cc3228f..6b4e155da7 100644--- a/server/cmd/multica/cmd_skill_test.go+++ b/server/cmd/multica/cmd_skill_test.go@@ -10,6 +10,8 @@ import ("testing""github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli")func newSkillImportTestCmd() *cobra.Command {@@ -172,6 +174,122 @@ func TestRunSkillImportSendsOnConflictAndPrintsStructuredResult(t *testing.T) {}}+// The user-visible line for a failed URL import or refresh is FormatError of+// the returned error. Each case is a response the import/refresh endpoints+// actually write (see importFetchErrorResponse), plus a proxy's own 502 page,+// which has no message and must keep the generic copy (GH #9812).+var skillSourceErrorCases = []struct {+ name string+ status int+ body string+ want string // FormatError output after the per-command lead-in+}{+ {+ name: "413 over file-count cap",+ status: http.StatusRequestEntityTooLarge,+ body: `{"error":"import cap exceeded: import bundle would contain 600 files, exceeding the 512 file limit"}`,+ want: "Request too large: import cap exceeded: import bundle would contain 600 files, exceeding the 512 file limit",+ },+ {+ name: "502 source error",+ status: http.StatusBadGateway,+ body: `{"error":"SKILL.md not found at skills/foo in acme/skills@main"}`,+ want: "{leadIn}SKILL.md not found at skills/foo in acme/skills@main",+ },+ {+ name: "503 source unavailable",+ status: http.StatusServiceUnavailable,+ body: `{"error":"import source temporarily unavailable: could not read the acme/skills repository tree"}`,+ want: "{leadIn}import source temporarily unavailable: could not read the acme/skills repository tree",+ },+ {+ name: "504 fetch deadline",+ status: http.StatusGatewayTimeout,+ body: `{"error":"skill import timed out fetching source files; the skill may be too large or the source too slow"}`,+ want: "{leadIn}skill import timed out fetching source files; the skill may be too large or the source too slow",+ },+ {+ name: "proxy 502 page keeps generic copy",+ status: http.StatusBadGateway,+ body: `<html><body>502 Bad Gateway</body></html>`,+ want: "The Multica service is temporarily unavailable (server error). Please try again later; if it persists, contact support. Re-run with --debug to see the raw server response.",+ },+}++func newSkillSourceErrorServer(t *testing.T, wantPath string, status int, body string) *httptest.Server {+ t.Helper()+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != wantPath {+ t.Fatalf("path = %q, want %q", r.URL.Path, wantPath)+ }+ if strings.HasPrefix(body, "{") {+ w.Header().Set("Content-Type", "application/json")+ }+ w.WriteHeader(status)+ _, _ = io.WriteString(w, body)+ }))+}++func setEnglishLocale(t *testing.T) {+ t.Helper()+ t.Setenv("LC_ALL", "")+ t.Setenv("LC_MESSAGES", "")+ t.Setenv("LANG", "en_US.UTF-8")+}++func TestRunSkillImportSurfacesSourceFetchErrors(t *testing.T) {+ for _, tc := range skillSourceErrorCases {+ t.Run(tc.name, func(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ setEnglishLocale(t)+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")+ srv := newSkillSourceErrorServer(t, "/api/skills/import", tc.status, tc.body)+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newSkillImportTestCmd()+ _ = cmd.Flags().Set("url", "https://github.com/acme/skills/tree/main/skills/foo")+ _, err := captureStdout(t, func() error { return runSkillImport(cmd, nil) })+ if err == nil {+ t.Fatal("expected import to fail")+ }+ want := strings.ReplaceAll(tc.want, "{leadIn}", "Skill import failed: ")+ if got := cli.FormatError(err, false); got != want {+ t.Errorf("FormatError = %q, want %q", got, want)+ }+ })+ }+}++func TestRunSkillRefreshSurfacesSourceFetchErrors(t *testing.T) {+ for _, tc := range skillSourceErrorCases {+ t.Run(tc.name, func(t *testing.T) {+ redirectTestHome(t, t.TempDir())+ setEnglishLocale(t)+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")+ srv := newSkillSourceErrorServer(t, "/api/skills/skill-123/refresh", tc.status, tc.body)+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := &cobra.Command{Use: "refresh"}+ cmd.Flags().String("server-url", "", "")+ cmd.Flags().String("workspace-id", "", "")+ cmd.Flags().String("profile", "", "")+ cmd.Flags().String("output", "table", "")+ _, err := captureStdout(t, func() error { return runSkillRefresh(cmd, []string{"skill-123"}) })+ if err == nil {+ t.Fatal("expected refresh to fail")+ }+ want := strings.ReplaceAll(tc.want, "{leadIn}", "Skill refresh failed: ")+ if got := cli.FormatError(err, false); got != want {+ t.Errorf("FormatError = %q, want %q", got, want)+ }+ })+ }+}+func TestRunSkillSearchRequestsSearchEndpoint(t *testing.T) {var gotPath stringsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/cli/errors.go b/server/internal/cli/errors.goindex a592f11bea..e6874a71e0 100644--- a/server/internal/cli/errors.go+++ b/server/internal/cli/errors.go@@ -57,6 +57,7 @@ const (KindNotFound // 404KindConflict // 409KindValidation // 400 / 422+ KindTooLarge // 413KindRateLimited // 429KindServerError // 5xx@@ -114,6 +115,8 @@ func (k ErrorKind) String() string {return "conflict"case KindValidation:return "validation"+ case KindTooLarge:+ return "too_large"case KindRateLimited:return "rate_limited"case KindServerError:@@ -212,6 +215,8 @@ func (e *HTTPError) Kind() ErrorKind {return KindConflictcase 400, 422:return KindValidation+ case 413:+ return KindTooLargecase 429:return KindRateLimiteddefault:@@ -444,6 +449,10 @@ var kindMessages = map[ErrorKind][2]string{"The request was invalid. Check the values you provided; run the command with --help to see the expected format.","请求无效。请检查所填写的参数;可用 --help 查看期望的格式。",},+ KindTooLarge: {+ "The request is larger than the server accepts. Reduce its size and try again. Re-run with --debug to see the raw server response.",+ "请求超出服务器允许的大小。请缩小后重试。可加 --debug 查看服务器原始响应。",+ },KindRateLimited: {"Too many requests. Please wait a moment and try again; if this keeps happening, reduce how frequently you call the API.","请求过于频繁。请稍候重试;若持续出现,请降低 API 调用频率。",@@ -469,9 +478,15 @@ var kindMessages = map[ErrorKind][2]string{// already exists", "set parent_id (--parent) to <id>"). Agents took the retry// hint literally and burned hours re-sending an unchanged request (GH #6264,// GH #5948), and the server-side wording added in MUL-4417 never reached them.+//+// 413 belongs here because the server names the limit that was hit and the+// size that hit it. Before 413 had a kind, a skill import over the file-count+// cap printed "An unexpected error occurred." for a URL import while the same+// bundle as a ZIP (rejected with 400) printed the limit (GH #9812).var serverMessagePrefixes = map[ErrorKind][2]string{KindValidation: {"Invalid request: ", "请求无效:"},KindConflict: {"Request conflict: ", "请求冲突:"},+ KindTooLarge: {"Request too large: ", "请求过大:"},}// messageFor returns the localized message for a kind.@@ -605,6 +620,22 @@ func extractServerMessage(body string) string {return code}+// ServerMessage returns the human-readable message a server error body+// carries, or "" when err is not an HTTP failure or the body has none (an HTML+// proxy page, an empty body).+//+// It exists for a command whose endpoint writes actionable prose on a status+// whose generic copy is deliberately vague. A 5xx from most routes means "the+// Multica service failed"; a 5xx from skill import means "the upstream source+// failed", and the server names which one and why.+func ServerMessage(err error) string {+ var httpErr *HTTPError+ if !errors.As(err, &httpErr) {+ return ""+ }+ return extractServerMessage(httpErr.Body)+}+// ServerErrorCode returns the stable `code` a server error body carries, or ""// when err is not an HTTP failure or the body has no code.//diff --git a/server/internal/cli/errors_test.go b/server/internal/cli/errors_test.goindex a1f9bf9997..bf78260a09 100644--- a/server/internal/cli/errors_test.go+++ b/server/internal/cli/errors_test.go@@ -70,6 +70,7 @@ func TestHTTPErrorKind(t *testing.T) {{409, KindConflict},{400, KindValidation},{422, KindValidation},+ {413, KindTooLarge},{429, KindRateLimited},{500, KindServerError},{502, KindServerError},@@ -93,7 +94,7 @@ func TestFormatErrorAllKinds(t *testing.T) {allKinds := []ErrorKind{KindNetworkTimeout, KindNetworkDNS, KindNetworkRefused, KindNetworkTLS, KindNetworkOffline, KindNetworkTLSHandshakeTimeout,KindAuthRequired, KindTaskTokenRejected, KindForbidden, KindNotFound, KindConflict,- KindValidation, KindRateLimited, KindServerError, KindUnknown,+ KindValidation, KindTooLarge, KindRateLimited, KindServerError, KindUnknown,}for _, lang := range []Language{LangEN, LangZH} {for _, k := range allKinds {@@ -202,6 +203,66 @@ func TestFormatErrorConflictFallsBackToGenericTemplate(t *testing.T) {}}+// TestFormatErrorTooLargeUsesServerMessage pins GH #9812: a URL skill import+// over the file-count cap answers 413 with the count and the limit, and the CLI+// printed "An unexpected error occurred." because 413 had no kind. The same+// bundle as a ZIP (rejected with 400) already printed the limit.+func TestFormatErrorTooLargeUsesServerMessage(t *testing.T) {+ const serverMsg = "import cap exceeded: import bundle would contain 600 files, exceeding the 512 file limit"+ httpErr := &HTTPError{+ Method: "POST",+ Path: "/api/skills/import",+ StatusCode: 413,+ Body: `{"error":"` + serverMsg + `"}`,+ }+ wrapped := fmt.Errorf("import skill: %w", httpErr)++ withLang(t, "en_US.UTF-8")+ if got, want := FormatError(wrapped, false), "Request too large: "+serverMsg; got != want {+ t.Errorf("EN: got %q, want %q", got, want)+ }+ withLang(t, "zh_CN.UTF-8")+ if got, want := FormatError(wrapped, false), "请求过大:"+serverMsg; got != want {+ t.Errorf("ZH: got %q, want %q", got, want)+ }+}++// A 413 a proxy writes itself (nginx's client_max_body_size page) has no JSON+// message, so it gets the generic size copy, never the raw page.+func TestFormatErrorTooLargeFallsBackToGenericTemplate(t *testing.T) {+ withLang(t, "en_US.UTF-8")+ for _, body := range []string{+ `<html><body><h1>413 Request Entity Too Large</h1></body></html>`,+ ``,+ } {+ got := FormatError(&HTTPError{StatusCode: 413, Body: body}, false)+ if got != messageFor(KindTooLarge, LangEN) {+ t.Errorf("body %q: expected generic too-large template, got %q", body, got)+ }+ }+}++func TestServerMessage(t *testing.T) {+ cases := []struct {+ name string+ err error+ want string+ }{+ {"json error", fmt.Errorf("refresh skill: %w", &HTTPError{StatusCode: 503, Body: `{"error":"import source temporarily unavailable"}`}), "import source temporarily unavailable"},+ {"html page", &HTTPError{StatusCode: 502, Body: `<html>502 Bad Gateway</html>`}, ""},+ {"empty body", &HTTPError{StatusCode: 504}, ""},+ {"not http", errors.New("boom"), ""},+ {"nil", nil, ""},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := ServerMessage(tc.err); got != tc.want {+ t.Errorf("ServerMessage() = %q, want %q", got, tc.want)+ }+ })+ }+}+// TestExtractServerMessagePrefersProseOverMachineCode covers the endpoints that// put a stable code in "error" and the sentence in "message" (issue-table// cursor responses). The sentence is what helps a person.@@ -287,6 +348,7 @@ func TestExitCodeFor(t *testing.T) {{"validation 400", &HTTPError{StatusCode: 400}, ExitValidation},{"validation 422", &HTTPError{StatusCode: 422}, ExitValidation},{"conflict 409", &HTTPError{StatusCode: 409}, ExitGeneric},+ {"too large 413", &HTTPError{StatusCode: 413}, ExitGeneric},{"rate limited 429", &HTTPError{StatusCode: 429}, ExitGeneric},{"server 500", &HTTPError{StatusCode: 500}, ExitGeneric},{"plain", errors.New("boom"), ExitGeneric},@@ -398,6 +460,7 @@ func TestErrorKindString(t *testing.T) {KindNotFound: "not_found",KindConflict: "conflict",KindValidation: "validation",+ KindTooLarge: "too_large",KindRateLimited: "rate_limited",KindServerError: "server_error",KindUnknown: "unknown",@@ -505,6 +568,7 @@ func TestFormatErrorActionableHints(t *testing.T) {{409, []string{"conflict", "again"}, []string{"冲突", "重新获取"}},{400, []string{"--help", "expected format"}, []string{"--help", "格式", "参数"}},{422, []string{"--help", "expected format"}, []string{"--help", "格式", "参数"}},+ {413, []string{"larger than the server accepts", "--debug"}, []string{"超出", "--debug"}},{429, []string{"Too many requests"}, []string{"过于频繁"}},{500, []string{"temporarily unavailable", "--debug"}, []string{"暂时不可用", "--debug"}},}diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.goindex c4bff5b59a..12fc40af99 100644--- a/server/internal/daemon/local_skills.go+++ b/server/internal/daemon/local_skills.go@@ -23,7 +23,7 @@ const (// Kept in lockstep with the server-side importer's maxImportFileCount so a// skill that imports from a URL/archive also imports from a runtime-local// directory. The 8 MiB bundle cap is the real guard on skill size.- maxLocalSkillFileCount = 256+ maxLocalSkillFileCount = 512// Cap how deep skill discovery descends below a runtime root. opencode// stores skills two levels deep (e.g. `release/reporter/SKILL.md`); a// few extra levels covers any realistic future layout while boundingdiff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex 0d03b38cc4..b0ab2410fe 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -771,7 +771,7 @@ func validImportOnConflict(strategy string) bool {const (maxImportFileSize = 1 << 20 // 1 MiB per filemaxImportTotalSize = 8 << 20 // 8 MiB per import bundle (sum of supporting files)- maxImportFileCount = 256 // max number of supporting files+ maxImportFileCount = 512 // max number of supporting files)// importedSkill holds the data extracted from an external source.@@ -1463,7 +1463,7 @@ func acceptConventionalSkillDir(ctx context.Context, httpClient *http.Client, ra// treeDownloadConcurrency bounds how many supporting files are downloaded in// parallel during tree-based collection. Small enough that one import cannot// open hundreds of sockets to GitHub at once, large enough to keep the download-// phase well under the overall import deadline for a full (256-file) bundle.+// phase well under the overall import deadline for a full (512-file) bundle.const treeDownloadConcurrency = 8// addSupportingFilesFromTree enumerates the supporting files under skillDir fromdiff --git a/server/internal/handler/skill_test.go b/server/internal/handler/skill_test.goindex f2865f2e66..9b1b72a439 100644--- a/server/internal/handler/skill_test.go+++ b/server/internal/handler/skill_test.go@@ -540,7 +540,7 @@ func TestFetchFromSkillsSh_TreeTotalByteCapFailsFast(t *testing.T) {}}-// A skill under the raised 256-file cap imports its full supporting-file set+// A skill under the file-count cap imports its full supporting-file set// from the tree via concurrent downloads, in a stable path order regardless of// completion timing.func TestFetchFromSkillsSh_TreeEnumerationImportsManyFiles(t *testing.T) {diff --git a/server/internal/service/builtin_skills/multica-platform/references/skill-import.md b/server/internal/service/builtin_skills/multica-platform/references/skill-import.mdindex 58fa69d0ee..0b712930a4 100644--- a/server/internal/service/builtin_skills/multica-platform/references/skill-import.md+++ b/server/internal/service/builtin_skills/multica-platform/references/skill-import.md@@ -83,7 +83,7 @@ skill folder works too. The server: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 (256) caps as URL imports, and rejects path+ per-bundle (8 MiB), and file-count (512) caps as URL imports, and rejects pathtraversal (zip-slip);- returns the same structured result envelope and honors the same`--on-conflict` strategies as URL imports.