Просмотр исходного кода

feat(plugin-market): 新增本机插件市场目录、包与 resolve 接口

桌面端 host-core 需要匿名读取市场目录、插件包,并在安装时解析包地址。
新增 /plugin 下的三个接口:catalog.json、package/{file} 和
api/v1/download/resolve;目录与包由 plugin.market.root-path 提供,默认
./data/plugin-market。

/plugin/** 加入 Sa-Token 白名单,因为客户端请求不携带登录态。resolve 按
catalog 返回 sha256、sizeBytes 和本地包地址;未知版本返回 NOT_FOUND,
包元数据缺失返回 NO_DOWNLOAD_SOURCE。安装、权限与存储逻辑不变。

市场目录与镜像脚本位于 .gitignore 忽略的 ai-server/data 和 tools 下,
不随本次提交。
cc 1 неделя назад
Родитель
Сommit
c7faeb946a

+ 2 - 0
ai-server/src/main/java/com/zsjz/ai/common/config/SaTokenWebConfig.java

@@ -44,6 +44,8 @@ public class SaTokenWebConfig implements WebMvcConfigurer {
             "/sys/code",
             "/sys/noNet",
             "/sys/map/**",
+            /* 本机插件市场:桌面端 host-core 匿名读取目录、插件包和 resolve。 */
+            "/plugin/**",
             "/error",
     };
 

+ 181 - 0
ai-server/src/main/java/com/zsjz/ai/module/plugin/controller/PluginMarketController.java

