Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Preserve structured tool error codes through wrapping https://github.com/siyuan-note/siyuan/issues/20626

Danielaae2f95c8da8
diff --git a/kernel/api/contract_mcp_oauth_test.go b/kernel/api/contract_mcp_oauth_test.go
index 447b2cba0b..02cb901be7 100644
--- a/kernel/api/contract_mcp_oauth_test.go
+++ b/kernel/api/contract_mcp_oauth_test.go
@@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"net/url"
@@ -17,6 +18,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/model/mcpoauth"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -88,6 +90,19 @@ func oauthHTTPRequest(t *testing.T, r *gin.Engine, method, path, body, contentTy
return response
}
+func TestAPIContractMCPOAuthWrappedGrantType(t *testing.T) {
+ r := gin.New()
+ r.POST("/oauth/mcp/token", contractHandler(apicontract.MCPOAuthToken,
+ func(_ *gin.Context, _ apicontract.MCPOAuthTokenRequest) apicontract.Response[apicontract.BinaryContent] {
+ return mcpOAuthError(fmt.Errorf("token service: %w", mcpoauth.ErrGrantType))
+ }))
+ res := oauthHTTPRequest(t, r, "POST", "/oauth/mcp/token", "grant_type=bogus",
+ "application/x-www-form-urlencoded", "", nil, "")
+ if res.Code != http.StatusBadRequest || res.Body.String() != `{"error":"unsupported_grant_type"}` {
+ t.Fatal(res.Code, res.Body.String())
+ }
+}
+
func TestAPIContractMCPOAuthFlow(t *testing.T) {
r := oauthTestRouter(t)
call := func(method, path, body, contentType, auth string, cookies []*http.Cookie, origin string) *httptest.ResponseRecorder {
@@ -109,6 +124,11 @@ func TestAPIContractMCPOAuthFlow(t *testing.T) {
t.Fatal(registered.Body.String(), err)
}
c := created.Data
+ unsupportedForm := url.Values{"grant_type": {"bogus"}, "resource": {"https://note.example.com/mcp"}, "client_id": {c.ID}, "client_secret": {c.Secret}}
+ unsupported := call("POST", "/oauth/mcp/token", unsupportedForm.Encode(), "application/x-www-form-urlencoded", "", nil, "")
+ if unsupported.Code != http.StatusBadRequest || unsupported.Body.String() != `{"error":"unsupported_grant_type"}` {
+ t.Fatal(unsupported.Code, unsupported.Body.String())
+ }
for _, path := range []string{"/.well-known/oauth-protected-resource/mcp", "/.well-known/oauth-protected-resource", "/.well-known/oauth-authorization-server"} {
res := call("GET", path, "", "", "", nil, "")
if res.Code != 200 || strings.Contains(res.Body.String(), `"code":`) || !strings.Contains(res.Body.String(), "https://note.example.com") {
diff --git a/kernel/api/mcp_oauth.go b/kernel/api/mcp_oauth.go
index cd105d5088..3cd889b721 100644
--- a/kernel/api/mcp_oauth.go
+++ b/kernel/api/mcp_oauth.go
@@ -38,7 +38,7 @@ func mcpOAuthError(err error) apicontract.Response[apicontract.BinaryContent] {
status, code = 400, "invalid_request"
case errors.Is(err, mcpoauth.ErrDisabled):
status, code = 404, "temporarily_unavailable"
- case err != nil && err.Error() == "unsupported_grant_type":
+ case errors.Is(err, mcpoauth.ErrGrantType):
status, code = 400, "unsupported_grant_type"
}
return mcpOAuthJSON(status, apicontract.MCPOAuthError{Error: code})
diff --git a/kernel/bazaar/install.go b/kernel/bazaar/install.go
index 01a67f8f38..f567ae936a 100644
--- a/kernel/bazaar/install.go
+++ b/kernel/bazaar/install.go
@@ -320,7 +320,7 @@ func replacePackageDirectoryWithOptions(sourcePath, installPath string, update b
if targetExists {
if rollbackErr := os.Rename(backupPath, installPath); rollbackErr != nil {
preserveOperationPath = true
- return result, fmt.Errorf("result_unknown: install marketplace package failed: %w; rollback failed: %s", err, rollbackErr)
+ return result, util.NewTextFileError(util.TextFileResultUnknown, fmt.Errorf("install marketplace package failed: %w; rollback failed: %s", err, rollbackErr))
}
}
return
@@ -328,7 +328,7 @@ func replacePackageDirectoryWithOptions(sourcePath, installPath string, update b
result.InstalledRevision, err = installedPackageRevision(installPath)
if err != nil || result.InstalledRevision != stagingRevision {
preserveOperationPath = true
- return result, errors.New("result_unknown: installed package changed after replacement; recovery copy preserved")
+ return result, util.NewTextFileError(util.TextFileResultUnknown, errors.New("installed package changed after replacement; recovery copy preserved"))
}
return
}
diff --git a/kernel/bazaar/install_revision.go b/kernel/bazaar/install_revision.go
index 43f10a4f8c..c0dded220e 100644
--- a/kernel/bazaar/install_revision.go
+++ b/kernel/bazaar/install_revision.go
@@ -23,7 +23,7 @@ import (
const MissingInstalledRevision = "missing"
var (
- ErrInstalledRevisionConflict = errors.New("revision_conflict: installed package changed")
+ ErrInstalledRevisionConflict = util.NewTextFileError(util.TextFileRevisionConflict, errors.New("installed package changed"))
ErrPackageHashConflict = errors.New("package_hash_conflict: package archive changed")
)
diff --git a/kernel/bazaar/plugin_project.go b/kernel/bazaar/plugin_project.go
index a12ebf62e3..f164bf4b29 100644
--- a/kernel/bazaar/plugin_project.go
+++ b/kernel/bazaar/plugin_project.go
@@ -29,7 +29,7 @@ const pluginProjectPackagerVersion = "siyuan-plugin-zip-v1"
// 也不将打包结果当作 JavaScript 语法或运行时验证。
func buildPluginProjectArchive(grant *util.PluginDevelopmentGrant, snapshot map[string][]byte) ([]byte, *util.PluginProjectArtifact, error) {
if len(grant.AllowFiles) == 0 || len(grant.AllowFiles) > util.PluginProjectMaxFiles {
- return nil, nil, errors.New("invalid_path: invalid approved inventory")
+ return nil, nil, util.NewTextFileError(util.TextFileInvalidPath, errors.New("invalid approved inventory"))
}
approved := append([]string(nil), grant.AllowFiles...)
sort.Strings(approved)
@@ -44,13 +44,13 @@ func buildPluginProjectArchive(grant *util.PluginDevelopmentGrant, snapshot map[
}
key := strings.ToLower(name)
if seen[key] {
- return nil, nil, errors.New("invalid_path: duplicate or case-colliding archive member")
+ return nil, nil, util.NewTextFileError(util.TextFileInvalidPath, errors.New("duplicate or case-colliding archive member"))
}
seen[key] = true
for prefix := name; prefix != "."; prefix = path.Dir(prefix) {
key := strings.ToLower(prefix)
if old, ok := prefixes[key]; ok && old != prefix {
- return nil, nil, errors.New("invalid_path: case-colliding archive path prefix")
+ return nil, nil, util.NewTextFileError(util.TextFileInvalidPath, errors.New("case-colliding archive path prefix"))
}
prefixes[key] = prefix
}
@@ -60,11 +60,11 @@ func buildPluginProjectArchive(grant *util.PluginDevelopmentGrant, snapshot map[
}
names = append(names, name)
if int64(len(data)) > util.PluginProjectMaxFileBytes {
- return nil, nil, errors.New("too_large: archive member exceeds 16 MiB")
+ return nil, nil, util.NewTextFileError(util.TextFileTooLarge, errors.New("archive member exceeds 16 MiB"))
}
total += int64(len(data))
if total > util.PluginProjectMaxBytes {
- return nil, nil, errors.New("too_large: project exceeds 64 MiB")
+ return nil, nil, util.NewTextFileError(util.TextFileTooLarge, errors.New("project exceeds 64 MiB"))
}
// 仅提供有限补充扫描;安全边界主要来自已确认并冻结的显式清单。
if bytes.Contains(data, []byte("-----BEGIN PRIVATE KEY-----")) || bytes.Contains(data, []byte("-----BEGIN RSA PRIVATE KEY-----")) || bytes.Contains(data, []byte("-----BEGIN OPENSSH PRIVATE KEY-----")) || bytes.Contains(data, []byte("-----BEGIN EC PRIVATE KEY-----")) {
@@ -78,7 +78,7 @@ func buildPluginProjectArchive(grant *util.PluginDevelopmentGrant, snapshot map[
for name := range seen {
for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) {
if seen[parent] {
- return nil, nil, errors.New("invalid_path: file/directory archive member collision")
+ return nil, nil, util.NewTextFileError(util.TextFileInvalidPath, errors.New("file/directory archive member collision"))
}
}
}
@@ -141,7 +141,7 @@ func buildPluginProjectArchive(grant *util.PluginDevelopmentGrant, snapshot map[
return nil, nil, err
}
if int64(output.Len()) > MaxLocalPackageArchiveSize {
- return nil, nil, errors.New("too_large: archive exceeds local installation limit")
+ return nil, nil, util.NewTextFileError(util.TextFileTooLarge, errors.New("archive exceeds local installation limit"))
}
sourceRevision := util.PluginProjectTreeRevision(inventory)
artifact := &util.PluginProjectArtifact{PackageHash: util.PluginProjectDigest(output.Bytes()), SourceRevision: sourceRevision, PackageName: pkg.Name, Version: pkg.Version, Frontend: grant.Frontend, FileListDigest: util.PluginProjectDigest([]byte(strings.Join(names, "\x00"))), PackagerVersion: pluginProjectPackagerVersion, Checks: map[string]string{
@@ -155,14 +155,14 @@ func buildPluginProjectArchive(grant *util.PluginDevelopmentGrant, snapshot map[
func PackagePluginProject(ctx context.Context, taskID, expectedRevision string) (ret *util.PluginProjectArtifact, err error) {
err = util.WithPluginProjectSource(ctx, true, func(grant *util.PluginDevelopmentGrant, root *os.Root) error {
if grant.TaskID != taskID {
- return errors.New("invalid_path: task mismatch")
+ return util.NewTextFileError(util.TextFileInvalidPath, errors.New("task mismatch"))
}
status, err := util.PluginProjectArtifactStatus(grant, root)
if err != nil {
return err
}
if status.Pending || status.ExternalChanges {
- return errors.New("revision_conflict: project has interrupted or external changes")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("project has interrupted or external changes"))
}
snapshot, err := util.SnapshotPluginProject(root, nil)
if err != nil {
@@ -173,7 +173,7 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
return err
}
if expectedRevision == "" || artifact.SourceRevision != expectedRevision {
- return errors.New("revision_conflict: source differs from the expected revision")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("source differs from the expected revision"))
}
// 归档始终消费上面的不可变字节快照,发布前再核对当前源码。
again, err := util.SnapshotPluginProject(root, nil)
@@ -185,7 +185,7 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
inventory[name] = util.PluginProjectDigest(data)
}
if util.PluginProjectTreeRevision(inventory) != expectedRevision {
- return errors.New("revision_conflict: source changed while packaging")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("source changed while packaging"))
}
if err = util.RecheckPluginProjectGrant(ctx, grant); err != nil {
return err
@@ -199,7 +199,7 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
name := artifact.PackageHash + ".zip"
if info, statErr := artifacts.Lstat(name); statErr == nil {
if !util.PluginProjectRegularFile(info) {
- return errors.New("invalid_path: existing artifact is not a regular file")
+ return util.NewTextFileError(util.TextFileInvalidPath, errors.New("existing artifact is not a regular file"))
}
file, readErr := util.OpenFileNoFollow(artifacts, name)
if readErr != nil {
@@ -212,7 +212,7 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
existing, readErr := io.ReadAll(io.LimitReader(file, MaxLocalPackageArchiveSize+1))
file.Close()
if readErr != nil || int64(len(existing)) > MaxLocalPackageArchiveSize || util.PluginProjectDigest(existing) != artifact.PackageHash {
- return errors.New("revision_conflict: published archive changed")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("published archive changed"))
}
} else {
if !errors.Is(statErr, os.ErrNotExist) {
@@ -231,7 +231,7 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
stored += info.Size()
}
if len(entries) >= 8 || stored+int64(len(archive)) > 256*1024*1024 {
- return errors.New("too_large: retained artifact limit reached; existing recovery artifacts were preserved")
+ return util.NewTextFileError(util.TextFileTooLarge, errors.New("retained artifact limit reached; existing recovery artifacts were preserved"))
}
tmp := ".package-" + artifact.PackageHash + ".tmp"
file, writeErr := artifacts.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
@@ -259,10 +259,10 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
artifact.PackagePath = filepath.ToSlash(rel)
ret = artifact
if err = publishPluginProjectDelivery(grant, artifact, archive); err != nil {
- return fmt.Errorf("result_unknown: authoritative archive retained; delivery publication failed: %w", err)
+ return util.NewTextFileError(util.TextFileResultUnknown, fmt.Errorf("authoritative archive retained; delivery publication failed: %w", err))
}
if err = util.RecordPluginProjectArtifact(grant, artifact); err != nil {
- return fmt.Errorf("result_unknown: archive retained; ready metadata was not saved: %w", err)
+ return util.NewTextFileError(util.TextFileResultUnknown, fmt.Errorf("archive retained; ready metadata was not saved: %w", err))
}
ret = artifact
return nil
@@ -275,7 +275,7 @@ func PackagePluginProject(ctx context.Context, taskID, expectedRevision string)
func ResolvePluginProjectArtifact(ctx context.Context, taskID, archivePath, expectedHash string) (ret string, err error) {
err = util.WithPluginProjectSource(ctx, false, func(grant *util.PluginDevelopmentGrant, root *os.Root) error {
if grant.TaskID != taskID {
- return errors.New("invalid_path: task mismatch")
+ return util.NewTextFileError(util.TextFileInvalidPath, errors.New("task mismatch"))
}
if err := util.RecheckPluginProjectGrant(ctx, grant); err != nil {
return err
@@ -285,7 +285,7 @@ func ResolvePluginProjectArtifact(ctx context.Context, taskID, archivePath, expe
return err
}
if status.Artifact == nil || (status.Artifact.PackagePath != archivePath && status.Artifact.DeliveryPath != archivePath) || status.Artifact.PackageHash != expectedHash {
- return errors.New("revision_conflict: archive is not the current approved project artifact")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("archive is not the current approved project artifact"))
}
ret = filepath.Join(util.WorkspaceDir, filepath.FromSlash(status.Artifact.PackagePath))
return nil
diff --git a/kernel/bazaar/plugin_project_delivery.go b/kernel/bazaar/plugin_project_delivery.go
index 171d54ae2d..44be0ec02d 100644
--- a/kernel/bazaar/plugin_project_delivery.go
+++ b/kernel/bazaar/plugin_project_delivery.go
@@ -25,7 +25,7 @@ func publishPluginProjectDelivery(grant *util.PluginDevelopmentGrant, artifact *
name := "plugin-project-" + grant.TaskID + "-" + artifact.PackageHash + ".zip"
if info, statErr := root.Lstat(name); statErr == nil {
if !util.PluginProjectRegularFile(info) {
- return errors.New("invalid_path: delivery copy is linked or special")
+ return util.NewTextFileError(util.TextFileInvalidPath, errors.New("delivery copy is linked or special"))
}
file, openErr := util.OpenFileNoFollow(root, name)
if openErr != nil {
@@ -34,7 +34,7 @@ func publishPluginProjectDelivery(grant *util.PluginDevelopmentGrant, artifact *
actual, statErr := file.Stat()
if statErr != nil || !os.SameFile(info, actual) {
file.Close()
- return errors.New("revision_conflict: delivery copy identity changed")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("delivery copy identity changed"))
}
if openErr = util.CheckSingleLinkRegularFile(file); openErr != nil {
file.Close()
@@ -43,7 +43,7 @@ func publishPluginProjectDelivery(grant *util.PluginDevelopmentGrant, artifact *
data, readErr := io.ReadAll(io.LimitReader(file, MaxLocalPackageArchiveSize+1))
file.Close()
if readErr != nil || util.PluginProjectDigest(data) != artifact.PackageHash {
- return errors.New("revision_conflict: existing delivery copy changed")
+ return util.NewTextFileError(util.TextFileRevisionConflict, errors.New("existing delivery copy changed"))
}
} else {
if !errors.Is(statErr, os.ErrNotExist) {
diff --git a/kernel/mcp/tools/bazaar_project.go b/kernel/mcp/tools/bazaar_project.go
index d6eb576352..60f767f5a9 100644
--- a/kernel/mcp/tools/bazaar_project.go
+++ b/kernel/mcp/tools/bazaar_project.go
@@ -7,7 +7,6 @@ import (
"github.com/siyuan-note/siyuan/kernel/bazaar"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
- "strings"
)
func isPluginProjectAction(action string) bool {
@@ -34,7 +33,7 @@ func bazaarProjectError(err error, partial any) (CallToolResult, error) {
if err == nil {
return bazaarProjectJSON(partial)
}
- unknown := strings.Contains(err.Error(), "result_unknown")
+ unknown := util.IsTextFileError(err, util.TextFileResultUnknown)
if partial == nil && !unknown {
return blockToolError(err.Error())
}
diff --git a/kernel/mcp/tools/bazaar_project_preview.go b/kernel/mcp/tools/bazaar_project_preview.go
index 583bde188c..53aa67eca0 100644
--- a/kernel/mcp/tools/bazaar_project_preview.go
+++ b/kernel/mcp/tools/bazaar_project_preview.go
@@ -55,7 +55,7 @@ func PluginDevelopmentInstallPreview(ctx context.Context, args map[string]any) (
return nil, err
}
if expectedInstalled != "" && preview.InstalledRevision != expectedInstalled {
- return nil, errors.New("revision_conflict: installed package changed before confirmation")
+ return nil, util.NewTextFileError(util.TextFileRevisionConflict, errors.New("installed package changed before confirmation"))
}
payload["package"], payload["managedArtifact"] = preview, managed
payload["archiveHashBound"], payload["targetRevisionBound"] = expectedHash != "", expectedInstalled != ""
diff --git a/kernel/mcp/tools/bazaar_project_test.go b/kernel/mcp/tools/bazaar_project_test.go
index 4e13b1b736..34e760d922 100644
--- a/kernel/mcp/tools/bazaar_project_test.go
+++ b/kernel/mcp/tools/bazaar_project_test.go
@@ -116,7 +116,7 @@ func TestBazaarProjectManagedArchiveCannotUseLegacyInstall(t *testing.T) {
}
func TestBazaarProjectUnknownErrorsRetainExecutionState(t *testing.T) {
- result, err := bazaarProjectError(errors.New("result_unknown: staged replacement may be partial"), map[string]any{"installedRevision": "observed"})
+ result, err := bazaarProjectError(util.NewTextFileError(util.TextFileResultUnknown, errors.New("staged replacement may be partial")), map[string]any{"installedRevision": "observed"})
if err != nil || !result.IsError || !result.ExecutionUnknown || !strings.Contains(probeText(result), "observed") {
t.Fatal(result, err)
}
diff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.go
index 5ad1561a0b..a2a4e0dcc6 100644
--- a/kernel/mcp/tools/file.go
+++ b/kernel/mcp/tools/file.go
@@ -368,7 +368,7 @@ func fileWrite(args map[string]any) (CallToolResult, error) {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil
}
if util.IsPluginDevelopmentRawWriteForbidden(abs) {
- return fileSafeError(fileInvalid("invalid_path", "raw write to a managed plugin or delivery path is forbidden"))
+ return fileSafeError(fileInvalid(util.TextFileInvalidPath, "raw write to a managed plugin or delivery path is forbidden"))
}
if err := os.MkdirAll(filepath.Dir(abs), 0755); err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "mkdir failed: " + err.Error()}}, IsError: true}, nil
@@ -398,18 +398,11 @@ type fileReadPage struct {
func fileSafeError(err error) (CallToolResult, error) {
var failure *util.TextFileError
if !errors.As(err, &failure) {
- failure = &util.TextFileError{Code: "write_failed", Message: err.Error()}
- for _, code := range []string{"revision_conflict", "invalid_path", "unsupported_encoding", "too_large", "backup_failed", "result_unknown"} {
- if strings.HasPrefix(err.Error(), code+":") {
- failure.Code = code
- failure.Message = strings.TrimSpace(strings.TrimPrefix(err.Error(), code+":"))
- break
- }
- }
+ failure = &util.TextFileError{Code: util.TextFileWriteFailed, Message: err.Error()}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
- failure.Code = "cancelled"
+ failure.Code = util.TextFileCancelled
} else if errors.Is(err, os.ErrNotExist) {
- failure.Code = "invalid_path"
+ failure.Code = util.TextFileInvalidPath
}
}
// 系统错误可能包含输入路径;复制后限制错误文本,避免共享输出截断器破坏错误 JSON 或修改调用方对象。
@@ -423,7 +416,7 @@ func fileSafeError(err error) (CallToolResult, error) {
failure.Message = failure.Message[:end] + "..."
}
encoded, _ := json.Marshal(failure)
- return CallToolResult{Content: []ContentItem{{Type: "text", Text: string(encoded)}}, StructuredContent: failure, StructuredContentSet: true, IsError: true, ExecutionUnknown: failure.Code == "result_unknown"}, nil
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: string(encoded)}}, StructuredContent: failure, StructuredContentSet: true, IsError: true, ExecutionUnknown: failure.Code == util.TextFileResultUnknown}, nil
}
func fileInvalid(code, message string) error {
@@ -436,7 +429,7 @@ func fileJSONResult(value any) (CallToolResult, error) {
return fileSafeError(err)
}
if len(encoded) >= fileJSONBudget {
- return fileSafeError(fileInvalid("too_large", "serialized result exceeds safe response budget"))
+ return fileSafeError(fileInvalid(util.TextFileTooLarge, "serialized result exceeds safe response budget"))
}
return CallToolResult{Content: []ContentItem{{Type: "text", Text: string(encoded)}}, StructuredContent: value, StructuredContentSet: true}, nil
}
@@ -475,7 +468,7 @@ func fileReadMetadata(args map[string]any) (CallToolResult, error) {
return fileSafeError(err)
}
if _, err := resolvePath(p); err != nil {
- return fileSafeError(fileInvalid("invalid_path", err.Error()))
+ return fileSafeError(fileInvalid(util.TextFileInvalidPath, err.Error()))
}
root, err := os.OpenRoot(util.WorkspaceDir)
if err != nil {
@@ -495,7 +488,7 @@ func fileMetadataContent(args map[string]any, content string) (CallToolResult, e
}
revision := util.TextFileRevision([]byte(content))
if expected, exists := args["expectedRevision"]; exists && expected != revision {
- return fileSafeError(fileInvalid("revision_conflict", "file changed; restart the read with its current revision"))
+ return fileSafeError(fileInvalid(util.TextFileRevisionConflict, "file changed; restart the read with its current revision"))
}
offset, err := fileIntegerArg(args, "byteOffset", 0)
if err != nil {
@@ -558,7 +551,7 @@ func fileMetadataContent(args map[string]any, content string) (CallToolResult, e
}
setEnd(best)
if best == offset && offset < len(content) {
- return fileSafeError(fileInvalid("too_large", "metadata leaves no room for content"))
+ return fileSafeError(fileInvalid(util.TextFileTooLarge, "metadata leaves no room for content"))
}
return fileJSONResult(page)
}
@@ -628,7 +621,7 @@ func fileMutationResult(result util.TextFileMutationResult) (CallToolResult, err
return fileJSONResult(result)
}
if len(result.Diff) == 0 {
- return fileSafeError(fileInvalid("too_large", "edit result exceeds response budget"))
+ return fileSafeError(fileInvalid(util.TextFileTooLarge, "edit result exceeds response budget"))
}
end := len(result.Diff) / 2
for end > 0 && !utf8.RuneStart(result.Diff[end]) {
@@ -646,10 +639,10 @@ func fileMutate(ctx context.Context, args map[string]any) (CallToolResult, error
}
abs, err := resolvePath(p)
if err != nil {
- return fileSafeError(fileInvalid("invalid_path", err.Error()))
+ return fileSafeError(fileInvalid(util.TextFileInvalidPath, err.Error()))
}
if util.IsPluginDevelopmentRawWriteForbidden(abs) {
- return fileSafeError(fileInvalid("invalid_path", "raw write to a managed plugin or delivery path is forbidden"))
+ return fileSafeError(fileInvalid(util.TextFileInvalidPath, "raw write to a managed plugin or delivery path is forbidden"))
}
request, err := fileMutationRequest(args)
if err != nil {
@@ -666,7 +659,7 @@ func fileMutate(ctx context.Context, args map[string]any) (CallToolResult, error
return err
}
if util.IsPluginDevelopmentRawWriteForbidden(abs) {
- return fileInvalid("invalid_path", "raw write to a managed plugin or delivery path is forbidden")
+ return fileInvalid(util.TextFileInvalidPath, "raw write to a managed plugin or delivery path is forbidden")
}
return nil
}
@@ -680,7 +673,7 @@ func fileMutate(ctx context.Context, args map[string]any) (CallToolResult, error
func fileManaged(ctx context.Context, args map[string]any) (result CallToolResult, resultErr error) {
action, _ := args["action"].(string)
if action != "read" && action != "write" && action != "edit" && action != "delete" && action != "rename" {
- return fileSafeError(fileInvalid("invalid_path", "managed sources support only read, conditional write/edit and file-only delete/rename"))
+ return fileSafeError(fileInvalid(util.TextFileInvalidPath, "managed sources support only read, conditional write/edit and file-only delete/rename"))
}
write := action != "read"
err := util.WithPluginProjectSource(ctx, write, func(grant *util.PluginDevelopmentGrant, root *os.Root) error {
@@ -715,7 +708,7 @@ func fileManaged(ctx context.Context, args map[string]any) (result CallToolResul
return err
}
if current.TaskID != grant.TaskID || current.SessionID != grant.SessionID || current.PlanHash != grant.PlanHash || current.PlanVersion != grant.PlanVersion || current.SkillDigest != grant.SkillDigest || current.SourceRoot != grant.SourceRoot {
- return fileInvalid("revision_conflict", "approved plugin plan changed during operation")
+ return fileInvalid(util.TextFileRevisionConflict, "approved plugin plan changed during operation")
}
_, err = fileManagedRelative(current, p)
if err == nil && action == "rename" {
@@ -774,11 +767,11 @@ func fileManagedRelative(grant *util.PluginDevelopmentGrant, p string) (string,
}
abs := filepath.Join(util.WorkspaceDir, filepath.FromSlash(p))
if grant.SourceRoot == "" || filepath.Clean(grant.SourceRoot) != filepath.Join(util.PluginProjectRoot(grant.TaskID), "source") {
- return "", fileInvalid("invalid_path", "invalid host-owned source root")
+ return "", fileInvalid(util.TextFileInvalidPath, "invalid host-owned source root")
}
rel, err := filepath.Rel(grant.SourceRoot, abs)
if err != nil {
- return "", fileInvalid("invalid_path", "path is outside approved source")
+ return "", fileInvalid(util.TextFileInvalidPath, "path is outside approved source")
}
rel = filepath.ToSlash(rel)
if err = util.ValidateTextFilePath(rel); err != nil {
@@ -787,7 +780,7 @@ func fileManagedRelative(grant *util.PluginDevelopmentGrant, p string) (string,
if slices.Contains(grant.AllowFiles, rel) {
return rel, nil
}
- return "", fileInvalid("invalid_path", "file is outside the approved project allowlist")
+ return "", fileInvalid(util.TextFileInvalidPath, "file is outside the approved project allowlist")
}
func fileDelete(args map[string]any) (CallToolResult, error) {
diff --git a/kernel/mcp/tools/file_error_test.go b/kernel/mcp/tools/file_error_test.go
new file mode 100644
index 0000000000..cff56eaaa8
--- /dev/null
+++ b/kernel/mcp/tools/file_error_test.go
@@ -0,0 +1,74 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestFileSafeErrorPreservesStructuredCodes(t *testing.T) {
+ for _, code := range []string{util.TextFileRevisionConflict, util.TextFileInvalidPath,
+ util.TextFileUnsupportedEncoding, util.TextFileTooLarge, util.TextFileBackupFailed, util.TextFileResultUnknown} {
+ t.Run(code, func(t *testing.T) {
+ failure := util.NewTextFileError(code, errors.New("operation failed"))
+ failure.Written = true
+ result, err := fileSafeError(fmt.Errorf("outer: %w", failure))
+ var data util.TextFileError
+ if err != nil || !result.IsError || json.Unmarshal([]byte(result.Content[0].Text), &data) != nil ||
+ data.Code != code || data.Message != failure.Message || !data.Written ||
+ result.ExecutionUnknown != (code == util.TextFileResultUnknown) {
+ t.Fatalf("结构化文件错误丢失:%+v,%v", result, err)
+ }
+ })
+ }
+}
+
+func TestFileSafeErrorClassifiesCausesWithoutParsingMessages(t *testing.T) {
+ for _, tc := range []struct {
+ err error
+ code string
+ }{
+ {errors.New("result_unknown-draft.md: permission denied"), "write_failed"},
+ {errors.New("result_unknown: ordinary error text"), "write_failed"},
+ {fmt.Errorf("cancelled read: %w", context.Canceled), "cancelled"},
+ {fmt.Errorf("timed out: %w", context.DeadlineExceeded), "cancelled"},
+ {fmt.Errorf("missing result_unknown-draft.md: %w", os.ErrNotExist), "invalid_path"},
+ } {
+ result, err := fileSafeError(tc.err)
+ var data util.TextFileError
+ if err != nil || json.Unmarshal([]byte(result.Content[0].Text), &data) != nil || data.Code != tc.code || result.ExecutionUnknown {
+ t.Fatalf("普通文件错误分类错误:%+v,%v", result, err)
+ }
+ }
+}
+
+func TestBazaarProjectErrorUsesStructuredExecutionState(t *testing.T) {
+ for _, tc := range []struct {
+ err error
+ unknown bool
+ }{
+ {errors.New("result_unknown-draft.md: permission denied"), false},
+ {util.NewTextFileError(util.TextFileInvalidPath, errors.New("result_unknown-draft.md")), false},
+ {fmt.Errorf("outer: %w", util.NewTextFileError(util.TextFileResultUnknown, errors.New("partial replacement"))), true},
+ } {
+ for _, partial := range []any{nil, map[string]any{"revision": "observed"}} {
+ result, err := bazaarProjectError(tc.err, partial)
+ if err != nil || !result.IsError || result.ExecutionUnknown != tc.unknown {
+ t.Fatalf("项目执行状态错误:%+v,%v", result, err)
+ }
+ if partial != nil || tc.unknown {
+ var payload struct {
+ ResultUnknown bool `json:"resultUnknown"`
+ }
+ if err = json.Unmarshal([]byte(result.Content[0].Text), &payload); err != nil || payload.ResultUnknown != tc.unknown {
+ t.Fatalf("项目响应状态错误:%+v,%v", result, err)
+ }
+ }
+ }
+ }
+}
diff --git a/kernel/model/mcpoauth/service.go b/kernel/model/mcpoauth/service.go
index 74d2b6872b..275bf76af2 100644
--- a/kernel/model/mcpoauth/service.go
+++ b/kernel/model/mcpoauth/service.go
@@ -27,6 +27,7 @@ const maxPending = 256
var ErrInvalid = errors.New("invalid_request")
var ErrGrant = errors.New("invalid_grant")
+var ErrGrantType = errors.New("unsupported_grant_type")
var ErrClient = errors.New("invalid_client")
var ErrDisabled = errors.New("MCP OAuth is disabled")
@@ -464,7 +465,7 @@ func (s *Service) Token(req apicontract.MCPOAuthTokenRequest) (ret apicontract.M
}
g.Spent = append(g.Spent, g.RefreshHash)
default:
- return ret, errors.New("unsupported_grant_type")
+ return ret, ErrGrantType
}
ret = apicontract.MCPOAuthTokenResponse{AccessToken: AccessPrefix + random(), TokenType: "Bearer", ExpiresIn: 3600, Scope: g.Scope}
if remaining := g.Expires - now; remaining < int64(ret.ExpiresIn) {
diff --git a/kernel/util/plugin_project.go b/kernel/util/plugin_project.go
index 4401f6fb82..9a07b02741 100644
--- a/kernel/util/plugin_project.go
+++ b/kernel/util/plugin_project.go
@@ -102,15 +102,15 @@ func validPluginProjectRevision(s string) bool {
// 即使出现在允许清单中,也拒绝平台别名及私密、构建依赖和运行时材料。
func ValidatePluginProjectFile(name string) error {
if err := validateManagedSkillPath(name); err != nil {
- return fmt.Errorf("invalid_path: %w", err)
+ return NewTextFileError(TextFileInvalidPath, err)
}
for part := range strings.SplitSeq(strings.ToLower(name), "/") {
switch part {
case "configs", "settings", "cache", "logs", "secrets", "credentials", "data.json", "settings.json", "token.json", "token.txt", "tokens.txt", "auth.json", "auth.txt", "credential.json", "credentials.txt", "secret.json", "secrets.json", "secrets.txt":
- return fmt.Errorf("invalid_path: credential or runtime material is not permitted: %s", name)
+ return NewTextFileError(TextFileInvalidPath, fmt.Errorf("credential or runtime material is not permitted: %s", name))
}
if strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".log") || strings.HasSuffix(part, ".bak") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".p12") || strings.HasSuffix(part, ".pfx") || strings.HasSuffix(part, ".zip") || part == "node_modules" || part == "backup" || part == "backups" || part == "checkpoints" || part == "artifacts" || part == "storage" || part == "conf" || part == "config" || part == "conf.json" || part == "config.json" || part == "credentials.json" || part == "token" || part == "tokens.json" || strings.HasPrefix(part, "id_rsa") || strings.HasPrefix(part, "id_ed25519") {
- return fmt.Errorf("invalid_path: private, runtime or generated archive material is not permitted: %s", name)
+ return NewTextFileError(TextFileInvalidPath, fmt.Errorf("private, runtime or generated archive material is not permitted: %s", name))
}
}
return nil
@@ -118,7 +118,7 @@ func ValidatePluginProjectFile(name string) error {
func pluginProjectAllowFiles(grant *PluginDevelopmentGrant) ([]string, error) {
if len(grant.AllowFiles) == 0 || len(grant.AllowFiles) > PluginProjectMaxFiles {
- return nil, errors.New("invalid_path: approved file inventory is empty or too large")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("approved file inventory is empty or too large"))
}
files := append([]string(nil), grant.AllowFiles...)
sort.Strings(files)
@@ -129,14 +129,14 @@ func pluginProjectAllowFiles(grant *PluginDevelopmentGrant) ([]string, error) {
}
key := strings.ToLower(name)
if seen[key] {
- return nil, errors.New("invalid_path: duplicate or case-colliding approved file")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("duplicate or case-colliding approved file"))
}
seen[key] = true
}
for key := range seen {
for parent := path.Dir(key); parent != "."; parent = path.Dir(parent) {
if seen[parent] {
- return nil, errors.New("invalid_path: file/directory collision")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("file/directory collision"))
}
}
}
@@ -165,7 +165,7 @@ func PluginProjectRegularFile(info os.FileInfo) bool {
func OpenPluginProjectDirectory(abs string, create bool) (*os.Root, error) {
rel, err := filepath.Rel(WorkspaceDir, abs)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
- return nil, errors.New("invalid_path: project path escapes workspace")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("project path escapes workspace"))
}
root, err := os.OpenRoot(WorkspaceDir)
if err != nil {
@@ -192,7 +192,7 @@ func OpenPluginProjectDirectory(abs string, create bool) (*os.Root, error) {
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
root.Close()
- return nil, errors.New("invalid_path: linked project directory")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("linked project directory"))
}
next, openErr := root.OpenRoot(part)
if openErr != nil {
@@ -203,7 +203,7 @@ func OpenPluginProjectDirectory(abs string, create bool) (*os.Root, error) {
root.Close()
if statErr != nil || !os.SameFile(info, actual) {
next.Close()
- return nil, errors.New("invalid_path: project directory changed")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("project directory changed"))
}
root = next
}
@@ -219,10 +219,10 @@ func readPluginProjectFile(root *os.Root, name string) ([]byte, error) {
return nil, err
}
if !PluginProjectRegularFile(info) {
- return nil, errors.New("invalid_path: linked or special file")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("linked or special file"))
}
if info.Size() > PluginProjectMaxFileBytes {
- return nil, errors.New("too_large: project file exceeds 16 MiB")
+ return nil, NewTextFileError(TextFileTooLarge, errors.New("project file exceeds 16 MiB"))
}
f, err := OpenFileNoFollow(root, name)
if err != nil {
@@ -231,7 +231,7 @@ func readPluginProjectFile(root *os.Root, name string) ([]byte, error) {
defer f.Close()
actual, err := f.Stat()
if err != nil || !PluginProjectRegularFile(actual) || !os.SameFile(info, actual) {
- return nil, errors.New("revision_conflict: file identity changed")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("file identity changed"))
}
if err = CheckSingleLinkRegularFile(f); err != nil {
return nil, err
@@ -241,7 +241,7 @@ func readPluginProjectFile(root *os.Root, name string) ([]byte, error) {
return nil, err
}
if int64(len(data)) > PluginProjectMaxFileBytes {
- return nil, errors.New("too_large: project file exceeds 16 MiB")
+ return nil, NewTextFileError(TextFileTooLarge, errors.New("project file exceeds 16 MiB"))
}
return data, nil
}
@@ -266,7 +266,7 @@ func snapshotPluginProject(root *os.Root, authorize func(string) error, temporar
data, err := readPluginProjectFile(root, name)
if err != nil || PluginProjectDigest(data) != revision {
- return errors.New("result_unknown: recorded temporary file has incomplete or unknown bytes; preserved for inspection")
+ return NewTextFileError(TextFileResultUnknown, errors.New("recorded temporary file has incomplete or unknown bytes; preserved for inspection"))
}
return nil
}
@@ -280,24 +280,24 @@ func snapshotPluginProject(root *os.Root, authorize func(string) error, temporar
}
key := strings.ToLower(name)
if seen[key] {
- return errors.New("invalid_path: case-colliding project paths")
+ return NewTextFileError(TextFileInvalidPath, errors.New("case-colliding project paths"))
}
seen[key] = true
if len(seen) > PluginProjectMaxFiles*2 {
- return errors.New("too_large: project contains too many paths")
+ return NewTextFileError(TextFileTooLarge, errors.New("project contains too many paths"))
}
info, err := root.Lstat(name)
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
- return errors.New("invalid_path: linked project member")
+ return NewTextFileError(TextFileInvalidPath, errors.New("linked project member"))
}
if info.IsDir() {
return nil
}
if len(files) >= PluginProjectMaxFiles {
- return errors.New("too_large: project contains too many files")
+ return NewTextFileError(TextFileTooLarge, errors.New("project contains too many files"))
}
data, err := readPluginProjectFile(root, name)
if err != nil {
@@ -305,7 +305,7 @@ func snapshotPluginProject(root *os.Root, authorize func(string) error, temporar
}
total += int64(len(data))
if total > PluginProjectMaxBytes {
- return errors.New("too_large: project exceeds 64 MiB")
+ return NewTextFileError(TextFileTooLarge, errors.New("project exceeds 64 MiB"))
}
files[name] = data
return nil
@@ -358,7 +358,7 @@ func InspectPluginProjectSource(abs string, authorize func(string) error, select
return inspectPluginProjectCandidate(root, authorize)
}
if len(selected) != 1 {
- return nil, errors.New("invalid_path: invalid selected source inventory")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("invalid selected source inventory"))
}
files, err := snapshotSelectedPluginSource(root, selected[0], authorize)
if err != nil {
@@ -369,11 +369,11 @@ func InspectPluginProjectSource(abs string, authorize func(string) error, select
func checkPluginProjectGrant(grant *PluginDevelopmentGrant, taskID string) error {
if taskID == "" || grant.TaskID != taskID || !fs.ValidPath(taskID) || strings.ContainsAny(taskID, "/\\:.") {
- return errors.New("invalid_path: invalid project task")
+ return NewTextFileError(TextFileInvalidPath, errors.New("invalid project task"))
}
want := filepath.Join(PluginProjectRoot(taskID), "source")
if grant.SourceRoot != want {
- return errors.New("invalid_path: source root does not match host project")
+ return NewTextFileError(TextFileInvalidPath, errors.New("source root does not match host project"))
}
return nil
}
@@ -406,7 +406,7 @@ func readPluginProjectManifest(grant *PluginDevelopmentGrant) (*pluginProjectMan
return nil, err
}
if manifest.PlanHash != grant.PlanHash {
- return nil, errors.New("revision_conflict: prepare_project with expectedSourceRevision is required for the newly approved plan")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("prepare_project with expectedSourceRevision is required for the newly approved plan"))
}
return manifest, nil
}
@@ -426,7 +426,7 @@ func readPluginProjectManifestForStatus(grant *PluginDevelopmentGrant) (*pluginP
return nil, err
}
if manifest.Version != 1 || manifest.Baseline == nil || manifest.Current == nil {
- return nil, errors.New("revision_conflict: project belongs to another approved plan")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("project belongs to another approved plan"))
}
return &manifest, nil
}
@@ -452,12 +452,12 @@ func savePluginProjectManifest(grant *PluginDevelopmentGrant, manifest *pluginPr
func validateProjectBaseline(grant *PluginDevelopmentGrant, manifest *pluginProjectManifest) error {
root, err := OpenPluginProjectDirectory(pluginProjectBaselinePath(grant, manifest), false)
if err != nil {
- return fmt.Errorf("backup_failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, err)
}
defer root.Close()
files, err := SnapshotPluginProject(root, nil)
if err != nil || PluginProjectTreeRevision(projectInventory(files)) != PluginProjectTreeRevision(manifest.Baseline) {
- return errors.New("backup_failed: baseline checkpoint is missing or changed")
+ return NewTextFileError(TextFileBackupFailed, errors.New("baseline checkpoint is missing or changed"))
}
return nil
}
@@ -486,7 +486,7 @@ func PreparePluginProject(ctx context.Context, taskID string, authorize func(str
if manifest, readErr := readPluginProjectManifestForStatus(grant); readErr == nil {
if manifest.Preparing {
if manifest.PlanHash != grant.PlanHash || manifest.SourcePath != grant.SourcePath || manifest.SourceRevision != grant.SourceRevision {
- return errors.New("revision_conflict: finish interrupted preparation before changing plans")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("finish interrupted preparation before changing plans"))
}
ret, err = resumePluginProjectPreparation(ctx, grant, manifest, allowed, recoveryOnly)
return err
@@ -507,14 +507,14 @@ func PreparePluginProject(ctx context.Context, taskID string, authorize func(str
return errors.New("recovery-only approval cannot initialize a project")
}
if _, err = os.Lstat(PluginProjectRoot(taskID)); err == nil {
- return errors.New("result_unknown: unregistered project source exists; preserved for inspection")
+ return NewTextFileError(TextFileResultUnknown, errors.New("unregistered project source exists; preserved for inspection"))
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
selected := map[string][]byte{}
if grant.SourcePath != "" {
if filepath.IsAbs(grant.SourcePath) || !IsPublishRelativePath(grant.SourcePath) {
- return errors.New("invalid_path: sourcePath must be workspace relative")
+ return NewTextFileError(TextFileInvalidPath, errors.New("sourcePath must be workspace relative"))
}
abs := filepath.Join(WorkspaceDir, filepath.FromSlash(grant.SourcePath))
if authorize != nil {
@@ -536,12 +536,12 @@ func PreparePluginProject(ctx context.Context, taskID string, authorize func(str
return err
}
if PluginProjectTreeRevision(projectInventory(selected)) != grant.SourceRevision {
- return errors.New("revision_conflict: approved selected import source changed; inspect with sourceFiles matching the approved allowFiles")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("approved selected import source changed; inspect with sourceFiles matching the approved allowFiles"))
}
again, inspectErr := InspectPluginProjectSource(abs, authorize, allowed)
actual, statErr := os.Stat(abs)
if inspectErr != nil || statErr != nil || !os.SameFile(identity, actual) || again.SourceRevision != grant.SourceRevision {
- return errors.New("revision_conflict: selected import source changed while freezing")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("selected import source changed while freezing"))
}
}
if err = ensurePluginProjectCheckpoint(grant, "baseline", selected); err != nil {
@@ -549,7 +549,7 @@ func PreparePluginProject(ctx context.Context, taskID string, authorize func(str
}
manifest := &pluginProjectManifest{Version: 1, PlanHash: grant.PlanHash, SourcePath: grant.SourcePath, SourceRevision: grant.SourceRevision, Preparing: true, Baseline: projectInventory(selected), Current: map[string]string{}}
if err = savePluginProjectManifest(grant, manifest); err != nil {
- return fmt.Errorf("backup_failed: preparation journal not saved; source was not created: %w", err)
+ return NewTextFileError(TextFileBackupFailed, fmt.Errorf("preparation journal not saved; source was not created: %w", err))
}
ret, err = resumePluginProjectPreparation(ctx, grant, manifest, allowed, false)
return err
@@ -578,7 +578,7 @@ func WithPluginProjectSource(ctx context.Context, write bool, fn func(*PluginDev
return err
}
if grant.TaskID != lockedTaskID {
- return errors.New("revision_conflict: active task changed while waiting for the project lock")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("active task changed while waiting for the project lock"))
}
if err = checkPluginProjectGrant(grant, grant.TaskID); err != nil {
return err
@@ -589,13 +589,13 @@ func WithPluginProjectSource(ctx context.Context, write bool, fn func(*PluginDev
}
if write {
if manifest.Preparing {
- return errors.New("result_unknown: retry prepare_project to finish interrupted preparation")
+ return NewTextFileError(TextFileResultUnknown, errors.New("retry prepare_project to finish interrupted preparation"))
}
if manifest.PlanHash != grant.PlanHash {
- return errors.New("revision_conflict: prepare_project is required for the newly approved plan")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("prepare_project is required for the newly approved plan"))
}
if manifest.mutationPending() {
- return errors.New("result_unknown: interrupted mutation requires project_status and restore_project")
+ return NewTextFileError(TextFileResultUnknown, errors.New("interrupted mutation requires project_status and restore_project"))
}
if err = validateProjectBaseline(grant, manifest); err != nil {
return err
@@ -647,7 +647,7 @@ func PluginProjectArtifactStatus(grant *PluginDevelopmentGrant, root *os.Root) (
files, err := snapshotPluginProject(root, nil, manifest.TemporaryFiles)
if err != nil {
if manifest.mutationPending() {
- return nil, fmt.Errorf("result_unknown: pending project cannot be safely inspected; manual inspection required; source and journal preserved: %w", err)
+ return nil, NewTextFileError(TextFileResultUnknown, fmt.Errorf("pending project cannot be safely inspected; manual inspection required; source and journal preserved: %w", err))
}
return nil, err
}
@@ -671,7 +671,7 @@ func BeginPluginProjectMutations(grant *PluginDevelopmentGrant, changes map[stri
return err
}
if len(changes) == 0 || manifest.mutationPending() {
- return errors.New("result_unknown: pending or empty project mutation")
+ return NewTextFileError(TextFileResultUnknown, errors.New("pending or empty project mutation"))
}
if err = validateProjectBaseline(grant, manifest); err != nil {
return err
@@ -694,36 +694,36 @@ func BeginPluginProjectMutations(grant *PluginDevelopmentGrant, changes map[stri
return err
}
if PluginProjectTreeRevision(projectInventory(files)) != PluginProjectTreeRevision(manifest.Current) {
- return errors.New("revision_conflict: source contains external edits")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("source contains external edits"))
}
for name, change := range changes {
if !set[name] || !validPluginProjectRevision(change.OldRevision) || !validPluginProjectRevision(change.NewRevision) {
- return errors.New("invalid_path: mutation is outside the approved inventory")
+ return NewTextFileError(TextFileInvalidPath, errors.New("mutation is outside the approved inventory"))
}
old := manifest.Current[name]
if old == "" {
old = PluginProjectMissingRevision
}
if old != change.OldRevision {
- return errors.New("revision_conflict: mutation old revision differs")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("mutation old revision differs"))
}
}
manifest.Pending, manifest.Artifact = changes, nil
manifest.TemporaryFiles = map[string]string{}
if len(temporaryPaths) > 0 {
if len(changes) != 1 || len(temporaryPaths) != 1 {
- return errors.New("invalid_path: temporary file requires one mutation")
+ return NewTextFileError(TextFileInvalidPath, errors.New("temporary file requires one mutation"))
}
for name, change := range changes {
tmp := temporaryPaths[0]
if path.Dir(tmp) != path.Dir(name) || !strings.HasPrefix(path.Base(tmp), ".text-file-") || validateManagedSkillPath(tmp) != nil || change.NewRevision == PluginProjectMissingRevision {
- return errors.New("invalid_path: invalid host temporary file")
+ return NewTextFileError(TextFileInvalidPath, errors.New("invalid host temporary file"))
}
manifest.TemporaryFiles[tmp] = change.NewRevision
}
}
if err = savePluginProjectManifest(grant, manifest); err != nil {
- return fmt.Errorf("backup_failed: mutation journal could not be saved: %w", err)
+ return NewTextFileError(TextFileBackupFailed, fmt.Errorf("mutation journal could not be saved: %w", err))
}
return nil
}
@@ -738,7 +738,7 @@ func FinishPluginProjectMutations(grant *PluginDevelopmentGrant, paths []string)
return err
}
if len(paths) != len(manifest.Pending) {
- return errors.New("result_unknown: incomplete mutation completion")
+ return NewTextFileError(TextFileResultUnknown, errors.New("incomplete mutation completion"))
}
root, err := OpenPluginProjectDirectory(grant.SourceRoot, false)
if err != nil {
@@ -752,14 +752,14 @@ func FinishPluginProjectMutations(grant *PluginDevelopmentGrant, paths []string)
for _, name := range paths {
change, ok := manifest.Pending[name]
if !ok {
- return errors.New("result_unknown: mutation journal mismatch")
+ return NewTextFileError(TextFileResultUnknown, errors.New("mutation journal mismatch"))
}
actual := PluginProjectMissingRevision
if data, ok := files[name]; ok {
actual = PluginProjectDigest(data)
}
if actual != change.NewRevision {
- return errors.New("result_unknown: mutation result differs; journal preserved")
+ return NewTextFileError(TextFileResultUnknown, errors.New("mutation result differs; journal preserved"))
}
if actual == PluginProjectMissingRevision {
delete(manifest.Current, name)
@@ -768,7 +768,7 @@ func FinishPluginProjectMutations(grant *PluginDevelopmentGrant, paths []string)
}
}
if PluginProjectTreeRevision(projectInventory(files)) != PluginProjectTreeRevision(manifest.Current) {
- return errors.New("result_unknown: source changed while completing mutation")
+ return NewTextFileError(TextFileResultUnknown, errors.New("source changed while completing mutation"))
}
manifest.Pending = nil
manifest.TemporaryFiles = nil
@@ -786,7 +786,7 @@ func RecordPluginProjectArtifact(grant *PluginDevelopmentGrant, artifact *Plugin
return err
}
if manifest.mutationPending() || artifact.SourceRevision != PluginProjectTreeRevision(manifest.Current) {
- return errors.New("revision_conflict: artifact source is not the recorded project revision")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("artifact source is not the recorded project revision"))
}
manifest.Artifact = artifact
return savePluginProjectManifest(grant, manifest)
@@ -798,8 +798,8 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
err = WithPluginProjectLockContext(ctx, taskID, func() (operationErr error) {
restorationStarted := false
defer func() {
- if restorationStarted && operationErr != nil && !strings.Contains(operationErr.Error(), "result_unknown") {
- operationErr = fmt.Errorf("result_unknown: restoration may be partial; journal and checkpoints preserved: %w", operationErr)
+ if restorationStarted && operationErr != nil && !IsTextFileError(operationErr, TextFileResultUnknown) {
+ operationErr = NewTextFileError(TextFileResultUnknown, fmt.Errorf("restoration may be partial; journal and checkpoints preserved: %w", operationErr))
}
}()
grant, err := RequirePluginDevelopment(ctx, "recover")
@@ -824,13 +824,13 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
files, err := snapshotPluginProject(root, nil, manifest.TemporaryFiles)
if err != nil {
if manifest.mutationPending() {
- return fmt.Errorf("result_unknown: pending project cannot be safely restored; manual inspection required; source and journal preserved: %w", err)
+ return NewTextFileError(TextFileResultUnknown, fmt.Errorf("pending project cannot be safely restored; manual inspection required; source and journal preserved: %w", err))
}
return err
}
inventory := projectInventory(files)
if expectedRevision == "" || PluginProjectTreeRevision(inventory) != expectedRevision {
- return errors.New("revision_conflict: current project revision changed")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("current project revision changed"))
}
known := map[string]string{}
maps.Copy(known, manifest.Current)
@@ -840,7 +840,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
actual = PluginProjectMissingRevision
}
if actual != change.OldRevision && actual != change.NewRevision {
- return errors.New("revision_conflict: recovery would overwrite an external edit")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("recovery would overwrite an external edit"))
}
if actual == PluginProjectMissingRevision {
delete(known, name)
@@ -849,7 +849,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
}
}
if PluginProjectTreeRevision(known) != expectedRevision {
- return errors.New("revision_conflict: recovery would overwrite an external edit")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("recovery would overwrite an external edit"))
}
baseline, err := OpenPluginProjectDirectory(pluginProjectBaselinePath(grant, manifest), false)
if err != nil {
@@ -889,7 +889,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
}
}
if err = savePluginProjectManifest(grant, manifest); err != nil {
- return fmt.Errorf("backup_failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, err)
}
restorationStarted = true
for name, revision := range manifest.TemporaryFiles {
@@ -898,7 +898,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
continue
}
if readErr != nil || PluginProjectDigest(data) != revision {
- return errors.New("result_unknown: temporary file changed during restoration; preserved")
+ return NewTextFileError(TextFileResultUnknown, errors.New("temporary file changed during restoration; preserved"))
}
if err = root.Remove(name); err != nil {
return err
@@ -916,7 +916,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
return readErr
}
if actual != change.OldRevision {
- return errors.New("revision_conflict: source changed during restoration; journal preserved")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("source changed during restoration; journal preserved"))
}
if change.NewRevision == PluginProjectMissingRevision {
err = root.Remove(name)
@@ -930,7 +930,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
}
}
if err != nil {
- return fmt.Errorf("result_unknown: restoration interrupted; journal preserved: %w", err)
+ return NewTextFileError(TextFileResultUnknown, fmt.Errorf("restoration interrupted; journal preserved: %w", err))
}
}
restored, err := SnapshotPluginProject(root, nil)
@@ -938,7 +938,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)
return err
}
if PluginProjectTreeRevision(projectInventory(restored)) != PluginProjectTreeRevision(manifest.Baseline) {
- return errors.New("result_unknown: restored source differs; journal preserved")
+ return NewTextFileError(TextFileResultUnknown, errors.New("restored source differs; journal preserved"))
}
manifest.Current, manifest.Pending = projectInventory(restored), nil
manifest.TemporaryFiles = nil
diff --git a/kernel/util/plugin_project_prepare.go b/kernel/util/plugin_project_prepare.go
index 9333e1b226..452a25b907 100644
--- a/kernel/util/plugin_project_prepare.go
+++ b/kernel/util/plugin_project_prepare.go
@@ -22,7 +22,7 @@ func recheckPluginProjectGrantOperation(ctx context.Context, expected *PluginDev
return err
}
if !reflect.DeepEqual(current, expected) {
- return errors.New("revision_conflict: plugin development grant changed during the operation")
+ return NewTextFileError(TextFileRevisionConflict, errors.New("plugin development grant changed during the operation"))
}
return nil
}
@@ -31,18 +31,18 @@ func recheckPluginProjectGrantOperation(ctx context.Context, expected *PluginDev
func ensurePluginProjectCheckpoint(grant *PluginDevelopmentGrant, directory string, files map[string][]byte) error {
private, err := OpenPluginProjectDirectory(PluginProjectPrivateDir(grant.TaskID), true)
if err != nil {
- return fmt.Errorf("backup_failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, err)
}
defer private.Close()
if _, statErr := private.Lstat(directory); statErr == nil {
baseline, err := OpenPluginProjectDirectory(filepath.Join(PluginProjectPrivateDir(grant.TaskID), filepath.FromSlash(directory)), false)
if err != nil {
- return fmt.Errorf("backup_failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, err)
}
defer baseline.Close()
existing, err := SnapshotPluginProject(baseline, nil)
if err != nil || PluginProjectTreeRevision(projectInventory(existing)) != PluginProjectTreeRevision(projectInventory(files)) {
- return errors.New("backup_failed: existing checkpoint does not match the frozen source")
+ return NewTextFileError(TextFileBackupFailed, errors.New("existing checkpoint does not match the frozen source"))
}
return nil
} else if !errors.Is(statErr, os.ErrNotExist) {
@@ -60,19 +60,19 @@ func ensurePluginProjectCheckpoint(grant *PluginDevelopmentGrant, directory stri
for name, data := range files {
if err = writePluginProjectBytes(stage, name, data); err != nil {
stage.Close()
- return fmt.Errorf("backup_failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, err)
}
}
verify, err := SnapshotPluginProject(stage, nil)
stage.Close()
if err != nil || PluginProjectTreeRevision(projectInventory(verify)) != PluginProjectTreeRevision(projectInventory(files)) {
- return errors.New("backup_failed: staged checkpoint verification failed")
+ return NewTextFileError(TextFileBackupFailed, errors.New("staged checkpoint verification failed"))
}
if err = private.MkdirAll(path.Dir(directory), 0700); err != nil {
return err
}
if err = private.Rename(tmp, directory); err != nil {
- return fmt.Errorf("backup_failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, err)
}
return nil
}
@@ -124,19 +124,19 @@ func resumePluginProjectPreparation(ctx context.Context, grant *PluginDevelopmen
for name, data := range files {
if err = writePluginProjectBytes(stage, name, data); err != nil {
stage.Close()
- return nil, fmt.Errorf("result_unknown: preparation interrupted; retry prepare_project to rebuild uncommitted staging: %w", err)
+ return nil, NewTextFileError(TextFileResultUnknown, fmt.Errorf("preparation interrupted; retry prepare_project to rebuild uncommitted staging: %w", err))
}
}
verify, verifyErr := SnapshotPluginProject(stage, nil)
stage.Close()
if verifyErr != nil || PluginProjectTreeRevision(projectInventory(verify)) != PluginProjectTreeRevision(manifest.Baseline) {
- return nil, errors.New("result_unknown: staged source differs; preparation journal and checkpoint preserved")
+ return nil, NewTextFileError(TextFileResultUnknown, errors.New("staged source differs; preparation journal and checkpoint preserved"))
}
if err = recheckPluginProjectGrantOperation(ctx, grant, operation); err != nil {
return nil, err
}
if err = project.Rename(".prepare-source", "source"); err != nil {
- return nil, fmt.Errorf("result_unknown: source publication failed; preparation is resumable: %w", err)
+ return nil, NewTextFileError(TextFileResultUnknown, fmt.Errorf("source publication failed; preparation is resumable: %w", err))
}
} else if statErr != nil {
return nil, statErr
@@ -151,15 +151,15 @@ func resumePluginProjectPreparation(ctx context.Context, grant *PluginDevelopmen
return nil, err
}
if PluginProjectTreeRevision(projectInventory(actual)) != PluginProjectTreeRevision(manifest.Baseline) {
- return nil, errors.New("revision_conflict: published preparation source has external changes; preserved")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("published preparation source has external changes; preserved"))
}
manifest.Current, manifest.Preparing = projectInventory(actual), false
if err = savePluginProjectManifest(grant, manifest); err != nil {
- return nil, fmt.Errorf("result_unknown: complete source and checkpoint retained; retry prepare_project to finish journal: %w", err)
+ return nil, NewTextFileError(TextFileResultUnknown, fmt.Errorf("complete source and checkpoint retained; retry prepare_project to finish journal: %w", err))
}
if recoveryOnly {
if _, err = RequirePluginDevelopment(ctx, "recovered"); err != nil {
- return nil, fmt.Errorf("result_unknown: preparation completed but recovery grant could not be consumed: %w", err)
+ return nil, NewTextFileError(TextFileResultUnknown, fmt.Errorf("preparation completed but recovery grant could not be consumed: %w", err))
}
}
return PluginProjectArtifactStatus(grant, source)
diff --git a/kernel/util/plugin_project_replan.go b/kernel/util/plugin_project_replan.go
index 773d98fa1a..ee9750742c 100644
--- a/kernel/util/plugin_project_replan.go
+++ b/kernel/util/plugin_project_replan.go
@@ -26,10 +26,10 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, all
return nil, err
}
if manifest.SourcePath != grant.SourcePath || manifest.SourceRevision != grant.SourceRevision {
- return nil, errors.New("revision_conflict: changing import provenance requires a new plugin development task")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("changing import provenance requires a new plugin development task"))
}
if manifest.mutationPending() {
- return nil, errors.New("result_unknown: resolve interrupted source mutation before preparing a new plan")
+ return nil, NewTextFileError(TextFileResultUnknown, errors.New("resolve interrupted source mutation before preparing a new plan"))
}
if err = validateProjectBaseline(grant, manifest); err != nil {
return nil, err
@@ -46,7 +46,7 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, all
inventory := projectInventory(files)
revision := PluginProjectTreeRevision(inventory)
if expected == "" || expected != revision || revision != PluginProjectTreeRevision(manifest.Current) {
- return nil, errors.New("revision_conflict: replan requires expectedSourceRevision and unchanged recorded source")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("replan requires expectedSourceRevision and unchanged recorded source"))
}
set := map[string]bool{}
for _, name := range allowed {
@@ -54,7 +54,7 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, all
}
for name := range files {
if !set[name] {
- return nil, fmt.Errorf("invalid_path: existing file %s must remain in the approved write scope, including when it will be explicitly deleted", name)
+ return nil, NewTextFileError(TextFileInvalidPath, fmt.Errorf("existing file %s must remain in the approved write scope, including when it will be explicitly deleted", name))
}
}
if manifest.PlanHash == grant.PlanHash {
@@ -83,7 +83,7 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, all
return nil, err
}
if PluginProjectTreeRevision(projectInventory(again)) != expected {
- return nil, errors.New("revision_conflict: source changed while preparing new checkpoint")
+ return nil, NewTextFileError(TextFileRevisionConflict, errors.New("source changed while preparing new checkpoint"))
}
for _, name := range allowed {
if err = source.MkdirAll(path.Dir(name), 0700); err != nil {
@@ -104,7 +104,7 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, all
// 调用方持有项目锁,且已确认没有待完成写入;清单原子切换后才能删除上一基线。
func cleanPluginProjectCheckpoints(grant *PluginDevelopmentGrant, manifest *pluginProjectManifest, retain ...string) error {
if manifest.Preparing || manifest.mutationPending() {
- return errors.New("result_unknown: pending project recovery evidence must be preserved")
+ return NewTextFileError(TextFileResultUnknown, errors.New("pending project recovery evidence must be preserved"))
}
if err := validateProjectBaseline(grant, manifest); err != nil {
return err
@@ -139,7 +139,7 @@ func cleanPluginProjectCheckpoints(grant *PluginDevelopmentGrant, manifest *plug
return private.RemoveAll(name)
}
if err = remove("baseline"); err != nil {
- return fmt.Errorf("backup_failed: obsolete checkpoint cleanup failed; current baseline preserved: %w", err)
+ return NewTextFileError(TextFileBackupFailed, fmt.Errorf("obsolete checkpoint cleanup failed; current baseline preserved: %w", err))
}
entries, err := fs.ReadDir(private.FS(), ".")
if err != nil {
@@ -149,7 +149,7 @@ func cleanPluginProjectCheckpoints(grant *PluginDevelopmentGrant, manifest *plug
name := entry.Name()
if suffix, ok := strings.CutPrefix(name, ".checkpoint-"); ok && len(suffix) == 26 && strings.Trim(suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") == "" {
if err = remove(name); err != nil {
- return fmt.Errorf("backup_failed: staged checkpoint cleanup failed: %w", err)
+ return NewTextFileError(TextFileBackupFailed, fmt.Errorf("staged checkpoint cleanup failed: %w", err))
}
}
}
@@ -161,7 +161,7 @@ func cleanPluginProjectCheckpoints(grant *PluginDevelopmentGrant, manifest *plug
return err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
- return errors.New("backup_failed: checkpoint directory must be an unlinked directory")
+ return NewTextFileError(TextFileBackupFailed, errors.New("checkpoint directory must be an unlinked directory"))
}
entries, err = fs.ReadDir(private.FS(), "checkpoints")
if err != nil {
@@ -172,7 +172,7 @@ func cleanPluginProjectCheckpoints(grant *PluginDevelopmentGrant, manifest *plug
continue
}
if err = remove(path.Join("checkpoints", entry.Name())); err != nil {
- return fmt.Errorf("backup_failed: obsolete checkpoint cleanup failed; current baseline preserved: %w", err)
+ return NewTextFileError(TextFileBackupFailed, fmt.Errorf("obsolete checkpoint cleanup failed; current baseline preserved: %w", err))
}
}
return nil
diff --git a/kernel/util/plugin_project_source.go b/kernel/util/plugin_project_source.go
index 2a5b131f6b..9a4b0eef4a 100644
--- a/kernel/util/plugin_project_source.go
+++ b/kernel/util/plugin_project_source.go
@@ -23,13 +23,13 @@ func validatePluginProjectPrefixes(names []string) error {
}
key := strings.ToLower(name)
if files[key] {
- return errors.New("invalid_path: duplicate or case-colliding approved file")
+ return NewTextFileError(TextFileInvalidPath, errors.New("duplicate or case-colliding approved file"))
}
files[key] = true
for prefix := name; prefix != "."; prefix = path.Dir(prefix) {
key := strings.ToLower(prefix)
if old, ok := seen[key]; ok && old != prefix {
- return errors.New("invalid_path: case-colliding source path prefix")
+ return NewTextFileError(TextFileInvalidPath, errors.New("case-colliding source path prefix"))
}
seen[key] = prefix
}
@@ -37,7 +37,7 @@ func validatePluginProjectPrefixes(names []string) error {
for name := range files {
for parent := path.Dir(name); parent != "."; parent = path.Dir(parent) {
if files[parent] {
- return errors.New("invalid_path: source file/directory collision")
+ return NewTextFileError(TextFileInvalidPath, errors.New("source file/directory collision"))
}
}
}
@@ -47,7 +47,7 @@ func validatePluginProjectPrefixes(names []string) error {
// 只读取冻结允许清单的现有文件;允许将未来新建文件列入方案,但绝不追随链接。
func snapshotSelectedPluginSource(root *os.Root, selected []string, authorize func(string) error) (map[string][]byte, error) {
if len(selected) == 0 || len(selected) > PluginProjectMaxFiles {
- return nil, errors.New("invalid_path: sourceFiles must be a bounded nonempty file list")
+ return nil, NewTextFileError(TextFileInvalidPath, errors.New("sourceFiles must be a bounded nonempty file list"))
}
if err := validatePluginProjectPrefixes(selected); err != nil {
return nil, err
@@ -69,7 +69,7 @@ func snapshotSelectedPluginSource(root *os.Root, selected []string, authorize fu
}
total += int64(len(data))
if total > PluginProjectMaxBytes {
- return nil, errors.New("too_large: selected source exceeds 64 MiB")
+ return nil, NewTextFileError(TextFileTooLarge, errors.New("selected source exceeds 64 MiB"))
}
files[name] = data
}
@@ -91,7 +91,7 @@ func inspectPluginProjectCandidate(root *os.Root, authorize func(string) error)
}
paths++
if paths > PluginProjectMaxFiles*2 {
- return errors.New("too_large: source inventory exceeds bounded inspection")
+ return NewTextFileError(TextFileTooLarge, errors.New("source inventory exceeds bounded inspection"))
}
exclude := func(reason string) error {
excluded = append(excluded, PluginProjectExcludedFile{name, reason})
@@ -115,7 +115,7 @@ func inspectPluginProjectCandidate(root *os.Root, authorize func(string) error)
return nil
}
if len(files) >= PluginProjectMaxFiles {
- return errors.New("too_large: source inventory contains too many files")
+ return NewTextFileError(TextFileTooLarge, errors.New("source inventory contains too many files"))
}
data, err := readPluginProjectFile(root, name)
if err != nil {
@@ -123,7 +123,7 @@ func inspectPluginProjectCandidate(root *os.Root, authorize func(string) error)
}
total += int64(len(data))
if total > PluginProjectMaxBytes {
- return errors.New("too_large: source inventory exceeds 64 MiB")
+ return NewTextFileError(TextFileTooLarge, errors.New("source inventory exceeds 64 MiB"))
}
files[name] = data
return nil
diff --git a/kernel/util/text_file.go b/kernel/util/text_file.go
index 514b732ff5..4be91bc0fe 100644
--- a/kernel/util/text_file.go
+++ b/kernel/util/text_file.go
@@ -20,15 +20,39 @@ import (
const MaxTextFileBytes = 8 * 1024 * 1024
+const (
+ TextFileRevisionConflict = "revision_conflict"
+ TextFileInvalidPath = "invalid_path"
+ TextFileUnsupportedEncoding = "unsupported_encoding"
+ TextFileTooLarge = "too_large"
+ TextFileBackupFailed = "backup_failed"
+ TextFileResultUnknown = "result_unknown"
+ TextFileWriteFailed = "write_failed"
+ TextFileCancelled = "cancelled"
+)
+
// TextFileError 说明目标是否可能已变化;result_unknown 必须先读取目标核实,不能直接重试修改。
type TextFileError struct {
Code string `json:"code"`
Message string `json:"message"`
Written bool `json:"written"`
+ cause error
}
func (e *TextFileError) Error() string { return e.Code + ": " + e.Message }
+func (e *TextFileError) Unwrap() error { return e.cause }
+
+// NewTextFileError 将结果码与错误原因分别保存,保留错误链供调用方判断。
+func NewTextFileError(code string, err error) *TextFileError {
+ return &TextFileError{Code: code, Message: err.Error(), cause: err}
+}
+
+func IsTextFileError(err error, code string) bool {
+ failure, ok := errors.AsType[*TextFileError](err)
+ return ok && failure.Code == code
+}
+
func textFileError(code, message string) error {
return &TextFileError{Code: code, Message: message}
}
@@ -37,12 +61,7 @@ func textFileBeforeCommitError(err error) error {
if failure, ok := errors.AsType[*TextFileError](err); ok {
return failure
}
- for _, code := range []string{"revision_conflict", "invalid_path", "unsupported_encoding", "too_large", "backup_failed", "result_unknown"} {
- if after, ok := strings.CutPrefix(err.Error(), code+":"); ok {
- return textFileError(code, strings.TrimSpace(after))
- }
- }
- return textFileError("backup_failed", err.Error())
+ return NewTextFileError(TextFileBackupFailed, err)
}
func TextFileRevision(content []byte) string { return fmt.Sprintf("%x", sha256.Sum256(content)) }
@@ -55,7 +74,7 @@ func CheckSingleLinkRegularFile(file *os.File) error {
return err
}
if !info.Mode().IsRegular() {
- return textFileError("invalid_path", "target must be a regular file")
+ return textFileError(TextFileInvalidPath, "target must be a regular file")
}
return textFileSingleLink(file, info)
}
@@ -69,7 +88,7 @@ func OpenFileNoFollow(root *os.Root, name string) (*os.File, error) {
// ValidateTextFilePath 拒绝非规范路径,避免将目录穿越、Windows 别名或其他分隔符静默转换为目标路径。
func ValidateTextFilePath(p string) error {
if p == "." || validateManagedSkillPath(p) != nil {
- return textFileError("invalid_path", "expected a canonical relative file path")
+ return textFileError(TextFileInvalidPath, "expected a canonical relative file path")
}
return nil
}
@@ -77,9 +96,9 @@ func ValidateTextFilePath(p string) error {
func ValidateTextFileContent(content string) error {
if err := validateManagedSkillSource(content); err != nil {
if errors.Is(err, ErrSkillTooLarge) {
- return textFileError("too_large", "text files must be at most 8 MiB")
+ return textFileError(TextFileTooLarge, "text files must be at most 8 MiB")
}
- return textFileError("unsupported_encoding", "only UTF-8 text without binary control characters is supported")
+ return textFileError(TextFileUnsupportedEncoding, "only UTF-8 text without binary control characters is supported")
}
return nil
}
@@ -98,7 +117,7 @@ func openTextFileParent(root *os.Root, p string) (*os.Root, string, error) {
info, statErr := current.Lstat(part)
if statErr != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
current.Close()
- return nil, "", textFileError("invalid_path", "parent must be an existing regular directory")
+ return nil, "", textFileError(TextFileInvalidPath, "parent must be an existing regular directory")
}
next, openErr := current.OpenRoot(part)
current.Close()
@@ -108,7 +127,7 @@ func openTextFileParent(root *os.Root, p string) (*os.Root, string, error) {
opened, statErr := next.Stat(".")
if statErr != nil || !os.SameFile(info, opened) {
next.Close()
- return nil, "", textFileError("invalid_path", "parent changed while opening")
+ return nil, "", textFileError(TextFileInvalidPath, "parent changed while opening")
}
current = next
}
@@ -125,7 +144,7 @@ func readRegularFileAt(parent *os.Root, name string, textOnly bool) (string, os.
return "", nil, err
}
if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
- return "", nil, textFileError("invalid_path", "target must be a regular unlinked file")
+ return "", nil, textFileError(TextFileInvalidPath, "target must be a regular unlinked file")
}
file, err := openTextFileRead(parent, name)
if err != nil {
@@ -137,7 +156,7 @@ func readRegularFileAt(parent *os.Root, name string, textOnly bool) (string, os.
return "", nil, err
}
if !opened.Mode().IsRegular() || !os.SameFile(info, opened) {
- return "", nil, textFileError("invalid_path", "target changed while opening")
+ return "", nil, textFileError(TextFileInvalidPath, "target changed while opening")
}
if err = textFileSingleLink(file, opened); err != nil {
return "", nil, err
@@ -147,7 +166,7 @@ func readRegularFileAt(parent *os.Root, name string, textOnly bool) (string, os.
limit = PluginProjectMaxFileBytes
}
if opened.Size() > limit {
- return "", nil, textFileError("too_large", fmt.Sprintf("file must be at most %d bytes", limit))
+ return "", nil, textFileError(TextFileTooLarge, fmt.Sprintf("file must be at most %d bytes", limit))
}
data, err := io.ReadAll(io.LimitReader(file, limit+1))
if err != nil {
@@ -155,7 +174,7 @@ func readRegularFileAt(parent *os.Root, name string, textOnly bool) (string, os.
}
content := string(data)
if int64(len(content)) > limit {
- return "", nil, textFileError("too_large", fmt.Sprintf("file must be at most %d bytes", limit))
+ return "", nil, textFileError(TextFileTooLarge, fmt.Sprintf("file must be at most %d bytes", limit))
}
if textOnly {
if err = ValidateTextFileContent(content); err != nil {
@@ -197,7 +216,7 @@ func ApplyTextEdits(original string, edits []TextEdit) (string, []TextEditRange,
return "", nil, textFileError("invalid_edit", "oldText must not be empty")
}
if !utf8.ValidString(edit.OldText) || !utf8.ValidString(edit.NewText) {
- return "", nil, textFileError("unsupported_encoding", "edits must contain UTF-8 text")
+ return "", nil, textFileError(TextFileUnsupportedEncoding, "edits must contain UTF-8 text")
}
start := strings.Index(original, edit.OldText)
if start < 0 {
@@ -219,7 +238,7 @@ func ApplyTextEdits(original string, edits []TextEdit) (string, []TextEditRange,
size += len(edit.NewText) - len(edit.OldText)
}
if size > MaxTextFileBytes {
- return "", nil, textFileError("too_large", "edited text must be at most 8 MiB")
+ return "", nil, textFileError(TextFileTooLarge, "edited text must be at most 8 MiB")
}
var out strings.Builder
out.Grow(size)
@@ -299,7 +318,7 @@ func mutateTextFile(ctx context.Context, root *os.Root, p string, request TextFi
}
defer unlock()
if request.IfAbsent == (request.ExpectedRevision != "") || (request.IfAbsent && request.Edits != nil) {
- return ret, textFileError("revision_conflict", "provide exactly one of ifAbsent=true or expectedRevision; edits require expectedRevision")
+ return ret, textFileError(TextFileRevisionConflict, "provide exactly one of ifAbsent=true or expectedRevision; edits require expectedRevision")
}
parent, name, err := openTextFileParent(root, p)
if err != nil {
@@ -311,7 +330,7 @@ func mutateTextFile(ctx context.Context, root *os.Root, p string, request TextFi
var originalInfo os.FileInfo
if request.IfAbsent {
if _, statErr := parent.Lstat(name); !errors.Is(statErr, os.ErrNotExist) {
- return ret, textFileError("revision_conflict", "new file must not exist")
+ return ret, textFileError(TextFileRevisionConflict, "new file must not exist")
}
} else {
original, originalInfo, err = readTextFileAt(parent, name)
@@ -320,7 +339,7 @@ func mutateTextFile(ctx context.Context, root *os.Root, p string, request TextFi
}
ret.OldRevision = TextFileRevision([]byte(original))
if ret.OldRevision != request.ExpectedRevision {
- return ret, textFileError("revision_conflict", "file changed; read it again before writing")
+ return ret, textFileError(TextFileRevisionConflict, "file changed; read it again before writing")
}
mode = originalInfo.Mode().Perm()
}
@@ -361,7 +380,7 @@ func mutateTextFile(ctx context.Context, root *os.Root, p string, request TextFi
}
file, err := parent.OpenFile(temporary, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
- return ret, textFileError("write_failed", err.Error())
+ return ret, textFileError(TextFileWriteFailed, err.Error())
}
defer parent.Remove(temporary)
if err = file.Chmod(mode); err == nil {
@@ -379,7 +398,7 @@ func mutateTextFile(ctx context.Context, root *os.Root, p string, request TextFi
err = closeErr
}
if err != nil {
- return ret, textFileError("write_failed", err.Error())
+ return ret, textFileError(TextFileWriteFailed, err.Error())
}
// 固定父目录句柄,防止中间目录被替换后改变写入目标;同时拒绝父目录在打开后被移动的情况。
if err = sameTextFileParent(root, p, parent); err != nil {
@@ -411,22 +430,22 @@ func mutateTextFile(ctx context.Context, root *os.Root, p string, request TextFi
if err == nil {
err = operations.remove(parent, temporary)
if err != nil {
- return ret, &TextFileError{Code: "result_unknown", Message: err.Error(), Written: true}
+ return ret, &TextFileError{Code: TextFileResultUnknown, Message: err.Error(), Written: true}
}
}
} else {
err = operations.rename(parent, temporary, name)
}
if err != nil {
- return ret, textFileError("write_failed", err.Error())
+ return ret, textFileError(TextFileWriteFailed, err.Error())
}
actual, _, readErr := readTextFileAt(parent, name)
if readErr != nil || TextFileRevision([]byte(actual)) != ret.NewRevision {
- return ret, &TextFileError{Code: "result_unknown", Message: "replacement completed but readback did not match; inspect before retrying", Written: true}
+ return ret, &TextFileError{Code: TextFileResultUnknown, Message: "replacement completed but readback did not match; inspect before retrying", Written: true}
}
if request.AfterCommit != nil {
if err = request.AfterCommit(); err != nil {
- return ret, &TextFileError{Code: "result_unknown", Message: "replacement completed but project journal update failed: " + err.Error(), Written: true}
+ return ret, &TextFileError{Code: TextFileResultUnknown, Message: "replacement completed but project journal update failed: " + err.Error(), Written: true}
}
}
return ret, nil
@@ -444,7 +463,7 @@ func sameTextFileParent(root *os.Root, p string, parent *os.Root) error {
}
second, err := current.Stat(".")
if err != nil || !os.SameFile(first, second) {
- return textFileError("invalid_path", "parent changed during write")
+ return textFileError(TextFileInvalidPath, "parent changed during write")
}
return nil
}
@@ -452,7 +471,7 @@ func sameTextFileParent(root *os.Root, p string, parent *os.Root) error {
func checkTextFileRevision(parent *os.Root, name string, absent bool, revision string, originalInfo os.FileInfo) error {
if absent {
if _, err := parent.Lstat(name); !errors.Is(err, os.ErrNotExist) {
- return textFileError("revision_conflict", "new file appeared during write")
+ return textFileError(TextFileRevisionConflict, "new file appeared during write")
}
return nil
}
@@ -461,7 +480,7 @@ func checkTextFileRevision(parent *os.Root, name string, absent bool, revision s
return err
}
if !os.SameFile(originalInfo, info) || info.Mode().Perm() != originalInfo.Mode().Perm() || TextFileRevision([]byte(content)) != revision {
- return textFileError("revision_conflict", "file changed during write")
+ return textFileError(TextFileRevisionConflict, "file changed during write")
}
return nil
}
@@ -494,7 +513,7 @@ func MutateTextFileName(ctx context.Context, root *os.Root, p, target string, re
}
defer unlock()
if request.ExpectedRevision == "" {
- return ret, textFileError("revision_conflict", "expectedRevision is required")
+ return ret, textFileError(TextFileRevisionConflict, "expectedRevision is required")
}
parent, name, err := openTextFileParent(root, p)
if err != nil {
@@ -508,7 +527,7 @@ func MutateTextFileName(ctx context.Context, root *os.Root, p, target string, re
ret.OldRevision = TextFileRevision([]byte(original))
ret.NewRevision = "missing"
if ret.OldRevision != request.ExpectedRevision {
- return ret, textFileError("revision_conflict", "file changed; read it again before modifying")
+ return ret, textFileError(TextFileRevisionConflict, "file changed; read it again before modifying")
}
var destination *os.Root
var newName string
@@ -519,7 +538,7 @@ func MutateTextFileName(ctx context.Context, root *os.Root, p, target string, re
}
defer destination.Close()
if _, statErr := destination.Lstat(newName); !errors.Is(statErr, os.ErrNotExist) {
- return ret, textFileError("revision_conflict", "rename destination must not exist")
+ return ret, textFileError(TextFileRevisionConflict, "rename destination must not exist")
}
ret.NewRevision = ret.OldRevision
}
@@ -540,14 +559,14 @@ func MutateTextFileName(ctx context.Context, root *os.Root, p, target string, re
return err
}
if !os.SameFile(originalInfo, info) || TextFileRevision([]byte(current)) != ret.OldRevision {
- return textFileError("revision_conflict", "file changed during operation")
+ return textFileError(TextFileRevisionConflict, "file changed during operation")
}
if destination != nil {
if err := sameTextFileParent(root, target, destination); err != nil {
return err
}
if _, err := destination.Lstat(newName); !errors.Is(err, os.ErrNotExist) {
- return textFileError("revision_conflict", "rename destination appeared during operation")
+ return textFileError(TextFileRevisionConflict, "rename destination appeared during operation")
}
}
return nil
@@ -572,19 +591,19 @@ func MutateTextFileName(ctx context.Context, root *os.Root, p, target string, re
err = parent.Remove(name)
}
if err != nil {
- return ret, textFileError("write_failed", err.Error())
+ return ret, textFileError(TextFileWriteFailed, err.Error())
}
if destination != nil {
actual, _, readErr := readRegularFileAt(destination, newName, false)
if readErr != nil || TextFileRevision([]byte(actual)) != ret.NewRevision {
- return ret, &TextFileError{Code: "result_unknown", Message: "rename completed but readback failed; inspect before retrying", Written: true}
+ return ret, &TextFileError{Code: TextFileResultUnknown, Message: "rename completed but readback failed; inspect before retrying", Written: true}
}
} else if _, statErr := parent.Lstat(name); !errors.Is(statErr, os.ErrNotExist) {
- return ret, &TextFileError{Code: "result_unknown", Message: "delete completed but absence could not be verified", Written: true}
+ return ret, &TextFileError{Code: TextFileResultUnknown, Message: "delete completed but absence could not be verified", Written: true}
}
if request.AfterCommit != nil {
if err = request.AfterCommit(); err != nil {
- return ret, &TextFileError{Code: "result_unknown", Message: "operation completed but project journal update failed: " + err.Error(), Written: true}
+ return ret, &TextFileError{Code: TextFileResultUnknown, Message: "operation completed but project journal update failed: " + err.Error(), Written: true}
}
}
return ret, nil
diff --git a/kernel/util/text_file_error_test.go b/kernel/util/text_file_error_test.go
new file mode 100644
index 0000000000..94ecb0af7b
--- /dev/null
+++ b/kernel/util/text_file_error_test.go
@@ -0,0 +1,48 @@
+package util
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "testing"
+)
+
+func TestTextFileErrorPreservesCodeAndCause(t *testing.T) {
+ cause := errors.New("source unavailable")
+ for _, code := range []string{TextFileRevisionConflict, TextFileInvalidPath, TextFileUnsupportedEncoding,
+ TextFileTooLarge, TextFileBackupFailed, TextFileResultUnknown} {
+ t.Run(code, func(t *testing.T) {
+ failure := NewTextFileError(code, cause)
+ failure.Written = true
+ wrapped := fmt.Errorf("project operation: %w", failure)
+ if !IsTextFileError(wrapped, code) || !errors.Is(wrapped, cause) {
+ t.Fatalf("错误码或原因丢失:%v", wrapped)
+ }
+ if got := textFileBeforeCommitError(wrapped); got != failure {
+ t.Fatalf("备份错误未保留结构化状态:%#v", got)
+ }
+ data, err := json.Marshal(failure)
+ want := fmt.Sprintf(`{"code":%q,"message":"source unavailable","written":true}`, code)
+ if err != nil || string(data) != want {
+ t.Fatalf("错误响应改变:%s,%v", data, err)
+ }
+ })
+ }
+}
+
+func TestTextFileErrorIgnoresCodesInMessages(t *testing.T) {
+ for _, message := range []string{"result_unknown-draft.md: permission denied", "result_unknown: plain diagnostic"} {
+ err := errors.New(message)
+ if IsTextFileError(err, TextFileResultUnknown) {
+ t.Fatalf("错误文本被解释为结果码:%v", err)
+ }
+ failure := textFileBeforeCommitError(err)
+ if !IsTextFileError(failure, TextFileBackupFailed) || !errors.Is(failure, err) {
+ t.Fatalf("未保留备份失败阶段和原因:%v", failure)
+ }
+ }
+ err := ValidatePluginProjectFile("../result_unknown-draft.md")
+ if !IsTextFileError(err, TextFileInvalidPath) {
+ t.Fatalf("项目路径校验未提供结构化错误:%v", err)
+ }
+}
diff --git a/kernel/util/text_file_links_other.go b/kernel/util/text_file_links_other.go
index 0b0015c31e..73c7c830c2 100644
--- a/kernel/util/text_file_links_other.go
+++ b/kernel/util/text_file_links_other.go
@@ -9,9 +9,9 @@ package util
import "os"
func openTextFileRead(*os.Root, string) (*os.File, error) {
- return nil, textFileError("invalid_path", "safe file handles are unavailable on this platform")
+ return nil, textFileError(TextFileInvalidPath, "safe file handles are unavailable on this platform")
}
func textFileSingleLink(*os.File, os.FileInfo) error {
- return textFileError("invalid_path", "file link counts are unavailable on this platform")
+ return textFileError(TextFileInvalidPath, "file link counts are unavailable on this platform")
}
diff --git a/kernel/util/text_file_links_unix.go b/kernel/util/text_file_links_unix.go
index 4b87ce4fea..f27b08035a 100644
--- a/kernel/util/text_file_links_unix.go
+++ b/kernel/util/text_file_links_unix.go
@@ -30,5 +30,5 @@ func textFileSingleLink(_ *os.File, info os.FileInfo) error {
}
}
}
- return textFileError("invalid_path", "hard-linked files or unknown link counts are not supported")
+ return textFileError(TextFileInvalidPath, "hard-linked files or unknown link counts are not supported")
}
diff --git a/kernel/util/text_file_links_windows.go b/kernel/util/text_file_links_windows.go
index 39bcc04c92..96fc342ea4 100644
--- a/kernel/util/text_file_links_windows.go
+++ b/kernel/util/text_file_links_windows.go
@@ -21,7 +21,7 @@ func textFileSingleLink(file *os.File, _ os.FileInfo) error {
return err
}
if info.NumberOfLinks != 1 {
- return textFileError("invalid_path", "hard-linked files are not supported")
+ return textFileError(TextFileInvalidPath, "hard-linked files are not supported")
}
return nil
}