From 81f37d59376ee7d6ac2d597d8839ba2f051dbbe6 Mon Sep 17 00:00:00 2001 From: Sivan Date: Thu, 12 Nov 2026 18:50:49 +0800 Subject: [PATCH 1/2] Add reviewed plugin discovery and SHA-pinned market installs --- .github/workflows/ci.yml | 12 + cmd/deepzora/main.go | 2 + desktop/frontend/bench/settings-pages.mjs | 7 + .../src/components/CapabilitiesPanel.tsx | 49 ++- .../frontend/src/components/PluginMarket.tsx | 177 +++++++++++ .../generated/desktopContract.generated.json | 50 +++ .../generated/desktopContract.generated.ts | 7 +- desktop/frontend/src/lib/bridge.ts | 8 +- desktop/frontend/src/lib/types.ts | 3 + desktop/frontend/src/locales/en.ts | 10 + desktop/frontend/src/locales/zh.ts | 10 + desktop/host_command_owners.generated.json | 15 + desktop/main.go | 2 + desktop/plugin_packages_app.go | 41 ++- docs/PLUGIN_PACKAGES.md | 18 ++ docs/PLUGIN_PACKAGES.zh-CN.md | 18 ++ docs/plans/plugin-market-acceptance.zh-CN.md | 16 + docs/plans/plugin-market-delivery.md | 10 + docs/plans/plugin-marketplace.zh-CN.md | 107 +++++++ internal/cli/plugin.go | 110 ++++++- internal/installsource/catalog.go | 152 +++++++++ internal/installsource/catalog_transaction.go | 139 +++++++++ .../installsource/catalog_transaction_test.go | 54 ++++ internal/installsource/install_source.go | 13 + internal/installsource/plan.go | 3 + internal/installsource/plugin_package.go | 15 + internal/installsource/types.go | 3 +- internal/plugincatalog/catalog.go | 293 ++++++++++++++++++ internal/plugincatalog/catalog_test.go | 63 ++++ internal/pluginpkg/pluginpkg.go | 2 + scripts/plugin-market-e2e.py | 88 ++++++ 31 files changed, 1484 insertions(+), 13 deletions(-) create mode 100644 desktop/frontend/src/components/PluginMarket.tsx create mode 100644 docs/plans/plugin-market-acceptance.zh-CN.md create mode 100644 docs/plans/plugin-market-delivery.md create mode 100644 docs/plans/plugin-marketplace.zh-CN.md create mode 100644 internal/installsource/catalog.go create mode 100644 internal/installsource/catalog_transaction.go create mode 100644 internal/installsource/catalog_transaction_test.go create mode 100644 internal/plugincatalog/catalog.go create mode 100644 internal/plugincatalog/catalog_test.go create mode 100644 scripts/plugin-market-e2e.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b2e24b7e8..35d005259 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -159,6 +159,11 @@ jobs: - name: Build and test root module if: env.RUN_STEPS == 'true' run: go test -timeout=15m ./... + - name: Accept plugin market installs against a moving Git reference + if: env.RUN_STEPS == 'true' + run: | + go build -o "$RUNNER_TEMP/deepzora-market" ./cmd/deepzora + python3 scripts/plugin-market-e2e.py "$RUNNER_TEMP/deepzora-market" - if: always() && env.RUN_STEPS == 'true' uses: ./.github/actions/go-build-cache with: @@ -204,6 +209,13 @@ jobs: # The runner fails unless every discovered package reports pass or skip. - name: Build and test every root package run: node scripts/ci-windows-root.mjs "$RUNNER_TEMP/windows-root" + - name: Verify Windows plugin market installation and replacement + shell: pwsh + run: | + $market = Join-Path $env:RUNNER_TEMP 'deepzora-market.exe' + go build -o $market ./cmd/deepzora + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/plugin-market-e2e.py $market - name: Upload root package evidence if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/cmd/deepzora/main.go b/cmd/deepzora/main.go index 75911a706..bbbde5cfb 100644 --- a/cmd/deepzora/main.go +++ b/cmd/deepzora/main.go @@ -9,6 +9,7 @@ import ( "deepzora/internal/config" "deepzora/internal/crashreport" "deepzora/internal/plugin" + "deepzora/internal/plugincatalog" "deepzora/internal/skill/skillwatch" // Blank imports wire compile-time built-ins into their registries. @@ -38,6 +39,7 @@ var runCLI = func(args []string, buildVersion string) int { } func main() { + plugincatalog.HostVersion = version // Internal watcher-helper entry: the host-shared skill watch service // re-enters this executable so Windows directory watching never runs // in-process. Dispatch before any application initialization. diff --git a/desktop/frontend/bench/settings-pages.mjs b/desktop/frontend/bench/settings-pages.mjs index 449634525..8113c9350 100644 --- a/desktop/frontend/bench/settings-pages.mjs +++ b/desktop/frontend/bench/settings-pages.mjs @@ -207,6 +207,13 @@ try { await verify(page, "subagent-edit", true); await go("Plugins"); + await page.getByRole("button", { name: "Discover", exact: true }).click(); + await page.getByText("Review Checklist", {exact:true}).waitFor(); + await verify(page,"plugin-discover",true); + await page.locator("article").filter({hasText:"Review Checklist"}).getByRole("button",{name:/preview/i}).click(); + await page.locator(".cap-plugin-plan").waitFor(); + await page.locator(".cap-plugin-installer__actions button.btn--primary").click(); + await page.locator("#settings-plugin-install").waitFor({state:"hidden"}); await page.getByRole("button", { name: "Install plugin", exact: true }).click(); await page.locator(".cap-plugin-installer").waitFor(); await verify(page, "plugin-local", true); diff --git a/desktop/frontend/src/components/CapabilitiesPanel.tsx b/desktop/frontend/src/components/CapabilitiesPanel.tsx index bb471ee37..71ad0012a 100644 --- a/desktop/frontend/src/components/CapabilitiesPanel.tsx +++ b/desktop/frontend/src/components/CapabilitiesPanel.tsx @@ -1,4 +1,5 @@ import { ErrorMessage } from "./ErrorMessage"; +import { PluginMarket } from "./PluginMarket"; import { SettingsSubpageHeader, SettingsFeedback, useSettingsDraft, useSettingsExperience } from "./SettingsExperience"; import { SettingsOptions } from "./SettingsOptions"; import { SettingsSelect } from "./SettingsSelect"; @@ -1622,6 +1623,7 @@ type PluginRuntimePlan = { }; type PluginInstallPlanAction = { + changes?: string[]; action?: string; kind?: string; name?: string; @@ -1641,6 +1643,8 @@ type PluginInstallPlanAction = { }; type PluginInstallPlanView = { + planId?: string; + activationWarning?: string; raw: string; ok?: boolean; status?: string; @@ -1656,6 +1660,7 @@ type PluginInstallMode = "local" | "git"; // Settings. It mirrors the MCP/Skills density: install planning on top, package // rows below, and diagnostics/details only when a row is expanded. export function PluginsSettingsPage() { + const [discover, setDiscover] = useState(false); const t = useT(); const { requestLeave, announce } = useSettingsExperience(); const [installOpen, setInstallOpen] = useState(false); @@ -1717,6 +1722,20 @@ export function PluginsSettingsPage() { }; const sourceValue = (installMode === "local" ? localSource : gitSource).trim(); + const isMarket = /^(catalog|topic):/.test(sourceValue); + const chooseMarket = (spec: string, installed?: PluginView) => { + setDiscover(false); + setInstallMode("git"); + setGitSource(spec); + setName(installed?.name || ""); + setReplace(Boolean(installed)); + setPlan(null); + setInstallOpen(true); + void run(async () => { + const raw = await app.PlanPluginInstall(spec, { dryRun: true, replace: Boolean(installed), name: installed?.name }); + setPlan(parsePluginInstallPlan(raw)); + }, false); + }; const installOptions = (): PluginInstallOptions => ({ dryRun: false, link: installMode === "local" ? link : false, @@ -1743,7 +1762,7 @@ export function PluginsSettingsPage() { const install = () => { if (!sourceValue) return; void run(async () => { - const raw = await app.InstallPlugin(sourceValue, installOptions()); + const raw = await app.InstallPlugin(sourceValue, { ...installOptions(), planId: plan?.planId }); setPlan(parsePluginInstallPlan(raw)); setLocalSource(""); setGitSource(""); setName(""); setInstallOpen(false); announce("success"); @@ -1787,10 +1806,12 @@ export function PluginsSettingsPage() { {loadError && { setLoadError(null); void reload(); }}>} {notice && !err && {notice}}
-
{t("caps.installedPlugins")}{plugins && plugins.length > 0 &&
{summary}
}
+
+ {!discover && summary && {summary}}
+{discover && } -
+ ))}
@@ -2332,12 +2354,15 @@ function parsePluginInstallPlan(raw: string): PluginInstallPlanView { mappedCapabilities: (Array.isArray(item.mappedCapabilities) ? item.mappedCapabilities : []).filter((value): value is string => typeof value === "string"), skippedCapabilities: (Array.isArray(item.skippedCapabilities) ? item.skippedCapabilities : []) as PluginCompatibilityIssue[], runtime: parsePluginRuntimePlan(item.runtime), + changes: marketPlanChanges(item), agentCount: numericValue(item.agentCount), skillCount: numericValue(item.skillCount), commandCount: numericValue(item.commandCount), hookCount: numericValue(item.hookCount), toolCount: numericValue(item.toolCount), }]; }); return { raw, ok: typeof value.ok === "boolean" ? value.ok : undefined, + planId: stringValue(value.planId), + activationWarning: stringValue(value.activationWarning), status: stringValue(value.status), name: stringValue(value.name), actions, @@ -2349,6 +2374,17 @@ function parsePluginInstallPlan(raw: string): PluginInstallPlanView { } } +function marketPlanChanges(item:Record):string[] { + const c=item.catalog as {execution?:string[];previousExecution?:string[];requirements?:{namespace:string;kind:string;id:string}[];previous?:{version:string};previousCapabilities?:Record;capabilities?:Record}|undefined; + if(!c)return []; + const lines=(Array.isArray(item.riskReasons)?item.riskReasons:[]).filter((x):x is string=>typeof x==="string"); + for(const s of c.execution||[])lines.push((c.previous && !c.previousExecution?.includes(s)?"+ ":"")+s); + for(const s of c.previousExecution||[])if(!c.execution?.includes(s))lines.push("− "+s); + for(const r of c.requirements||[])lines.push("requires: "+[r.namespace,r.kind,r.id].join("/")); + if(c.previous){lines.unshift(c.previous.version+" → "+item.version); + for(const [k,v] of Object.entries(c.capabilities||{}))if(c.previousCapabilities?.[k]!==v)lines.push(k+": "+(c.previousCapabilities?.[k]??0)+" → "+v)} + return lines; +} function numericValue(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) ? value : undefined; } @@ -2382,6 +2418,7 @@ function pluginPlanActionLabel(action: PluginInstallPlanAction, t: ReturnType): string { + if(plan.activationWarning)return plan.activationWarning; if (plan.error) return plan.error; if (plan.status === "done" || plan.status === "applied" || plan.status === "complete") return t("caps.pluginPlanInstalled"); return plan.status ? t("caps.pluginPlanStatus", { status: plan.status }) : t("caps.pluginPlanComplete"); diff --git a/desktop/frontend/src/components/PluginMarket.tsx b/desktop/frontend/src/components/PluginMarket.tsx new file mode 100644 index 000000000..34b7f0789 --- /dev/null +++ b/desktop/frontend/src/components/PluginMarket.tsx @@ -0,0 +1,177 @@ +import { useEffect, useState } from "react"; +import { app, openExternal } from "../lib/bridge"; +import { useI18n } from "../lib/i18n"; +import type { PluginView } from "../lib/types"; +import { SettingsFeedback } from "./SettingsExperience"; + +type Entry = { + id: string; + spec: string; + name: string; + version: string; + commit: string; + repo: string; + path?: string; + summary: Record; + channel: string; + upstream?: { spec: string; version: string }; + capabilities?: string[]; +}; +function sameSource(p: PluginView, e: Entry) { + const match = + /^(?:https?:\/\/|git:)github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:\/tree\/[^/]+(?:\/(.+))?)?\/?$/i.exec( + p.source || "", + ); + return ( + !!match && + match[1].toLowerCase() === e.repo.toLowerCase() && + (match[2] || "") === (e.path || "") + ); +} +export function PluginMarket({ + installed, + choose, +}: { + installed: PluginView[]; + choose: (spec: string, p?: PluginView) => void; +}) { + const { t, locale } = useI18n(); + const [topics, setTopics] = useState(false); + const [q, setQ] = useState(""); + const [retry, setRetry] = useState(0); + const [data, setData] = useState<{ + entries: Entry[]; + warning?: string; + } | null>(null); + const [error, setError] = useState(""); + useEffect(() => { + let live = true; + setData(null); + setError(""); + app + .SearchPluginCatalog("", topics) + .then((raw) => { + if (live) setData(JSON.parse(raw)); + }) + .catch((e) => { + if (live) setError(String(e)); + }); + return () => { + live = false; + }; + }, [topics, retry]); + const rows = (data?.entries || []).filter((e) => + [ + e.id, + e.name, + e.repo, + ...Object.values(e.summary), + ...(e.capabilities || []), + ] + .join(" ") + .toLowerCase() + .includes(q.trim().toLowerCase()), + ); + return ( +
+
+ setQ(ev.target.value)} + /> + + +
+ {error ? ( + setRetry((i) => i + 1)}> + {error} + + ) : !data ? ( + + ) : null} + {data?.warning &&

{data.warning}

} + {data && !rows.length &&

{t("market.empty")}

} + {rows.map((e) => { + const p = installed.find((x) => sameSource(x, e)); + const current = p?.commit === e.commit; + return ( +
+
+ {e.name} + + {t( + e.channel === "community" + ? "market.reviewed" + : e.channel === "unreviewed" + ? "market.unreviewed" + : "market.custom", + )} + +
+

{e.summary[locale] || e.summary.en}

+ +
+ {e.repo} · v{e.version} · {e.commit.slice(0, 10)} + {e.capabilities?.length ? " · " + e.capabilities.join(", ") : ""} +
+ + {e.upstream && ( + + )} +
+ ); + })} +
+ ); +} diff --git a/desktop/frontend/src/generated/desktopContract.generated.json b/desktop/frontend/src/generated/desktopContract.generated.json index 882b5535c..0dfd1016a 100644 --- a/desktop/frontend/src/generated/desktopContract.generated.json +++ b/desktop/frontend/src/generated/desktopContract.generated.json @@ -11233,6 +11233,35 @@ "desktop/history_read_snapshots.go" ] }, + { + "cancellation": "before-dispatch", + "domain": "desktop/plugin_packages_app.go", + "name": "SearchPluginCatalog", + "owner": "App.SearchPluginCatalog", + "params": [ + { + "kind": "string" + }, + { + "kind": "boolean" + } + ], + "result": { + "kind": "string" + }, + "returnsError": true, + "scope": { + "inputs": [ + "query", + "topics" + ], + "kind": "owner-inputs", + "resolver": "App.SearchPluginCatalog" + }, + "sources": [ + "desktop/plugin_packages_app.go" + ] + }, { "cancellation": "before-dispatch", "domain": "desktop/session_history_service.go", @@ -26790,6 +26819,13 @@ }, "main.PluginInstallOptions": { "fields": [ + { + "name": "planId", + "optional": true, + "type": { + "kind": "string" + } + }, { "name": "dryRun", "optional": true, @@ -26912,6 +26948,20 @@ }, "main.PluginView": { "fields": [ + { + "name": "catalogId", + "optional": true, + "type": { + "kind": "string" + } + }, + { + "name": "commit", + "optional": true, + "type": { + "kind": "string" + } + }, { "name": "name", "type": { diff --git a/desktop/frontend/src/generated/desktopContract.generated.ts b/desktop/frontend/src/generated/desktopContract.generated.ts index 4f7cb26ff..0686da6ff 100644 --- a/desktop/frontend/src/generated/desktopContract.generated.ts +++ b/desktop/frontend/src/generated/desktopContract.generated.ts @@ -3,7 +3,7 @@ export const DESKTOP_PROTOCOL_VERSION = 11; -export const DESKTOP_CONTRACT_DIGEST = "sha256:7eccf12fe33ad5456f2c9f55f1867291a2c46935d4a484273c806df83b3a3e68"; +export const DESKTOP_CONTRACT_DIGEST = "sha256:741361958d4562006951b91e64b8b87117359cedd028a3155d073f0076a672b7"; export const DESKTOP_COMMANDS = [ "AIRenameSessionTarget", @@ -428,6 +428,7 @@ export const DESKTOP_COMMANDS = [ "SearchFileRefsForTab", "SearchFileRefsForTarget", "SearchHistoryContent", + "SearchPluginCatalog", "SearchSessionHistoryForTab", "SearchSessionHistoryForTarget", "SearchSessionHistoryRead", @@ -2792,6 +2793,7 @@ export interface PluginHookView { } export interface PluginInstallOptions { + planId?: string; dryRun?: boolean; link?: boolean; replace?: boolean; @@ -2817,6 +2819,8 @@ export interface PluginSkillView { } export interface PluginView { + catalogId?: string; + commit?: string; name: string; version?: string; description?: string; @@ -5653,6 +5657,7 @@ export interface GeneratedDesktopCommands { SearchFileRefsForTab(arg0: string, arg1: string): Promise; SearchFileRefsForTarget(arg0: ComposerTarget, arg1: string): Promise; SearchHistoryContent(arg0: HistorySearchRequest): Promise; + SearchPluginCatalog(arg0: string, arg1: boolean): Promise; SearchSessionHistoryForTab(arg0: string, arg1: string, arg2: string, arg3: number): Promise; SearchSessionHistoryForTarget(arg0: SessionSelector, arg1: string, arg2: string, arg3: number): Promise; SearchSessionHistoryRead(arg0: string, arg1: string, arg2: string, arg3: number): Promise; diff --git a/desktop/frontend/src/lib/bridge.ts b/desktop/frontend/src/lib/bridge.ts index 3a538600f..f6e49cdb1 100644 --- a/desktop/frontend/src/lib/bridge.ts +++ b/desktop/frontend/src/lib/bridge.ts @@ -388,6 +388,7 @@ export interface AppBindings extends AttachmentBindings, SessionExportBindings, RetryAuthenticationForTab(tabId: string): Promise>; RuntimeDoctor(): Promise; Plugins(): Promise; + SearchPluginCatalog(query: string, topics: boolean): Promise; PlanPluginInstall(source: string, options: PluginInstallOptions): Promise; InstallPlugin(source: string, options: PluginInstallOptions): Promise; RemovePlugin(name: string): Promise; @@ -3250,16 +3251,21 @@ function makeMockApp(): MockAppBindings { async Plugins() { return capPlugins.map((p) => ({ ...p })); }, + async SearchPluginCatalog() { + return JSON.stringify({ entries: [{ id:"community/review-checklist",spec:"catalog:community/review-checklist@1.0.0",name:"Review Checklist",repo:"SivanCola/deepzora-plugins",path:"packages/review-checklist",commit:"762d58f80167bdc0059eacb230afb88c32e42df3",version:"1.0.0",channel:"community",summary:{en:"Review changes and test coverage.",zh:"审阅改动与测试覆盖。"},capabilities:["Skills"] }] }); + }, async PlanPluginInstall(source: string, options: PluginInstallOptions) { const name = options.name || source.split("/").filter(Boolean).pop()?.replace(/\.git$/, "") || "plugin"; return JSON.stringify({ ok: true, status: "planned", - kind: "plugin", +kind: "plugin", + planId: "mock-market-plan", actions: [{ kind: "plugin", action: "install_plugin_package", name, source, status: "planned" }], }); }, async InstallPlugin(source: string, options: PluginInstallOptions) { + if (/^(catalog|topic):/.test(source) && options.planId !== "mock-market-plan") throw new Error("Missing catalog approval"); const name = options.name || source.split("/").filter(Boolean).pop()?.replace(/\.git$/, "") || "plugin"; const existing = capPlugins.findIndex((p) => p.name === name); const view: PluginView = { diff --git a/desktop/frontend/src/lib/types.ts b/desktop/frontend/src/lib/types.ts index cd2744444..9f2132013 100644 --- a/desktop/frontend/src/lib/types.ts +++ b/desktop/frontend/src/lib/types.ts @@ -1144,6 +1144,8 @@ export interface SubagentProfileInput { scope?: "project" | "global"; } export interface PluginView { + catalogId?: string; + commit?: string; name: string; version?: string; description?: string; @@ -1213,6 +1215,7 @@ export interface PluginMCPServerView { autoStart?: boolean; } export interface PluginInstallOptions { + planId?: string; dryRun?: boolean; link?: boolean; replace?: boolean; diff --git a/desktop/frontend/src/locales/en.ts b/desktop/frontend/src/locales/en.ts index de817e6e3..2e81a640e 100644 --- a/desktop/frontend/src/locales/en.ts +++ b/desktop/frontend/src/locales/en.ts @@ -1008,6 +1008,16 @@ export const en = { "caps.pluginChooseLocalFolder": "Choose plugin folder", "caps.pluginLocalFolder": "Local plugin folder", "caps.pluginNoLocalFolder": "No folder selected", + "market.discover": "Discover", + "market.submit": "Submit a plugin", + "market.source": "View source", + "market.search": "Search plugins", + "market.include": "Include unreviewed GitHub plugins", + "market.empty": "No matching plugins", + "market.reviewed": "Community reviewed", + "market.unreviewed": "Unreviewed", + "market.custom": "Custom catalog", + "market.reviewUpdate": "Preview update", "caps.pluginInstallName": "Install name (optional)", "caps.pluginInstallNamePlaceholder": "install name (optional)", "caps.pluginLink": "Developer mode: link source folder", diff --git a/desktop/frontend/src/locales/zh.ts b/desktop/frontend/src/locales/zh.ts index 521f0e607..ac09fa7fb 100644 --- a/desktop/frontend/src/locales/zh.ts +++ b/desktop/frontend/src/locales/zh.ts @@ -1009,6 +1009,16 @@ export const zh: Record = { "caps.pluginChooseLocalFolder": "选择插件目录", "caps.pluginLocalFolder": "本地插件目录", "caps.pluginNoLocalFolder": "尚未选择目录", + "market.discover": "发现", + "market.submit": "提交插件", + "market.source": "查看源码", + "market.search": "搜索插件", + "market.include": "包含 GitHub 未审核插件", + "market.empty": "没有匹配的插件", + "market.reviewed": "社区已审核", + "market.unreviewed": "未审核", + "market.custom": "自定义目录", + "market.reviewUpdate": "预览更新", "caps.pluginInstallName": "安装名称(可选)", "caps.pluginInstallNamePlaceholder": "安装名称(可选)", "caps.pluginLink": "开发模式:链接源目录", diff --git a/desktop/host_command_owners.generated.json b/desktop/host_command_owners.generated.json index d305fba0b..38e9cf93c 100644 --- a/desktop/host_command_owners.generated.json +++ b/desktop/host_command_owners.generated.json @@ -6020,6 +6020,21 @@ ] } }, + "SearchPluginCatalog": { + "domain": "desktop/plugin_packages_app.go", + "owner": "App.SearchPluginCatalog", + "sources": [ + "desktop/plugin_packages_app.go" + ], + "scope": { + "kind": "owner-inputs", + "resolver": "App.SearchPluginCatalog", + "inputs": [ + "query", + "topics" + ] + } + }, "SearchSessionHistoryForTab": { "domain": "desktop/session_history_service.go", "owner": "App.SearchSessionHistoryForTab", diff --git a/desktop/main.go b/desktop/main.go index 6acdf8244..869dbb5bd 100644 --- a/desktop/main.go +++ b/desktop/main.go @@ -13,6 +13,7 @@ import ( "os" "strings" + "deepzora/internal/plugincatalog" "deepzora/internal/skill/skillwatch" // Blank imports wire compile-time built-ins into their registries, exactly as @@ -47,6 +48,7 @@ func macSelfUpdateAllowed() bool { } func main() { + plugincatalog.HostVersion = version // Contract generation is a build-time operation. Dispatch it before crash // capture so packaging cannot create files in the operator's Deepzora home. if dir, ok := emitContractDir(os.Args[1:]); ok { diff --git a/desktop/plugin_packages_app.go b/desktop/plugin_packages_app.go index 88e55c6d4..26511ae0c 100644 --- a/desktop/plugin_packages_app.go +++ b/desktop/plugin_packages_app.go @@ -11,10 +11,13 @@ import ( "deepzora/internal/config" "deepzora/internal/hook" "deepzora/internal/installsource" + "deepzora/internal/plugincatalog" "deepzora/internal/pluginpkg" ) type PluginView struct { + CatalogID string `json:"catalogId,omitempty"` + Commit string `json:"commit,omitempty"` Name string `json:"name"` Version string `json:"version,omitempty"` Description string `json:"description,omitempty"` @@ -40,6 +43,7 @@ type PluginView struct { } type PluginInstallOptions struct { + PlanID string `json:"planId,omitempty"` DryRun bool `json:"dryRun,omitempty"` Link bool `json:"link,omitempty"` Replace bool `json:"replace,omitempty"` @@ -91,6 +95,15 @@ type PluginMCPServerView struct { AutoStart bool `json:"autoStart,omitempty"` } +func (a *App) SearchPluginCatalog(query string, topics bool) (string, error) { + result, err := plugincatalog.Search(context.Background(), config.DeepzoraHomeDir(), query, topics) + if err != nil { + return "", err + } + b, err := json.Marshal(result) + return string(b), err +} + func (a *App) Plugins() []PluginView { st, err := pluginpkg.LoadState(config.DeepzoraHomeDir()) if err != nil { @@ -106,6 +119,7 @@ func (a *App) Plugins() []PluginView { out := make([]PluginView, 0, len(st.Plugins)) for _, p := range st.Plugins { view := PluginView{ + CatalogID: p.CatalogID, Commit: p.Commit, Name: p.Name, Version: p.Version, Description: p.Description, @@ -213,13 +227,30 @@ func (a *App) InstallPlugin(source string, opts PluginInstallOptions) (string, e if err != nil { return "", err } + var result struct { + OK bool + Error string + Next string + } + if err = json.Unmarshal([]byte(out), &result); err != nil { + return "", err + } + if !result.OK { + return "", fmt.Errorf("plugin installation failed: %s %s", result.Error, result.Next) + } a.bumpExtensionGeneration() a.invalidateSkillRootsCache() if rebuildErr := a.rebuild(); rebuildErr != nil { - if _, ok := a.deferredRebuildWarning("plugins", rebuildErr); ok { - return out, nil + if warning, ok := a.deferredRebuildWarning("plugins", rebuildErr); ok { + var outcome map[string]any + if err := json.Unmarshal([]byte(out), &outcome); err != nil { + return out, err + } + outcome["activationWarning"] = warning + raw, err := json.Marshal(outcome) + return string(raw), err } - return out, rebuildErr + return out, fmt.Errorf("plugin installed; activation failed (inspect plugin diagnostics): %w", rebuildErr) } return out, nil } @@ -289,6 +320,9 @@ func (a *App) UpdatePlugin(name string) (string, error) { name = strings.TrimSpace(name) for _, p := range a.Plugins() { if p.Name == name { + if p.CatalogID != "" { + return "", fmt.Errorf("preview the catalog update for %s before installing", p.CatalogID) + } if strings.TrimSpace(p.Source) == "" { return "", fmt.Errorf("plugin %q has no recorded source", name) } @@ -343,6 +377,7 @@ func (a *App) runPluginInstallSource(source string, opts PluginInstallOptions, a } body := map[string]any{ "source": strings.TrimSpace(source), + "planId": opts.PlanID, "kind": "plugin", "mode": mode, "replace": opts.Replace, diff --git a/docs/PLUGIN_PACKAGES.md b/docs/PLUGIN_PACKAGES.md index c4ce720f3..95d8047de 100644 --- a/docs/PLUGIN_PACKAGES.md +++ b/docs/PLUGIN_PACKAGES.md @@ -1,5 +1,23 @@ # Deepzora Plugin Packages +## Discover community plugins + +Open **Settings → Plugins → Discover**. Search the reviewed catalog or include independent GitHub repositories tagged `deepzora-plugin`. The source link opens the exact revision. Submit a package or release via the [community repository](https://github.com/SivanCola/deepzora-plugins). + +```sh +deepzora plugin search review --all +deepzora plugin info catalog:community/review-checklist +deepzora plugin install catalog:community/review-checklist --dry-run +deepzora plugin install catalog:community/review-checklist --yes --plan-id +deepzora plugin updates +deepzora plugin update review-checklist --dry-run +deepzora plugin update review-checklist --yes --plan-id +``` + +A listing becomes installable after its review and publication. Inspect the plan, especially hooks, MCP and full-trust runtimes. Copy the plan ID for the same home, source, version, name and flags. A moved tag cannot change the installed tree. A withdrawn release, mismatched plan or different-source name collision fails closed. Use `--name` to install under another local name. Updates are explicit and preserve disabled state. After interruption, `deepzora plugin recover` reconciles staged files with the installed record; it cannot undo plugin side effects. + +Search reuses recent catalog data and can fall back to its disk cache. Preview and apply read the current index. For testing or a private catalog, `DEEPZORA_PLUGIN_CATALOG` and `DEEPZORA_PLUGIN_TAGGED` accept an HTTPS URL or absolute JSON filename. Alternate catalogs are labelled custom, never community reviewed. + Deepzora plugin packages bundle skills, hooks, MCP servers, prompts, themes, and code extensions behind one installable unit. diff --git a/docs/PLUGIN_PACKAGES.zh-CN.md b/docs/PLUGIN_PACKAGES.zh-CN.md index 86168ea78..8a4fe8d93 100644 --- a/docs/PLUGIN_PACKAGES.zh-CN.md +++ b/docs/PLUGIN_PACKAGES.zh-CN.md @@ -1,5 +1,23 @@ # Deepzora 插件包 +## 发现和安装社区插件 + +打开 **设置 → 插件 → 发现**。默认展示社区审核目录,也可以勾选带 `deepzora-plugin` topic 的第三方 GitHub 插件。「查看源码」打开准确提交,「提交插件」进入[社区仓库](https://github.com/SivanCola/deepzora-plugins)的投稿流程。插件 PR 审核、合并并发布后才会进入默认目录。 + +```sh +deepzora plugin search review --all +deepzora plugin info catalog:community/review-checklist +deepzora plugin install catalog:community/review-checklist --dry-run +deepzora plugin install catalog:community/review-checklist --yes --plan-id <预览返回的ID> +deepzora plugin updates +deepzora plugin update review-checklist --dry-run +deepzora plugin update review-checklist --yes --plan-id <更新预览返回的ID> +``` + +预览会指出真实能力,特别是 hook、MCP 和完整信任的 runtime。确认时使用相同来源、版本、安装名和参数;tag 移动不影响已审核的提交。版本撤回、确认 ID 不一致或不同来源占用同名目录时拒绝写入,可用 `--name` 选择其他名称。升级为显式操作,保留禁用状态。进程中断后可执行 `deepzora plugin recover` 核对安装登记并恢复目录;此操作不会撤销插件对外部系统的影响。 + +搜索可回退到磁盘缓存;预览和确认会重新读取索引。测试及私有部署可用 `DEEPZORA_PLUGIN_CATALOG`、`DEEPZORA_PLUGIN_TAGGED` 分别指定 HTTPS 地址或 JSON 文件绝对路径。自定义目录不会获得社区审核标记。 + Deepzora 插件包把 skills、hooks、MCP servers、prompts、主题和代码型扩展组织成一个可安装单元。 ## CLI 模式 diff --git a/docs/plans/plugin-market-acceptance.zh-CN.md b/docs/plans/plugin-market-acceptance.zh-CN.md new file mode 100644 index 000000000..14aceae02 --- /dev/null +++ b/docs/plans/plugin-market-acceptance.zh-CN.md @@ -0,0 +1,16 @@ +# 插件市场交付与验收(2026-11-12) + +**交付范围。** [社区仓库](https://github.com/SivanCola/deepzora-plugins) 管理投稿、CI、版本保留及发布。Deepzora 负责解析、安装、状态恢复、CLI 和桌面设置。面向作者的入口是元数据 PR;社区托管的包也可把源码放在同一 PR。不要把投稿 CI 通过解释为已经审核。 + +| 设计步骤 | 验收证据 | +|---|---| +| 真实投稿 | [Review Checklist PR #1](https://github.com/SivanCola/deepzora-plugins/pull/1) 提交 v2 资源包。配置 main 分支要求 validate 和一份批准,独立审核待完成。 | +| 实际分发 | [初始 dist 发布](https://github.com/SivanCola/deepzora-plugins/actions/runs/43201978028) 和[独立 topic 索引任务](https://github.com/SivanCola/deepzora-plugins/actions/runs/43203590124) 成功;正式目录为空符合当前发布状态。 | +| 候选包安装 | 下载[投稿 CI](https://github.com/SivanCola/deepzora-plugins/actions/runs/43202144947) 的 catalog artifact,作为自定义目录输入真实 CLI。搜索、预览、回传 planId、从 GitHub 按提交获取并安装、doctor 成功。在临时 Deepzora home 的安装记录中读到 `762d58f80167bdc0059eacb230afb88c32e42df3`。这不是绕过审核的线上社区安装。 | +| 可重复端到端验收 | 构建 CLI 后执行 `python3 scripts/plugin-market-e2e.py /absolute/path/to/deepzora`。临时 Git 上游、两代提交、移动 tag、错误 planId、撤回、禁用升级、不同来源同名、Claude 兼容包均有断言;脚本不会写真实用户配置。CI 已接入 Linux、macOS 和 Windows,远端状态应以对应 PR 检查为准。 | +| 中断恢复 | Go 测试模拟目录换好但状态尚未提交、状态已提交两个崩溃边界,验证恢复结果及二次恢复的幂等性。 | +| 桌面 | Go 后端插件测试、前端构建、设置交互测试及 Playwright 中英文设置页矩阵。浏览器使用测试桥,验证发现 → 预览 → 安装时计划 ID 的传递;真实下载由上面的 CLI 验收覆盖。 | + +**对原设计的落地调整。** 生产索引使用扁平的 `releases[]`,一个元素就是一个可独立撤回的版本;窗口按 ID 与来源聚合,不要求索引中的嵌套层级与 UI 一致。社区使用 dist 分支发布静态索引,安装包内容从固定 Git SHA 获取。未引入 npm、Bun、无提示自动升级或单独的二进制镜像。可选最低版本与平台属于发布元数据,真实可运行性仍由安装计划、doctor 和宿主激活结果判断。 + +**上线顺序。** 合并通过审核的插件投稿后,publish 工作流会把第一条已审核记录写入 dist;合并并发布 Deepzora 客户端后,现有用户才会看到新入口。两个发布独立,均无需更改已提交的插件源码。 diff --git a/docs/plans/plugin-market-delivery.md b/docs/plans/plugin-market-delivery.md new file mode 100644 index 000000000..0d3f0a090 --- /dev/null +++ b/docs/plans/plugin-market-delivery.md @@ -0,0 +1,10 @@ +# Community plugin market delivery plan + +1. Define one immutable release per catalog ID and semantic version. The review input identifies a GitHub repo, package subdirectory, manifest identity and a full SHA; the index is server-generated. Separate reviewed releases from topic candidates. Withdraw a release without recycling its version. +2. Bootstrap the independent community repository with contribution instructions, CODEOWNERS, read-only PR validation, a protected main branch and a dist branch. Build the review report from the actual pinned source without running the plugin. Publish only from main. Seed an intentionally resource-only plugin through a real PR; leave the human review visible. +3. Implement one Go resolver for search, provenance, stable version ordering and withdrawal. Only browse or install on user request. Cache the last good catalog for offline browsing; revalidate before writes. Keep custom catalogs visibly separate. +4. Feed a direct repo/tree/SHA/path snapshot to the existing install planner. Bind the preview, installed target, release identity and actual source to confirmation. Reject different-source collisions and preserve disabled state. Install and update share the same preview. +5. Expose search/info/updates and explicit preview/apply in CLI. In Desktop offer Discover, Installed and manual source installation, show author/channel, version, capability changes and the actual plan. Regenerate the host contract from Go. +6. Generate the unreviewed topic index on a schedule. Merge by canonical repository and package path, never display name. Preserve the reviewed default when upstream moves. +7. Exercise the full pipeline with temporary Git repos, isolated Deepzora home and the actual CLI; move a tag between preview/apply, withdraw a version, change the approval ID and try a conflicting source. Validate desktop contracts and UI interactions separately. Report local acceptance, remote PR checks and maintainer approval as distinct results. + diff --git a/docs/plans/plugin-marketplace.zh-CN.md b/docs/plans/plugin-marketplace.zh-CN.md new file mode 100644 index 000000000..5f84df744 --- /dev/null +++ b/docs/plans/plugin-marketplace.zh-CN.md @@ -0,0 +1,107 @@ +# Deepzora 插件提交、发现与在线安装方案 + +状态:原始设计与取舍,以下示例为设计契约,不是已发布版本的用户手册。实现基于 `943bdd50a`;实际命令见[插件包文档](../PLUGIN_PACKAGES.zh-CN.md),交付差异和实测证据见[验收记录](plugin-market-acceptance.zh-CN.md)。 + +## 决策 + +第一版建立一个由 GitHub PR 维护的**版本目录**。作者继续在自己的仓库发布,社区审核一个确定的 Git 提交。桌面端和 CLI 使用同一个 Go 客户端查目录,选中版本后仍交给原有安装器。作者自己发布即可通过 URL 安装;审核只决定哪个版本进入社区推荐。第二阶段再用 GitHub topic 做未审核发现。首版不要求 npm 包、Bun、插件托管服务或作者登录 Deepzora。 + +## 从现有代码出发 + +| 现有能力 | 设计如何使用 | +|---|---| +| [pluginpkg](../../internal/pluginpkg/pluginpkg.go) 解析原生、Codex、Claude 清单;[原生 v2](../../internal/pluginpkg/manifest_v2.go) 声明资源、runtime 和能力契约 | 继续以真实包为准。索引提供摘要,不能给包增加能力。兼容包显示实际映射及跳过项。 | +| [installsource](../../internal/installsource/plugin_package.go) 支持本地及 GitHub 仓库/子目录,并能解释部分 Claude marketplace;GitHub 计划检查源码树、记录 commit;复制安装先暂存、检查能力,再替换目录 | 目录条目指向一个具体包子目录,只产生一个安装动作。保留原有按 URL、本地路径、开发链接和 marketplace 导入入口。 | +| [安装计划](../../internal/installsource/install_source.go) 支持 planId,Hook、MCP、runtime 在计划中有不同风险说明 | 扩展计划以绑定目录发布身份;在线确认必须回传计划 ID。 | +| [桌面后端](../../desktop/plugin_packages_app.go) 已有预览、安装、诊断、启停和更新;[插件设置页](../../desktop/frontend/src/components/CapabilitiesPanel.tsx) 已经展示安装计划 | 在现有设置页增加“发现”。现有安装选项未透传 planId;现有 UpdatePlugin 会按旧 source 直接 replace。社区更新需改为预览新发布再确认。 | +| [CLI](../../internal/cli/plugin.go) 已有 install/list/show/doctor 等;全局状态在 Deepzora home 的 plugin-packages.json,安装目录以本地 name 命名 | 不改变旧命令语义;给安装记录添加可选来源字段,旧记录仍可读。 | +| [MCP Registry 客户端](../../internal/mcpregistry/registry.go) 只在用户浏览/安装时访问网络,支持缓存回退 | 沿用这个产品约定;插件市场不进入会话启动、模型请求或工具发现路径。 | + +## 一、提交和发布 + +1. **作者准备包。** 提供仓库、许可证、README、版本、包所在子目录。用现有 `deepzora plugin install ./path --dry-run` 本地检查。在提交流程中首选原生 v2,Codex/Claude 包有可映射能力也可收录。runtime 若依赖外部命令,README 列出平台和前置条件;首版不替作者执行构建或依赖安装脚本。 +2. **作者向独立目录仓库提元数据 PR。** 维护者可先创建如 `SivanCola/deepzora-plugins` 的仓库(拟名)。一条发布提交稳定 ID、仓库、路径、完整 commit、版本、名称和中英文简介。Git tag 便于阅读,不作安装依据。仅修改插件仓库的 main 或 tag,不改变已收录版本。 +3. **CI 生成差异供审核。** 受信任的校验器只读取指定提交,用与客户端同源的 Go 解析器生成清单类型、能力、runtime 命令、兼容性警告;校验版本、路径、重复 ID / 来源、重复版本换 SHA、许可证及平台声明。PR 中展示与上一发布相比新增的 hook 命令、MCP 启动目标、runtime、provides/requires 等。解析工作不启动插件、不加载 hook、不带发布凭据。对需要运行验证的包,另用隔离测试作业。 +4. **维护者审核该版本。** 核对仓库归属与发布者、能力及其实际行为;有执行能力时检查相对上次审核的代码变化,不能只看能力数量。目录来源变更或维护权移交单独审核。审核人和 PR 记录由发布流程关联,不接受作者自填“已审核”。 +5. **合并后发布静态索引。** 受保护分支的工作流重新校验,通过后发布版本化快照和稳定入口 `index-v1.json`。失败继续服务上一次成功快照。审核对象是“ID + 版本 + commit”,同一版本不允许重写;修复必须发新版本。撤回用 yanked 标记并附原因,停止推荐和新装,已安装用户收到通知,自行选择停用或卸载。 + +**索引最小契约(以下是示例数据):** + +```json +{ + "schemaVersion": 1, + "revision": 42, + "plugins": [{ + "id": "acme/review-kit", + "name": "Review Kit", + "summary": {"zh": "代码审阅命令和技能", "en": "Review commands and skills"}, + "source": {"repo": "acme/deepzora-tools", "path": "plugins/review-kit"}, + "releases": [{ + "version": "1.2.0", + "commit": "0123456789abcdef0123456789abcdef01234567", + "manifestName": "review-kit", + "manifestKind": "deepzora", + "minDeepzora": "0.0.5", + "platforms": ["darwin", "linux", "windows"], + "reviewPR": 123, + "yanked": false + }] + }] +} +``` + +平台、最低宿主版本与能力摘要属于每个版本;平台声明与已测试平台分开展示。只在受信任的内置目录来源上赋予“社区已审核”标记。自定义 URL、第三方索引里的同名字段不能生成该标记。首版以 HTTPS 和受保护分支为分发信任根;将来若提供独立镜像,再增加签名快照和防降级验证。 + +## 二、发现、去重和已安装匹配 + +桌面“设置 → 插件”保留“已安装”“从 URL / 路径安装”,增加“发现”。默认展示社区审核版本,可按语言搜索名称、简介、作者、能力,按原生/兼容、可用于本机筛选。卡片展示来源、版本、主要能力和安装状态;详情链接到 README、准确的代码提交和审核 PR。目录下载失败时显示最近成功缓存及时间;没有缓存则提示重试,同时保留手动安装入口。建议 6 小时缓存、ETag 条件请求、手动刷新、限制响应大小。过期缓存可浏览,执行目录安装/更新前需在有效期内确认发布未撤回。 + +三个身份分别处理: + +| 身份 | 用途 | +|---|---| +| 稳定目录 ID,例如 acme/review-kit | 搜索、订阅版本、关联历史;displayName 可改。 | +| 来源身份:GitHub 仓库标识 + 规范化子目录 | 合并社区目录与 topic 命中,也用于识别以前通过 URL 手动安装的包。仓库部分规范化,子目录保留大小写。 | +| 本地安装名,例如 review-kit | 沿用 plugins/ 和现有命令;用户已有别名继续保留。 | + +同一来源和子目录只显示一张卡。社区审核到 1.2.0,上游另发了 1.3.0,主按钮仍安装 1.2.0;若展示新版,则单列“上游版本,未审核”。不同仓库即使同名也分别显示发布者。社区把源码复制到另一仓库时,只有经过审核的显式来源映射才可归为同一项目,原安装不自动切换渠道。相同本地名已被其他来源占用时展示冲突,允许选合法别名或取消,不隐式 replace。 + +旧状态优先按已有 source、子目录、commit 匹配;来源匹配但提交不匹配时标注“已从此仓库安装,非审核版本”。缺少可验证来源或使用本地 link 的安装保持“本地管理”,不能仅凭名称认领。 + +第二阶段:后台工作流定时扫描公开、未归档仓库的 `deepzora-plugin` topic;先支持仓库根目录的受支持清单,monorepo 通过显式提交通道指定子目录。生成与社区目录分开的候选索引,记录扫描 commit、时间;静态解析通过后才进入“第三方 · 未审核”。普通客户端不各自扫描 GitHub。第三方默认不进入社区推荐,不自动覆盖或更新。 + +## 三、在线安装和升级 + +1. **选择发布。** 新增 Go 包 `internal/plugincatalog`,集中实现搜索、缓存、去重和版本解析。Desktop/CLI 发送目录 ID、版本和本地目标,Go 从可信目录解析坐标;前端不能提交一组自称已审核的 URL 和 SHA。首版社区版本采用明确的 SemVer 规则,默认选最新兼容、非预发布、未撤回的版本。 +2. **固定输入。** 给 installsource 增加明确的 repo/path/expectedCommit 输入,在解析 manifest **之前**获取并检出该 SHA,再校验包路径、名称和版本。不能只把 SHA 拼到 GitHub tree URL:当前准备流程对 tree ref 使用浅克隆的 `--branch`,并非通用的任意 SHA 安装接口。依赖无法满足时说明原因,不悄悄安装依赖插件。 +3. **预览真实变更。** 从检出的包生成 installsource 计划:目标目录、实际版本、兼容跳过项、将启用的资源、可执行命令和完整信任提示。显示运行时前置依赖;区分“包可复制”和“本机可运行”。升级另显示旧→新 commit 及能力/命令差异。即使社区审核通过,也保留现有风险分级。 +4. **确认同一计划。** Desktop 预览返回 planId,确认 API 必填;CLI 新增可回传的 `--plan-id`。目录 ID、版本、源路径、commit、目标别名、替换策略、旧安装身份纳入计划指纹;托管端在应用前复核计划、撤回状态及当前目标。目标或计划改变则返回“请重新预览”,不下载另一个版本作为替代。 +5. **安装并登记。** 在线安装只走 copy;沿用暂存复制和复制后校验。插件状态增补可选 catalogId、channel、reviewedVersion 等字段,实际 source 和 commit 仍保留。升级保留本地名称与 enabled 状态(现有包安装路径会写 Enabled=true,需显式修正)。并发确认须对目标串行化,并在锁内复核前置状态。 +6. **分别报告落盘和生效。** 沿用桌面扩展 generation / rebuild 及延迟生效路径。用户应能看到“已安装并生效”“已安装,等待会话允许重载”或“已安装,激活失败,查看诊断”。不要把 rebuild 失败显示成下载失败。目录替换与状态写入需一起恢复:现有复制函数在换目录成功后即删除备份,需延长备份到状态提交完成,保留恢复记录以处理进程中断。回到上一版只还原包和登记状态,不声称还原插件已产生的外部效果。 + +**首版更新策略:** 只提示,不静默执行。社区渠道比较同 ID 的审核发布;GitHub 手动安装、兼容 marketplace 和本地 link 仍归原来源管理。市场托管包从“已安装”点击更新也必须走目录固定版本计划;不可通过旧 UpdatePlugin 自动追踪上游 HEAD。用户可以固定版本或跳过本次更新。 + +**建议的 CLI(现有 URL 安装语法继续有效):** + +```sh +deepzora plugin search review +deepzora plugin info catalog:acme/review-kit +deepzora plugin install catalog:acme/review-kit@1.2.0 --dry-run +deepzora plugin install catalog:acme/review-kit@1.2.0 --yes --plan-id <预览返回的ID> +deepzora plugin updates +deepzora plugin update review-kit --dry-run +``` + +桌面新增 SearchPluginCatalog、PluginCatalogDetail 两个只读入口;安装、更新共用版本解析与计划确认服务,扩展现有 Go bridge 参数并从 Go 重新生成桌面契约。目录错误(离线/撤回/不兼容)、安装错误(计划变化/同名冲突/无法获取 SHA)与激活错误分开返回。 + +## 四、交付顺序与验收 + +| 阶段 | 交付内容 | 发布门槛 | +|---|---|---| +| 1. 社区渠道闭环 | 目录 schema、作者模板、静态校验/发布工作流、Go 客户端、固定 SHA 安装、CLI 搜索及预览确认 | 用含资源的原生包与有兼容跳过项的包,从 PR 到临时 Deepzora home 完整安装;移动 tag 后仍只装审核 SHA;预览变化、撤回或不同来源占名时不写盘。 | +| 2. 桌面及更新 | 发现/已安装联动、更新差异、保留禁用状态、失败恢复及诊断 | 用含 runtime 的测试包验证信任提示、取消零写入、禁用升级后仍禁用、重载延迟与激活失败不误报成功;模拟状态写入失败,旧版本仍可用。CLI 和 Desktop 解析同一版本。 | +| 3. 未审核发现 | topic 索引、独立来源筛选、显式来源映射 | 同 repo/path 多入口只展示一张卡;不同仓库同名不会覆盖;审核章不随 tag、fork 或候选索引迁移;离线启动会话不依赖市场。 | + +跨平台验收至少覆盖 Windows 路径/文件占用、macOS 和 Linux 的 Git 安装与目录替换。保留旧状态文件、手动 URL、本地 link 的回归用例。后续若 Git 下载速度成为实际瓶颈,再设计可校验的发布压缩包和镜像;目录身份、版本审批及现有安装状态均可沿用。 + +参考:[Magpie 社区目录与投稿](https://github.com/magpie-community/plugins#the-market)、[GitHub topic 索引](https://github.com/magpie-community/plugins/blob/main/.github/workflows/tagged.yml)、[Deepzora 插件包说明](../PLUGIN_PACKAGES.zh-CN.md)、[Deepzora 运行时 v2](../EXTENSION_RUNTIME_V2.zh-CN.md)。 diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index fa3d44d2f..433271baa 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -12,6 +12,7 @@ import ( "deepzora/internal/config" "deepzora/internal/hook" "deepzora/internal/installsource" + "deepzora/internal/plugincatalog" "deepzora/internal/pluginpkg" "deepzora/internal/secrets" ) @@ -22,6 +23,17 @@ func pluginCommand(args []string) int { return 0 } switch args[0] { + case "recover": + if len(args) != 1 { + return 2 + } + if err := installsource.RecoverCatalog(context.Background(), config.DeepzoraHomeDir()); err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + return 0 + case "search", "info", "updates", "update": + return pluginMarketCommand(args) case "install": return pluginInstallCommand(args[1:]) case "list": @@ -46,9 +58,80 @@ func pluginCommand(args []string) int { } } +func pluginMarketCommand(args []string) int { + home := config.DeepzoraHomeDir() + ctx := context.Background() + var data any + var err error + switch args[0] { + case "search": + var q []string + all := false + for _, s := range args[1:] { + if s == "--all" { + all = true + } else { + q = append(q, s) + } + } + data, err = plugincatalog.Search(ctx, home, strings.Join(q, " "), all) + case "info": + if len(args) != 2 || !plugincatalog.IsSpec(args[1]) { + pluginUsage() + return 2 + } + data, err = plugincatalog.Resolve(ctx, home, args[1]) + case "updates": + var st pluginpkg.State + st, err = pluginpkg.LoadState(home) + rows := []map[string]string{} + if err == nil { + for _, p := range st.Plugins { + if p.CatalogID == "" { + continue + } + r, e := plugincatalog.Resolve(ctx, home, p.CatalogID) + row := map[string]string{"name": p.Name, "installed": p.Version} + if e != nil { + row["error"] = e.Error() + } else if r.Commit != p.Commit { + row["available"] = r.Version + } else { + continue + } + rows = append(rows, row) + } + } + data = rows + case "update": + if len(args) < 2 { + pluginUsage() + return 2 + } + p, ok, e := findInstalledPlugin(args[1]) + if e != nil || !ok || p.CatalogID == "" { + fmt.Fprintln(os.Stderr, "no catalog installation named", args[1]) + return 1 + } + return pluginInstallCommand(append([]string{p.CatalogID, "--replace", "--name", p.Name}, args[2:]...)) + } + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + if err = json.NewEncoder(os.Stdout).Encode(data); err != nil { + return 1 + } + return 0 +} + func pluginUsage() { fmt.Fprintln(os.Stderr, `usage: - deepzora plugin install [--yes] [--dry-run] [--link] [--replace] +deepzora plugin search [query] [--all] + deepzora plugin info catalog:[@version] + deepzora plugin updates + deepzora plugin update --dry-run | --yes --plan-id + deepzora plugin install [--yes] [--plan-id ] [--dry-run] [--link] [--replace] deepzora plugin list deepzora plugin show deepzora plugin enable @@ -73,6 +156,7 @@ func pluginInstallCommand(args []string) int { } body := map[string]any{ "source": source, + "planId": opts.planID, "kind": "plugin", "apply": !opts.dryRun, "mode": mode, @@ -85,6 +169,7 @@ func pluginInstallCommand(args []string) int { } type parsedPluginInstallArgs struct { + planID string yes bool dryRun bool link bool @@ -100,6 +185,12 @@ func parsePluginInstallArgs(args []string) (parsedPluginInstallArgs, string, err switch { case arg == "--yes": opts.yes = true + case arg == "--plan-id": + i++ + if i >= len(args) || strings.HasPrefix(args[i], "-") { + return opts, "", fmt.Errorf("--plan-id requires a value") + } + opts.planID = args[i] case arg == "--dry-run": opts.dryRun = true case arg == "--link": @@ -203,8 +294,22 @@ func redactInstallSourceJSON(raw string) (string, error) { // planId is an engine-generated approval identity, not free-form output. // Scrubbing its digest would make the preview impossible to approve. var planID string + type verifiedCommit struct { + row map[string]any + sha string + } + var commits []verifiedCommit if object, ok := value.(map[string]any); ok { planID, _ = object["planId"].(string) + // Only restore Git object IDs from catalog actions verified against a fetched commit. + rows, _ := object["actions"].([]any) + for _, v := range rows { + a, _ := v.(map[string]any) + s, _ := a["commit"].(string) + if a["catalog"] != nil && len(s) == 40 && strings.Trim(s, "0123456789abcdef") == "" { + commits = append(commits, verifiedCommit{a, s}) + } + } } var redact func(any) any redact = func(v any) any { @@ -227,6 +332,9 @@ func redactInstallSourceJSON(raw string) (string, error) { return v } redacted := redact(value) + for _, v := range commits { + v.row["commit"] = v.sha + } if object, ok := redacted.(map[string]any); ok && planID != "" { object["planId"] = planID } diff --git a/internal/installsource/catalog.go b/internal/installsource/catalog.go new file mode 100644 index 000000000..8035e259c --- /dev/null +++ b/internal/installsource/catalog.go @@ -0,0 +1,152 @@ +package installsource + +import ( + "context" + "deepzora/internal/secrets" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + "deepzora/internal/filelock" + "deepzora/internal/plugincatalog" + "deepzora/internal/pluginpkg" +) + +var fullCommit = regexp.MustCompile(`^[a-f0-9]{40}$`) + +type CatalogPlan struct { + Execution []string `json:"execution,omitempty"` + PreviousExecution []string `json:"previousExecution,omitempty"` + Requirements []pluginpkg.CapabilityRef `json:"requirements,omitempty"` + ID string `json:"id"` + Channel string `json:"channel"` + Previous *pluginpkg.InstalledPlugin `json:"previous,omitempty"` + PreviousCapabilities *pluginpkg.CapabilitySummary `json:"previousCapabilities,omitempty"` + Capabilities pluginpkg.CapabilitySummary `json:"capabilities"` +} + +func executionSummary(p pluginpkg.Package) []string { + var lines []string + for _, h := range p.Inventory().Hooks { + if h.Command != "" { + lines = append(lines, "hook "+h.Event+": "+secrets.RedactCredentials(h.Command)) + } + } + for n, m := range p.Manifest.MCPServers { + lines = append(lines, "MCP "+n+": "+secrets.RedactCredentials(strings.TrimSpace(m.Command+" "+strings.Join(m.Args, " ")+" "+m.URL))) + } + if p.Manifest.Runtime != nil { + lines = append(lines, "runtime: "+secrets.RedactCredentials(pluginpkg.RuntimeCommandLine(p.Manifest.Runtime))) + } + sort.Strings(lines) + return lines +} +func catalogSpec(s string) bool { return plugincatalog.IsSpec(s) } +func (t *installSourceTool) lockCatalog(ctx context.Context) (func(), error) { + if err := os.MkdirAll(t.deepzoraHome, 0700); err != nil { + return nil, err + } + c, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + return filelock.Acquire(c, filepath.Join(t.deepzoraHome, ".plugin-market.lock")) +} +func fetchSnapshot(ctx context.Context, tmp, url, sha string) error { + for _, args := range [][]string{{"init", "--quiet", tmp}, {"-C", tmp, "fetch", "--no-tags", "--depth=1", url, sha}, {"-C", tmp, "checkout", "--quiet", "--detach", "FETCH_HEAD"}} { + if out, err := pluginGitCommand(ctx, args...).CombinedOutput(); err != nil { + return fmt.Errorf("fetch pinned plugin %s: %w: %s", sha, err, out) + } + } + out, err := pluginGitCommand(ctx, "-C", tmp, "rev-parse", "HEAD").Output() + if err != nil || strings.TrimSpace(string(out)) != sha { + return errors.New("plugin snapshot does not match approved commit") + } + return nil +} +func (t *installSourceTool) planCatalog(ctx context.Context, req request) ([]action, []string, error) { + if req.Mode == "link" || req.Op != "install" || (req.Kind != "auto" && req.Kind != "plugin") { + return nil, nil, errors.New("catalog entries require a plugin copy installation") + } + e, err := plugincatalog.Resolve(ctx, t.deepzoraHome, req.Source) + if err != nil { + return nil, nil, err + } + root, commit, cleanup, err := t.pluginSource(ctx, e.Source(), "copy") + if err != nil { + return nil, nil, err + } + keep := false + defer func() { + if !keep { + cleanup() + } + }() + p, w, err := pluginpkg.ParseDir(root) + if err != nil { + return nil, w, err + } + if commit != e.Commit || p.Manifest.Name != e.ManifestName || p.Manifest.Version != e.Version || p.ManifestKind != e.ManifestKind { + return nil, w, errors.New("catalog identity does not match the pinned manifest") + } + req.Mode = "copy" + a, err := t.pluginPackageAction(req, p, e.Source()) + if err != nil { + return nil, w, err + } + if !pluginpkg.IsValidName(a.Name) { + return nil, w, errors.New("invalid install name") + } + c := &CatalogPlan{ID: strings.Split(e.Spec, "@")[0], Channel: e.Channel, Capabilities: p.CapabilitySummary()} + c.Execution = executionSummary(p) + c.Requirements = p.Manifest.Requires + state, err := pluginpkg.LoadState(t.deepzoraHome) + if err != nil { + return nil, w, err + } + for _, old := range state.Plugins { + if !strings.EqualFold(old.Name, a.Name) { + continue + } + src, ok := parseGitHubRepoSource(old.Source) + if old.Name != a.Name || !ok || !strings.EqualFold(src.Owner+"/"+src.Repo, e.Repo) || src.Path != e.Path || old.CatalogID != "" && (old.CatalogID != c.ID || old.Channel != e.Channel) { + return nil, w, fmt.Errorf("%s belongs to another source; choose --name", a.Name) + } + if !req.Replace { + return nil, w, errors.New("already installed; preview with --replace to update") + } + c.Previous = &old + if prior, _, err := pluginpkg.ParseDir(pluginpkg.ResolveRoot(t.deepzoraHome, old.Root)); err == nil { + s := prior.CapabilitySummary() + c.PreviousCapabilities = &s + c.PreviousExecution = executionSummary(prior) + } + } + if c.Previous == nil { + if _, err := os.Lstat(a.Target); err == nil { + return nil, w, errors.New("target exists without a matching installed record; choose --name") + } else if !os.IsNotExist(err) { + return nil, w, err + } + } + a.Catalog = c + a.Commit = commit + a.preparedRoot = root + a.cleanup = cleanup + keep = true + return []action{a}, w, nil +} +func (t *installSourceTool) commitCatalogInstall(req request, a *action, p pluginpkg.Package, src, target, sha string) error { + enabled := true + if prev := a.Catalog.Previous; prev != nil { + if !req.Replace { + return errors.New("replacement not approved") + } + enabled = prev.Enabled + } + entry := pluginpkg.InstalledPlugin{Name: a.Name, Source: a.Source, Root: pluginpkg.RelativeRoot(t.deepzoraHome, target), Version: p.Manifest.Version, Description: p.Manifest.Description, ManifestKind: p.ManifestKind, Enabled: enabled, Commit: sha, CatalogID: a.Catalog.ID, Channel: a.Catalog.Channel} + return stageCatalog(t.deepzoraHome, p, src, target, catalogTransaction{Previous: a.Catalog.Previous, Next: entry}) +} diff --git a/internal/installsource/catalog_transaction.go b/internal/installsource/catalog_transaction.go new file mode 100644 index 000000000..9f51df853 --- /dev/null +++ b/internal/installsource/catalog_transaction.go @@ -0,0 +1,139 @@ +package installsource + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + + "deepzora/internal/fileutil" + "deepzora/internal/pluginpkg" +) + +// One writer holds the market lock. Keep both trees on the same filesystem; +// the durable journal precedes either rename. A lost process can be recovered +// without consulting a branch, a network index, or plugin code. +type catalogTransaction struct { + Previous *pluginpkg.InstalledPlugin `json:"previous,omitempty"` + Next pluginpkg.InstalledPlugin `json:"next"` +} + +func txnDir(home string) string { + return filepath.Join(pluginpkg.PluginsDir(home), ".market-transaction") +} +func exists(path string) (bool, error) { + _, err := os.Lstat(path) + if os.IsNotExist(err) { + return false, nil + } + return err == nil, err +} +func stageCatalog(home string, p pluginpkg.Package, src, target string, tx catalogTransaction) error { + d := txnDir(home) + if err := os.MkdirAll(filepath.Dir(d), 0700); err != nil { + return err + } + if err := os.Mkdir(d, 0700); err != nil { + return fmt.Errorf("plugin transaction pending (run deepzora plugin recover): %w", err) + } + stage := filepath.Join(d, "next") + if err := installCopiedPlugin(p, src, stage, false); err != nil { + _ = os.RemoveAll(d) + return err + } + b, err := json.Marshal(tx) + if err == nil { + err = fileutil.AtomicWriteFileStrict(filepath.Join(d, "journal.json"), b, 0600) + } + if err != nil { + _ = os.RemoveAll(d) + return err + } + rollback := func(cause error) error { return errors.Join(cause, recoverCatalog(home)) } + if tx.Previous != nil { + if err = os.Rename(target, filepath.Join(d, "previous")); err != nil { + return rollback(err) + } + } + if present, err := exists(target); err != nil || present { + return rollback(errors.New("plugin target changed while installing")) + } + if err = os.Rename(stage, target); err != nil { + return rollback(err) + } + if err = pluginpkg.Upsert(home, tx.Next); err != nil { + return rollback(err) + } + return os.RemoveAll(d) +} +func RecoverCatalog(ctx context.Context, home string) error { + t := &installSourceTool{deepzoraHome: home} + release, err := t.lockCatalog(ctx) + if err != nil { + return err + } + defer release() + return recoverCatalog(home) +} +func recoverCatalog(home string) error { + d := txnDir(home) + has, err := exists(d) + if err != nil || !has { + return err + } + var tx catalogTransaction + b, err := os.ReadFile(filepath.Join(d, "journal.json")) + if os.IsNotExist(err) { + return os.RemoveAll(d) + } + if err != nil { + return err + } + if err = json.Unmarshal(b, &tx); err != nil { + return err + } + if !pluginpkg.IsValidName(tx.Next.Name) || !fullCommit.MatchString(tx.Next.Commit) || tx.Previous != nil && tx.Previous.Name != tx.Next.Name { + return errors.New("invalid plugin recovery journal") + } + target := pluginpkg.InstallRoot(home, tx.Next.Name) + stage := filepath.Join(d, "next") + prior := filepath.Join(d, "previous") + moved, err := exists(prior) + if err != nil { + return err + } + staged, err := exists(stage) + if err != nil { + return err + } + state, err := pluginpkg.LoadState(home) + if err != nil { + return err + } + var current *pluginpkg.InstalledPlugin + for i := range state.Plugins { + if state.Plugins[i].Name == tx.Next.Name { + current = &state.Plugins[i] + break + } + } + if !staged && current != nil && *current == tx.Next { + return os.RemoveAll(d) + } + if current != nil && (tx.Previous == nil || *current != *tx.Previous) || current == nil && tx.Previous != nil { + return errors.New("installed record changed during recovery; previous package retained") + } + if !staged { + if err = os.Rename(target, stage); err != nil && !os.IsNotExist(err) { + return err + } + } + if moved { + if err = os.Rename(prior, target); err != nil { + return err + } + } + return os.RemoveAll(d) +} diff --git a/internal/installsource/catalog_transaction_test.go b/internal/installsource/catalog_transaction_test.go new file mode 100644 index 000000000..88f454ab2 --- /dev/null +++ b/internal/installsource/catalog_transaction_test.go @@ -0,0 +1,54 @@ +package installsource + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "deepzora/internal/pluginpkg" +) + +func TestMarketRecoveryBetweenTreeSwapAndStateCommit(t *testing.T) { + for _, committed := range []bool{false, true} { + t.Run(map[bool]string{false: "uncommitted", true: "committed"}[committed], func(t *testing.T) { + home := t.TempDir() + target := pluginpkg.InstallRoot(home, "kit") + d := txnDir(home) + old := pluginpkg.InstalledPlugin{Name: "kit", Root: "plugins/kit", Version: "1.0.0", Commit: strings.Repeat("a", 40)} + next := old + next.Version = "1.1.0" + next.Commit = strings.Repeat("b", 40) + for file, body := range map[string]string{filepath.Join(target, "marker"): "new", filepath.Join(d, "previous", "marker"): "old"} { + if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(file, []byte(body), 0600); err != nil { + t.Fatal(err) + } + } + b, _ := json.Marshal(catalogTransaction{Previous: &old, Next: next}) + if err := os.WriteFile(filepath.Join(d, "journal.json"), b, 0600); err != nil { + t.Fatal(err) + } + record, want := old, "old" + if committed { + record, want = next, "new" + } + if err := pluginpkg.Upsert(home, record); err != nil { + t.Fatal(err) + } + if err := RecoverCatalog(t.Context(), home); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(target, "marker")) + if err != nil || string(got) != want { + t.Fatalf("got %s %v", got, err) + } + if err := RecoverCatalog(t.Context(), home); err != nil { + t.Fatal("not idempotent", err) + } + }) + } +} diff --git a/internal/installsource/install_source.go b/internal/installsource/install_source.go index 4b7243955..7b0fc2bb5 100644 --- a/internal/installsource/install_source.go +++ b/internal/installsource/install_source.go @@ -180,6 +180,19 @@ func (t *installSourceTool) Execute(ctx context.Context, raw json.RawMessage) (s return t.executeUninstall(req), nil } + if catalogSpec(req.Source) && req.Apply { + if req.PlanID == "" { + return "", errors.New("catalog installation requires a preview and --plan-id") + } + unlock, err := t.lockCatalog(ctx) + if err != nil { + return "", err + } + defer unlock() + if err := recoverCatalog(t.deepzoraHome); err != nil { + return "", err + } + } actions, warnings, err := t.plan(ctx, req) if err != nil { if errors.Is(err, ErrNoCompatibleCapabilities) { diff --git a/internal/installsource/plan.go b/internal/installsource/plan.go index 524c49c10..4af449cd2 100644 --- a/internal/installsource/plan.go +++ b/internal/installsource/plan.go @@ -19,6 +19,9 @@ var githubAPIBaseURL = "https://api.github.com" // plan turns a request into a list of actions plus a warnings slice. It // does not touch the disk; the apply phase is responsible for side effects. func (t *installSourceTool) plan(ctx context.Context, req request) ([]action, []string, error) { + if catalogSpec(req.Source) { + return t.planCatalog(ctx, req) + } if after, ok := strings.CutPrefix(req.Source, "git:github.com/"); ok { req.Source = "https://github.com/" + after } diff --git a/internal/installsource/plugin_package.go b/internal/installsource/plugin_package.go index d752fedbb..c3bcf09b6 100644 --- a/internal/installsource/plugin_package.go +++ b/internal/installsource/plugin_package.go @@ -458,6 +458,9 @@ func (t *installSourceTool) applyInstallPluginPackage(ctx context.Context, req r if pkg.Manifest.Name != act.Name && strings.TrimSpace(req.Name) == "" { return newErr(ErrInvalidManifest, "planned plugin name %q but source now reports %q", act.Name, pkg.Manifest.Name) } + if act.Catalog != nil { + return t.commitCatalogInstall(req, act, pkg, sourceRoot, target, commit) + } if act.Mode == "link" { if !isLinkTargetSafe(sourceRoot, t.home, t.root) { return newErr(ErrUnsafeLinkTarget, "plugin source %s is outside %s and %s", sourceRoot, t.root, t.home) @@ -514,6 +517,18 @@ func (t *installSourceTool) preparePluginSource(ctx context.Context, source, mod return "", "", func() {}, err } cloneURL := fmt.Sprintf("https://github.com/%s/%s.git", src.Owner, src.Repo) + if fullCommit.MatchString(src.Branch) { + if err := fetchSnapshot(ctx, tmp, cloneURL, src.Branch); err != nil { + os.RemoveAll(tmp) + return "", "", func() {}, err + } + root, err := pluginRootFromClone(tmp, src.Path) + if err != nil { + os.RemoveAll(tmp) + return "", "", func() {}, err + } + return root, src.Branch, func() { _ = os.RemoveAll(tmp) }, nil + } args := []string{"clone", "--depth=1"} if src.Branch != "" { args = append(args, "--branch", src.Branch) diff --git a/internal/installsource/types.go b/internal/installsource/types.go index ea4cdafde..868fd8553 100644 --- a/internal/installsource/types.go +++ b/internal/installsource/types.go @@ -69,6 +69,7 @@ type kindTally struct { // dispatcher; RiskLevel/RiskReasons help the calling skill decide whether to // ask the user before apply=true. type action struct { + Catalog *CatalogPlan `json:"catalog,omitempty"` Kind string `json:"kind"` // "skill" | "mcp" | "plugin" Action string `json:"action"` // copy_skill|link_skill|register_skill_root|install_mcp_server|remove_skill|remove_skill_root|remove_mcp_server Status string `json:"status"` // planned|done|failed @@ -183,7 +184,7 @@ func publicActions(in []action) []action { // Construct the public DTO field-by-field so credentials held by the // internal config entry, environment, or headers cannot reach JSON output. out[i] = action{ - Kind: a.Kind, Action: a.Action, Status: a.Status, + Catalog: a.Catalog, Kind: a.Kind, Action: a.Action, Status: a.Status, RiskLevel: a.RiskLevel, RiskReasons: a.RiskReasons, Name: a.Name, Source: a.Source, Target: a.Target, ConfigPath: a.ConfigPath, Scope: a.Scope, Mode: a.Mode, Transport: a.Transport, URL: a.URL, diff --git a/internal/plugincatalog/catalog.go b/internal/plugincatalog/catalog.go new file mode 100644 index 000000000..56d6ebadb --- /dev/null +++ b/internal/plugincatalog/catalog.go @@ -0,0 +1,293 @@ +// Package plugincatalog reads the public market on explicit user requests only. +package plugincatalog + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "regexp" + "runtime" + "slices" + "sort" + "strings" + "time" + + "deepzora/internal/fileutil" + "golang.org/x/mod/semver" +) + +const base = "https://raw.githubusercontent.com/SivanCola/deepzora-plugins/dist/" +const maxSize = 4 << 20 + +// HostVersion is set once during process startup from the binary build identity. +var HostVersion string + +var pair = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*/[a-zA-Z0-9][a-zA-Z0-9_.-]*$`) +var segment = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`) +var sha = regexp.MustCompile(`^[a-f0-9]{40}$`) + +type Release struct { + MinDeepzora string `json:"minDeepzora,omitempty"` + ID string `json:"id"` + Name string `json:"name"` + Version string `json:"version"` + Repo string `json:"repo"` + Path string `json:"path,omitempty"` + Commit string `json:"commit"` + Summary map[string]string `json:"summary"` + ManifestName string `json:"manifestName"` + ManifestKind string `json:"manifestKind"` + Platforms []string `json:"platforms,omitempty"` + Capabilities []string `json:"capabilities,omitempty"` + Yanked bool `json:"yanked,omitempty"` +} +type Index struct { + SchemaVersion int `json:"schemaVersion"` + Releases []Release `json:"releases"` +} +type Candidate struct { + Spec string `json:"spec"` + Version string `json:"version"` +} +type Entry struct { + Upstream *Candidate `json:"upstream,omitempty"` + Release + Channel string `json:"channel"` + Spec string `json:"spec"` +} +type Result struct { + Entries []Entry `json:"entries"` + Warning string `json:"warning,omitempty"` +} + +func (r Release) Source() string { + return strings.TrimSuffix("https://github.com/"+r.Repo+"/tree/"+r.Commit+"/"+r.Path, "/") +} +func (r Release) origin() string { return strings.ToLower(r.Repo) + "/" + r.Path } +func (r Release) Compatible() bool { + if r.MinDeepzora != "" { + host := "v" + strings.TrimPrefix(HostVersion, "v") + if !semver.IsValid(host) || semver.Compare(host, "v"+r.MinDeepzora) < 0 { + return false + } + } + if len(r.Platforms) == 0 { + return true + } + return slices.Contains(r.Platforms, runtime.GOOS) +} +func Parse(b []byte) (Index, error) { + var idx Index + if err := json.Unmarshal(b, &idx); err != nil { + return idx, err + } + if idx.SchemaVersion != 1 || idx.Releases == nil { + return idx, errors.New("unsupported or incomplete plugin catalog") + } + seen := map[string]bool{} + sources := map[string]string{} + ids := map[string]string{} + for _, r := range idx.Releases { + if !pair.MatchString(r.ID) || strings.ToLower(r.ID) != r.ID || !pair.MatchString(r.Repo) || !sha.MatchString(r.Commit) || !segment.MatchString(r.ManifestName) || strings.TrimSpace(r.Name) == "" || !semver.IsValid("v"+r.Version) || semver.Canonical("v"+r.Version) != "v"+r.Version { + return idx, fmt.Errorf("invalid release %q @ %q", r.ID, r.Version) + } + if strings.TrimSpace(r.Summary["en"]) == "" || strings.TrimSpace(r.Summary["zh"]) == "" { + return idx, fmt.Errorf("missing localized summary for %s", r.ID) + } + if r.ManifestKind != "deepzora" && r.ManifestKind != "codex" && r.ManifestKind != "claude" { + return idx, fmt.Errorf("unsupported manifest kind %s", r.ManifestKind) + } + if r.Path != "" { + if path.Clean(r.Path) != r.Path { + return idx, errors.New("invalid package path") + } + for s := range strings.SplitSeq(r.Path, "/") { + if !segment.MatchString(s) { + return idx, errors.New("invalid package path") + } + } + } + if r.MinDeepzora != "" && !semver.IsValid("v"+r.MinDeepzora) { + return idx, fmt.Errorf("invalid minDeepzora for %s", r.ID) + } + key := r.ID + "@" + r.Version + if seen[key] || sources[r.origin()] != "" && sources[r.origin()] != r.ID || ids[r.ID] != "" && ids[r.ID] != r.origin() { + return idx, fmt.Errorf("conflicting catalog entry %s", key) + } + seen[key] = true + sources[r.origin()] = r.ID + ids[r.ID] = r.origin() + } + sort.Slice(idx.Releases, func(i, j int) bool { + a, b := idx.Releases[i], idx.Releases[j] + if a.ID == b.ID { + return semver.Compare("v"+a.Version, "v"+b.Version) > 0 + } + return a.ID < b.ID + }) + return idx, nil +} +func location(topic bool) (string, string) { + key, file, channel := "DEEPZORA_PLUGIN_CATALOG", "index-v1.json", "community" + if topic { + key, file, channel = "DEEPZORA_PLUGIN_TAGGED", "tagged.json", "unreviewed" + } + if v := os.Getenv(key); v != "" { + return v, "custom" + } + return base + file, channel +} + +type cachedIndex struct { + ETag string `json:"etag,omitempty"` + Body json.RawMessage `json:"body"` +} + +func fetch(ctx context.Context, loc string, prior cachedIndex) (cachedIndex, error) { + var rd io.ReadCloser + var tag string + if strings.HasPrefix(loc, "https://") { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, loc, nil) + if err != nil { + return cachedIndex{}, err + } + if prior.ETag != "" { + req.Header.Set("If-None-Match", prior.ETag) + } + resp, err := (&http.Client{Timeout: 15 * time.Second}).Do(req) + if err != nil { + return cachedIndex{}, err + } + rd = resp.Body + defer rd.Close() + if resp.StatusCode == http.StatusNotModified && prior.ETag != "" { + return prior, nil + } + if resp.StatusCode != http.StatusOK { + return cachedIndex{}, fmt.Errorf("catalog: HTTP %s", resp.Status) + } + tag = resp.Header.Get("ETag") + } else { + if !filepath.IsAbs(loc) { + return cachedIndex{}, errors.New("catalog must be HTTPS or an absolute local filename") + } + f, err := os.Open(loc) + if err != nil { + return cachedIndex{}, err + } + rd = f + defer rd.Close() + } + b, err := io.ReadAll(io.LimitReader(rd, maxSize+1)) + if len(b) > maxSize { + return cachedIndex{}, errors.New("catalog too large") + } + return cachedIndex{ETag: tag, Body: b}, err +} + +// Browse may use the last good snapshot. Install requires a successful fetch +// or conditional revalidation from the selected authority. +func read(ctx context.Context, home string, topic, fresh bool) (Index, string, string, error) { + loc, channel := location(topic) + f := filepath.Join(home, "cache", "plugin-market", fmt.Sprintf("%x.json", sha256.Sum256([]byte(loc)))) + var prior cachedIndex + var cached Index + if b, err := os.ReadFile(f); err == nil && json.Unmarshal(b, &prior) == nil { + if i, e := Parse(prior.Body); e == nil { + cached = i + } else { + prior = cachedIndex{} + } + } + if !fresh && cached.Releases != nil { + ttl := 6 * time.Hour + if topic { + ttl = 10 * time.Minute + } + if st, err := os.Stat(f); err == nil && time.Since(st.ModTime()) < ttl { + return cached, channel, "", nil + } + } + next, err := fetch(ctx, loc, prior) + if err == nil { + var i Index + i, err = Parse(next.Body) + if err == nil { + if b, e := json.Marshal(next); e == nil && os.MkdirAll(filepath.Dir(f), 0700) == nil { + _ = fileutil.AtomicWriteFile(f, b, 0600) + } + return i, channel, "", nil + } + } + if !fresh && cached.Releases != nil { + return cached, channel, "offline cache: " + err.Error(), nil + } + return Index{}, channel, "", err +} +func Search(ctx context.Context, home, q string, topics bool) (Result, error) { + out := Result{Entries: []Entry{}} + origins := map[string]bool{} + listed := map[string]int{} + for _, topic := range []bool{false, true} { + if topic && !topics { + break + } + idx, ch, w, err := read(ctx, home, topic, false) + if err != nil { + if !topic { + return out, err + } + out.Warning = err.Error() + break + } + if w != "" { + out.Warning = w + } + for _, r := range idx.Releases { + if r.Yanked || !r.Compatible() || semver.Prerelease("v"+r.Version) != "" { + continue + } + if origins[r.origin()] { + if i, ok := listed[r.origin()]; topic && ok && out.Entries[i].Upstream == nil && semver.Compare("v"+r.Version, "v"+out.Entries[i].Version) > 0 { + out.Entries[i].Upstream = &Candidate{"topic:" + r.ID + "@" + r.Version, r.Version} + } + continue + } + origins[r.origin()] = true + if !strings.Contains(strings.ToLower(strings.Join([]string{r.ID, r.Name, r.Repo, r.Summary["en"], r.Summary["zh"], strings.Join(r.Capabilities, " ")}, " ")), strings.ToLower(q)) { + continue + } + prefix := "catalog:" + if topic { + prefix = "topic:" + } + if !topic { + listed[r.origin()] = len(out.Entries) + } + out.Entries = append(out.Entries, Entry{Release: r, Channel: ch, Spec: prefix + r.ID + "@" + r.Version}) + } + } + return out, nil +} +func IsSpec(s string) bool { return strings.HasPrefix(s, "catalog:") || strings.HasPrefix(s, "topic:") } +func Resolve(ctx context.Context, home, s string) (Entry, error) { + prefix, rest, _ := strings.Cut(s, ":") + id, v, _ := strings.Cut(rest, "@") + idx, ch, _, err := read(ctx, home, prefix == "topic", true) + if err != nil { + return Entry{}, err + } + for _, r := range idx.Releases { + if r.ID == id && !r.Yanked && r.Compatible() && (r.Version == v || v == "" && semver.Prerelease("v"+r.Version) == "") { + return Entry{Release: r, Channel: ch, Spec: prefix + ":" + id + "@" + r.Version}, nil + } + } + return Entry{}, fmt.Errorf("no installable release for %s (absent, withdrawn, or incompatible)", s) +} diff --git a/internal/plugincatalog/catalog_test.go b/internal/plugincatalog/catalog_test.go new file mode 100644 index 000000000..f2be9fff9 --- /dev/null +++ b/internal/plugincatalog/catalog_test.go @@ -0,0 +1,63 @@ +package plugincatalog + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestDiscoveryIsNotApproval(t *testing.T) { + h := t.TempDir() + market, topics := filepath.Join(h, "catalog"), filepath.Join(h, "topic") + t.Setenv("DEEPZORA_PLUGIN_CATALOG", market) + t.Setenv("DEEPZORA_PLUGIN_TAGGED", topics) + row := Release{ID: "community/a", Name: "Tool", Version: "1.0.0", Repo: "A/Repo", Commit: strings.Repeat("a", 40), ManifestName: "tool", ManifestKind: "deepzora", Summary: map[string]string{"en": "Tool", "zh": "工具"}} + put := func(p string, rows ...Release) { + b, _ := json.Marshal(Index{1, rows}) + if err := os.WriteFile(p, b, 0600); err != nil { + t.Fatal(err) + } + } + upstream := row + upstream.ID = "a/repo" + upstream.Version = "2.0.0" + upstream.Commit = strings.Repeat("b", 40) + other := upstream + other.ID = "b/repo" + other.Repo = "b/repo" + put(market, row) + put(topics, upstream, other) + got, err := Search(t.Context(), h, "", true) + if err != nil || len(got.Entries) != 2 { + t.Fatal(got, err) + } + e := got.Entries[0] + if e.Channel != "custom" || e.Commit != row.Commit || e.Upstream == nil || e.Upstream.Version != "2.0.0" { + t.Fatal(e) + } + row.Yanked = true + put(market, row) + if _, err := Resolve(t.Context(), h, e.Spec); err == nil { + t.Fatal("cached result authorized a withdrawn release") + } + if err = os.Remove(market); err != nil { + t.Fatal(err) + } + cache, _ := filepath.Glob(filepath.Join(h, "cache", "plugin-market", "*.json")) + for _, p := range cache { + past := time.Now().Add(-24 * time.Hour) + if err = os.Chtimes(p, past, past); err != nil { + t.Fatal(err) + } + } + got, err = Search(t.Context(), h, "", false) + if err != nil || got.Warning == "" { + t.Fatal("offline browse", got, err) + } + if _, err = Resolve(t.Context(), h, e.Spec); err == nil { + t.Fatal("offline cache authorized installation") + } +} diff --git a/internal/pluginpkg/pluginpkg.go b/internal/pluginpkg/pluginpkg.go index 229568c30..cd8a33819 100644 --- a/internal/pluginpkg/pluginpkg.go +++ b/internal/pluginpkg/pluginpkg.go @@ -248,6 +248,8 @@ type State struct { } type InstalledPlugin struct { + CatalogID string `json:"catalogId,omitempty"` + Channel string `json:"channel,omitempty"` Name string `json:"name"` Source string `json:"source,omitempty"` Root string `json:"root"` diff --git a/scripts/plugin-market-e2e.py b/scripts/plugin-market-e2e.py new file mode 100644 index 000000000..f370037fd --- /dev/null +++ b/scripts/plugin-market-e2e.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Offline end-to-end acceptance with the real CLI, Git transport and package state.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +cli = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="deepzora-market-") as tmp: + t = Path(tmp) + repo = t / "upstream" + repo.mkdir() + env = dict(os.environ, HOME=str(t), DEEPZORA_HOME=str(t/"home"), + GIT_CONFIG_GLOBAL=str(t/"gitconfig"), XDG_CONFIG_HOME=str(t/"config"), + DEEPZORA_PLUGIN_CATALOG=str(t/"index.json"), DEEPZORA_PLUGIN_TAGGED=str(t/"tagged.json")) + def run(*args, ok=True): + r = subprocess.run(args, cwd=repo, env=env, text=True, capture_output=True, timeout=60) + assert (r.returncode == 0) == ok, (args, r.stdout, r.stderr) + return r.stdout.strip() + def git(*args): + return run("git",*args) + def dz(*args,ok=True): + return run(str(cli),"plugin",*args,ok=ok) + git("init","-q") + git("config","user.name","Acceptance") + git("config","user.email","test@example.invalid") + git("config","--global","url."+repo.as_uri()+".insteadOf","https://github.com/test/plugins.git") + pkg=repo/"packages"/"kit" + (pkg/"skills"/"kit").mkdir(parents=True) + def commit(version): + (pkg/"deepzora-plugin.json").write_text(json.dumps({"apiVersion":"deepzora.com/plugin/v2","name":"kit","version":version,"contributes":{"skills":["skills"]}})) + (pkg/"skills"/"kit"/"SKILL.md").write_text("---\nname: kit\ndescription: Test skill\n---\n"+version) + git("add",".");git("commit","-qm",version) + return git("rev-parse","HEAD") + sha=commit("1.0.0") + git("tag","latest") + def release(version,sha): + return dict(id="test/kit",name="Kit",repo="test/plugins",path="packages/kit",version=version,commit=sha,manifestName="kit",manifestKind="deepzora",summary={"en":"Code review","zh":"审查"}) + def publish(rows,channel="index"): + (t/(channel+".json")).write_text(json.dumps(dict(schemaVersion=1,releases=rows))) + row=release("1.0.0",sha) + publish([row]);publish([dict(row,id="third/kit")],"tagged") + spec="catalog:test/kit" + assert len(json.loads(dz("search","--all","review"))["entries"])==1 + plan=json.loads(dz("install",spec,"--dry-run")) + assert plan["actions"][0]["commit"]==sha and plan["actions"][0]["skillCount"]==1 + new=commit("1.1.0") + git("tag","-f","latest") + dz("install",spec,"--yes","--plan-id","wrong",ok=False) + dest=t/"home"/"plugins"/"kit" + assert not dest.exists() + dz("install",spec,"--yes","--plan-id",plan["planId"]) + skill=dest/"skills"/"kit"/"SKILL.md" + assert skill.read_text().endswith("1.0.0") + state=lambda:json.loads((t/"home"/"plugin-packages.json").read_text())["plugins"][0] + assert state()["commit"]==sha + dz("doctor","kit") + dz("disable","kit") + nextrow=release("1.1.0",new) + publish([row,nextrow]) + update=json.loads(dz("update","kit","--dry-run")) + publish([row,dict(nextrow,yanked=True)]) + dz("update","kit","--yes","--plan-id",update["planId"],ok=False) + assert state()["commit"]==sha + publish([row,nextrow]) + dz("update","kit","--yes","--plan-id",update["planId"]) + assert state()["commit"]==new and not state()["enabled"] + assert skill.read_text().endswith("1.1.0") + other=dict(nextrow,id="someone/kit",repo="test/other") + git("config","--global","--add","url."+repo.as_uri()+".insteadOf","https://github.com/test/other.git") + publish([nextrow,other]) + dz("install","catalog:someone/kit","--replace","--dry-run",ok=False) + # The other supported manifest path: one mapped skill plus a skipped feature. + compat=repo/"compat" + (compat/".claude-plugin").mkdir(parents=True) + (compat/".claude-plugin/plugin.json").write_text(json.dumps(dict(name="compat",version="1.0.0",outputStyles="./styles"))) + (compat/"skills/compat").mkdir(parents=True) + (compat/"skills/compat/SKILL.md").write_text("---\nname: compat\ndescription: Test\n---\nOK") + git("add",".");git("commit","-qm","Claude package") + cr=dict(row,id="test/compat",path="compat",manifestName="compat",manifestKind="claude",commit=git("rev-parse","HEAD")) + publish([cr]) + cp=json.loads(dz("install","catalog:test/compat","--dry-run")) + assert cp["actions"][0]["skillCount"]==1 + dz("install","catalog:test/compat","--yes","--plan-id",cp["planId"]) + print("PASS: search, deduplication, immutable Git snapshot after tag moved, plan identity, withdrawal, upgrade, disabled state, collision and compatible package.") + From 8070286bbcb93b66124d9da1c6f1b50663d5557f Mon Sep 17 00:00:00 2001 From: zumac Date: Thu, 12 Nov 2026 03:06:42 -0800 Subject: [PATCH 2/2] fix(plugins): tolerate malformed catalog rows, settle interrupted installs and repair CI gates - Parse drops malformed or conflicting catalog rows instead of rejecting the whole index, so one tagged repository cannot hide the unreviewed channel; dropped rows stay unresolvable. - Recovery settles to the installed record when the plugin was toggled or removed after an interruption instead of blocking later catalog writes. - Desktop clears a stale preview when name, replace or link changes, so a manual install no longer sends an outdated plan ID. - Acceptance script asserts the reason for each refusal and covers an index re-pointed at another commit. - Extract install-plan parsing from CapabilitiesPanel, split the catalog apply preflight out of Execute, and regenerate the desktop inventory. --- .../src/components/CapabilitiesPanel.tsx | 145 ++---------------- desktop/frontend/src/lib/bridge.ts | 2 +- desktop/frontend/src/lib/pluginInstallPlan.ts | 120 +++++++++++++++ docs/desktop-contract/INVENTORY.md | 129 ++++++++-------- docs/desktop-contract/inventory.json | 132 ++++++++-------- docs/plans/plugin-market-acceptance.zh-CN.md | 1 + internal/cli/plugin.go | 2 +- internal/installsource/catalog.go | 22 +++ internal/installsource/catalog_transaction.go | 39 ++++- .../installsource/catalog_transaction_test.go | 58 +++++++ internal/installsource/install_source.go | 16 +- internal/plugincatalog/catalog.go | 65 +++++--- internal/plugincatalog/catalog_test.go | 23 ++- scripts/plugin-market-e2e.py | 23 ++- 14 files changed, 468 insertions(+), 309 deletions(-) create mode 100644 desktop/frontend/src/lib/pluginInstallPlan.ts diff --git a/desktop/frontend/src/components/CapabilitiesPanel.tsx b/desktop/frontend/src/components/CapabilitiesPanel.tsx index 71ad0012a..bc3916aa9 100644 --- a/desktop/frontend/src/components/CapabilitiesPanel.tsx +++ b/desktop/frontend/src/components/CapabilitiesPanel.tsx @@ -10,10 +10,11 @@ import { app } from "../lib/bridge"; import { activeWorkBusyNoticeText, installMCPServer } from "../lib/capabilityMutations"; import { useT } from "../lib/i18n"; import { presentError } from "../lib/errorPresentation"; +import { parsePluginInstallPlan, type PluginInstallPlanAction, type PluginInstallPlanView, type PluginRuntimePlan } from "../lib/pluginInstallPlan"; import { mcpServerLifecycleActions, mcpServerRetryableFromAvailableList } from "../lib/mcpServerLifecycle"; import { mcpSessionStateLabel, mcpSettingsSearchText } from "../lib/mcpSessionStatus"; import { canUseNativeMCPOAuth } from "../lib/mcpOAuthEligibility"; -import type { CapabilitiesView, MCPMarketplaceEntry, MCPMarketplaceView, MCPServerInput, PluginAgentView, PluginCommandView, PluginCompatibilityIssue, PluginHookView, PluginInstallOptions, PluginMCPServerView, PluginSkillView, PluginView, ServerView, SkillRootSkillView, SkillRootView, SkillsSettingsView, SkillView, TabMeta } from "../lib/types"; +import type { CapabilitiesView, MCPMarketplaceEntry, MCPMarketplaceView, MCPServerInput, PluginAgentView, PluginCommandView, PluginHookView, PluginInstallOptions, PluginMCPServerView, PluginSkillView, PluginView, ServerView, SkillRootSkillView, SkillRootView, SkillsSettingsView, SkillView, TabMeta } from "../lib/types"; import { InlineConfirmButton } from "./InlineConfirmButton"; import { ResizableDrawer } from "./ResizableDrawer"; import { Tooltip } from "./Tooltip"; @@ -1613,47 +1614,6 @@ export function parseMCPQuickDefinition(raw: string): MCPServerInput { return { name: quickMCPName(definition), transport: "stdio", command: definition, args: [], url: "", env: null, headers: null }; } -type PluginRuntimePlan = { - command?: string; - args?: string[]; - intercepts?: string[]; - replaces?: string[]; - capabilities?: string[]; - fullTrust?: boolean; -}; - -type PluginInstallPlanAction = { - changes?: string[]; - action?: string; - kind?: string; - name?: string; - source?: string; - status?: string; - message?: string; - error?: string; - compatibility?: string; - mappedCapabilities?: string[]; - skippedCapabilities?: PluginCompatibilityIssue[]; - runtime?: PluginRuntimePlan; - agentCount?: number; - skillCount?: number; - commandCount?: number; - hookCount?: number; - toolCount?: number; -}; - -type PluginInstallPlanView = { - planId?: string; - activationWarning?: string; - raw: string; - ok?: boolean; - status?: string; - name?: string; - actions: PluginInstallPlanAction[]; - warnings: string[]; - error?: string; -}; - type PluginInstallMode = "local" | "git"; // PluginsSettingsPage is the desktop plugin package manager embedded inside @@ -1806,12 +1766,15 @@ export function PluginsSettingsPage() { {loadError && { setLoadError(null); void reload(); }}>} {notice && !err && {notice}}
-
- {!discover && summary && {summary}}
+
+ + + {!discover && summary && {summary}} +
-{discover && } + {discover && }