@@ -0,0 +1,181 @@
+package com.zsjz.ai.module.plugin.controller;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.zsjz.ai.common.exception.ServerException;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.CacheControl;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/**
+ * 本机插件市场:目录、插件包和安装解析接口。
+ *
+ * <p>桌面端 host-core 以匿名 HTTP 直接读取这三个接口,不走登录态,因此
+ * {@code /plugin/**} 必须加入 Sa-Token 白名单。目录与包位于
+ * {@code plugin.market.root-path} 下:{@code catalog.json} 与
+ * {@code packages/*.piplug}。
+ */
+@RestController
+@RequestMapping("/plugin")
+public class PluginMarketController {
+
+    /** 插件包文件名白名单:与 catalog 中的 url 字段一致。 */
+    private static final Pattern PACKAGE_NAME =
+            Pattern.compile("^[A-Za-z0-9][A-Za-z0-9._-]*\\.piplug$");
+
+    private final Path marketRoot;
+    private final ObjectMapper objectMapper;
+
+    public PluginMarketController(
+            @Value("${plugin.market.root-path:./data/plugin-market}") String rootPath,
+            ObjectMapper objectMapper) {
+        this.marketRoot = Paths.get(rootPath).toAbsolutePath().normalize();
+        this.objectMapper = objectMapper;
+    }
+
+    /** 市场目录;桌面端用它展示插件列表。 */
+    @GetMapping("/catalog.json")
+    public ResponseEntity<Resource> catalog() {
+        Path file = catalogPath();
+        if (!Files.isRegularFile(file)) {
+            throw new ServerException(404, "插件市场目录不存在");
+        }
+        return ResponseEntity.ok()
+                .contentType(MediaType.APPLICATION_JSON)
+                .cacheControl(CacheControl.noCache())
+                .body(new FileSystemResource(file));
+    }
+
+    /** 单个插件包;目录中的 url 最终解析到 {@code /plugin/package/<file>}。 */
+    @GetMapping("/package/{filename:.+}")
+    public ResponseEntity<Resource> packageFile(@PathVariable String filename) {
+        if (!PACKAGE_NAME.matcher(filename).matches()) {
+            throw new ServerException(400, "非法的插件包文件名");
+        }
+        Path packagesRoot = marketRoot.resolve("packages").normalize();
+        Path file = packagesRoot.resolve(filename).normalize();
+        if (!file.startsWith(packagesRoot) || !Files.isRegularFile(file)) {
+            throw new ServerException(404, "插件包不存在");
+        }
+        return ResponseEntity.ok()
+                .contentType(MediaType.APPLICATION_OCTET_STREAM)
+                .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
+                .cacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic())
+                .body(new FileSystemResource(file));
+    }
+
+    /**
+     * 安装解析:按 pluginId + version 返回目录中的摘要与下载地址。
+     *
+     * <p>路径与官方中心一致(目录路径下的 {@code /api/v1/download/resolve}),
+     * 这样桌面端的 resolve 流程不需要改变。未知版本返回 {@code NOT_FOUND},
+     * 元数据缺失返回 {@code NO_DOWNLOAD_SOURCE},两者都是客户端可识别的错误码。
+     */
+    @PostMapping("/api/v1/download/resolve")
+    public ResponseEntity<Map<String, Object>> resolve(@RequestBody ResolveRequest request) {
+        if (request == null
+                || isBlank(request.pluginId())
+                || isBlank(request.version())) {
+            return error(400, "BAD_REQUEST", "pluginId and version are required");
+        }
+        Path catalogPath = catalogPath();
+        if (!Files.isRegularFile(catalogPath)) {
+            return error(503, "NO_DOWNLOAD_SOURCE", "plugin market catalog is unavailable");
+        }
+        try {
+            JsonNode catalog = objectMapper.readTree(catalogPath.toFile());
+            JsonNode version = findVersion(catalog, request.pluginId(), request.version());
+            if (version == null) {
+                return error(404, "NOT_FOUND", "plugin version not found");
+            }
+            String sha256 = version.path("shasum").asText("").trim();
+            String packageUrl = version.path("url").asText("").trim();
+            if (sha256.isEmpty() || packageUrl.isEmpty()) {
+                return error(503, "NO_DOWNLOAD_SOURCE", "package metadata is incomplete");
+            }
+
+            Map<String, Object> mirror = new LinkedHashMap<>();
+            mirror.put("source", "local");
+            mirror.put("url", absolutePackageUrl(catalog, packageUrl));
+
+            Map<String, Object> body = new LinkedHashMap<>();
+            body.put("sha256", sha256);
+            // 用 Integer 而不是 Long:项目的 Jackson 配置把 Long 序列化成字符串,
+            // 桌面端 ResolvedDownload.sizeBytes 是数字类型。
+            body.put("sizeBytes", (int) Math.max(0, version.path("sizeBytes").asLong(0)));
+            body.put("downloads", List.of(mirror));
+            return ResponseEntity.ok(body);
+        } catch (Exception error) {
+            return error(503, "NO_DOWNLOAD_SOURCE", "plugin market catalog could not be read");
+        }
+    }
+
+    private Path catalogPath() {
+        return marketRoot.resolve("catalog.json").normalize();
+    }
+
+    private static JsonNode findVersion(JsonNode catalog, String pluginId, String version) {
+        for (JsonNode plugin : catalog.path("plugins")) {
+            if (!pluginId.equals(plugin.path("id").asText())) {
+                continue;
+            }
+            for (JsonNode candidate : plugin.path("versions")) {
+                if (version.equals(candidate.path("version").asText())) {
+                    return candidate;
+                }
+            }
+            return null;
+        }
+        return null;
+    }
+
+    private static String absolutePackageUrl(JsonNode catalog, String packageUrl) {
+        if (packageUrl.startsWith("http://")
+                || packageUrl.startsWith("https://")
+                || packageUrl.startsWith("file://")) {
+            return packageUrl;
+        }
+        String base = catalog.path("artifact_base_url").asText("").trim();
+        if (base.isEmpty()) {
+            base = ServletUriComponentsBuilder.fromCurrentContextPath()
+                    .path("/plugin/package/")
+                    .toUriString();
+        } else if (!base.endsWith("/")) {
+            base = base + "/";
+        }
+        return base + packageUrl.replaceFirst("^/+", "");
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.isBlank();
+    }
+
+    private static ResponseEntity<Map<String, Object>> error(
+            int status, String code, String message) {
+        return ResponseEntity.status(status)
+                .body(Map.of("error", Map.of("code", code, "message", message)));
+    }
+
+    /** 与桌面端 resolve 请求体一致;deviceId 仅随请求到达,不落库、不打日志。 */
+    public record ResolveRequest(String deviceId, String pluginId, String version) {
+    }
+}

+ 7 - 0
ai-server/src/main/resources/application.yaml

@@ -29,6 +29,13 @@ storage:
     # /files/** 由 LocalFileResourceConfig 映射到 root-path。
     base-url: "${STORAGE_LOCAL_BASE_URL:http://localhost:8980/js/a}"
 
+# 本机插件市场(桌面端 /plugin/** 接口,匿名可读)。
+# catalog.json 与 packages/*.piplug 放在 root-path 下;目录和包的访问地址
+# 固定为 http://127.0.0.1:8980/js/a/plugin/...,与桌面端内置的市场地址一致。
+plugin:
+  market:
+    root-path: "${PLUGIN_MARKET_ROOT:./data/plugin-market}"
+
 # 主 Agent 运行参数
 agent:
   # 单次提问的最大「推理→工具」循环轮数(专家未单独配置 max_iters 时生效)。