Files
Reims-Go/internal/plugin/contract.go
T
NwflowerandClaude Opus 5.5 fa3e1e2889 feat: add plugin views and expand the sandboxed page bridge
Plugins can add pages to the sidebar, VM tabs, Settings and dialogs. Their
pages can now use host forms and navigation, VM and settings access,
authorized file I/O, task progress, controlled HTTP requests, events and
private storage.

Plugin pages cannot change allow_ai_access, which stays the user's per-VM
consent. Closing a page cancels its unfinished tasks, and running plugin
tasks no longer block changing the data folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:11:23 -07:00

510 lines
19 KiB
Go

package plugin
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
)
// Contract catalogs (see docs/plugin-architecture.md).
//
// Every public contract entry is either stable or experimental. Stable entries
// are implemented by the host and covered by the compatibility promise;
// experimental entries are part of the published shape, accepted by manifest
// validation, reported by `plugin doctor`, and not yet acted on. An entry is
// promoted in the same change that implements it. Slots, layout options, icon
// names and view locations mirror frontend/src/styles/ui-contract.ts, bridge
// methods mirror frontend/src/lib/bridgeContract.ts; contract_test.go keeps
// them identical.
// ContractStatus marks whether a contract entry is implemented.
type ContractStatus string
const (
ContractStable ContractStatus = "stable"
ContractExperimental ContractStatus = "experimental"
)
// ContributionCatalog lists every `contributes` key (its JSON name).
var ContributionCatalog = map[string]ContractStatus{
"themes": ContractStable,
"channels": ContractStable,
"uiScripts": ContractExperimental, // theme.uiScript is the implemented path
"locales": ContractStable,
"inputFilters": ContractStable,
"vmTemplates": ContractExperimental,
"runtimeSources": ContractExperimental,
"runtimeKinds": ContractStable,
"runtimes": ContractExperimental,
"guestDrivers": ContractStable,
"downloaders": ContractStable,
"hooks": ContractStable,
"ruleHooks": ContractStable,
"commands": ContractStable,
"menus": ContractStable,
"vmCards": ContractExperimental,
"settingsPages": ContractExperimental,
"statusItems": ContractExperimental,
"panels": ContractStable,
"imageSources": ContractStable,
"views": ContractStable,
"diagnostics": ContractExperimental,
}
// ThemeFieldCatalog lists theme fields whose host support is still pending.
// Fields not listed here are stable.
var ThemeFieldCatalog = map[string]ContractStatus{
"icons": ContractStable,
"brandMark": ContractStable,
"layout": ContractStable,
}
// Slot content kinds.
const (
SlotDecoration = "decoration" // theme decorations
SlotMount = "mount" // UI SDK mountSlot
SlotPanel = "panel" // panels
SlotMenu = "menu" // menus
SlotStatusItem = "statusItem" // statusItems
SlotVMCard = "vmCard" // vmCards
SlotSettingsPage = "settingsPage" // settingsPages
)
// SlotSpec describes one UI slot: whether its anchor is rendered (Status),
// how many plugin items it takes, and which content kinds it accepts.
type SlotSpec struct {
Status ContractStatus
Max int
Accepts map[string]ContractStatus
}
func anchorSlot(status ContractStatus, max int, extra map[string]ContractStatus) SlotSpec {
accepts := map[string]ContractStatus{SlotDecoration: status, SlotMount: status}
for k, v := range extra {
accepts[k] = v
}
return SlotSpec{Status: status, Max: max, Accepts: accepts}
}
// UISlotCatalog lists every supported UI slot and accepted contribution kinds.
var UISlotCatalog = map[string]SlotSpec{
"sidebar.footer": anchorSlot(ContractStable, 2, map[string]ContractStatus{SlotPanel: ContractExperimental}),
"statusbar.right": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotStatusItem: ContractExperimental}),
"vm.card": anchorSlot(ContractStable, 6, map[string]ContractStatus{SlotVMCard: ContractExperimental, SlotPanel: ContractExperimental}),
"settings.plugin": anchorSlot(ContractStable, 16, map[string]ContractStatus{SlotPanel: ContractStable, SlotSettingsPage: ContractExperimental}),
"vm.preview.tl": anchorSlot(ContractStable, 2, nil),
"vm.preview.tr": anchorSlot(ContractStable, 2, nil),
"vm.preview.bl": anchorSlot(ContractStable, 2, nil),
"vm.preview.br": anchorSlot(ContractStable, 2, nil),
"empty.state": anchorSlot(ContractStable, 2, nil),
"titlebar.center": anchorSlot(ContractStable, 1, nil),
"sidebar.header": anchorSlot(ContractStable, 2, nil),
"nav.item.trailing": anchorSlot(ContractStable, 2, nil),
"vm.header.trailing": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotMenu: ContractExperimental}),
"vm.toolbar": anchorSlot(ContractStable, 8, map[string]ContractStatus{SlotMenu: ContractStable}),
"statusbar.left": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotStatusItem: ContractExperimental}),
"create.source": anchorSlot(ContractStable, 4, map[string]ContractStatus{SlotPanel: ContractExperimental}),
}
// ViewLocationSpec describes one place a plugin view can appear.
type ViewLocationSpec struct {
Status ContractStatus
PerPlugin int // views one plugin may declare at this location
}
// ViewLocationCatalog lists `views[].location` values.
var ViewLocationCatalog = map[string]ViewLocationSpec{
"sidebar": {Status: ContractStable, PerPlugin: 2},
"vm.tab": {Status: ContractStable, PerPlugin: 4},
"settings": {Status: ContractStable, PerPlugin: 1},
"dialog": {Status: ContractStable, PerPlugin: 8},
}
// UILayerCatalog lists full-window layers.
var UILayerCatalog = map[string]ContractStatus{
"layer.background": ContractStable,
"layer.overlay": ContractStable,
}
// ThemeLayoutCatalog lists theme `layout` options and their allowed values.
var ThemeLayoutCatalog = map[string][]string{
"sidebarPosition": {"left", "right"},
"sidebarMode": {"full", "rail", "floating"},
"density": {"compact", "regular", "comfortable"},
"titlebar": {"standard", "compact"},
}
// ThemeIconNames lists icon names a theme `icons` map may override.
var ThemeIconNames = []string{
"start", "stop", "force-stop", "restart", "suspend", "resume", "new-vm",
"settings", "plugin", "folder", "logs", "screenshot", "fullscreen", "window",
"snapshot", "clone", "delete", "info", "warning", "error",
"vm.state.running", "vm.state.stopped", "vm.state.suspended", "vm.state.busy", "vm.state.error",
}
// BridgeMethodSpec describes one plugin UI bridge method.
type BridgeMethodSpec struct {
Status ContractStatus
Permission string // "" = always allowed for the calling plugin's own data
}
// BridgeMethodCatalog lists bridgeApi 1.0 methods.
var BridgeMethodCatalog = map[string]BridgeMethodSpec{
"hello": {Status: ContractStable},
"i18n.getBundle": {Status: ContractStable},
"ui.notify": {Status: ContractStable, Permission: "ui:notify"},
"ui.confirm": {Status: ContractStable, Permission: "ui:notify"},
"ui.copy": {Status: ContractStable, Permission: "ui:slot"},
"ui.openExternal": {Status: ContractStable, Permission: "ui:slot"},
"vm.list": {Status: ContractStable, Permission: "vm:read"},
"command.invoke": {Status: ContractStable, Permission: "ui:slot"},
"storage.get": {Status: ContractStable, Permission: "fs:plugin_data"},
"storage.set": {Status: ContractStable, Permission: "fs:plugin_data"},
"storage.list": {Status: ContractStable, Permission: "fs:plugin_data"},
"storage.delete": {Status: ContractStable, Permission: "fs:plugin_data"},
"ui.showForm": {Status: ContractStable, Permission: "ui:slot"},
"ui.setTitle": {Status: ContractStable, Permission: "ui:slot"},
"ui.setBadge": {Status: ContractStable, Permission: "ui:slot"},
"ui.openView": {Status: ContractStable, Permission: "ui:slot"},
"ui.close": {Status: ContractStable, Permission: "ui:slot"},
"ui.navigate": {Status: ContractStable, Permission: "ui:slot"},
"vm.get": {Status: ContractStable, Permission: "vm:read"},
"settings.get": {Status: ContractStable},
"settings.set": {Status: ContractStable},
"file.pick": {Status: ContractStable, Permission: "fs:pick"},
"file.save": {Status: ContractStable, Permission: "fs:pick"},
"file.read": {Status: ContractStable, Permission: "fs:pick"},
"file.write": {Status: ContractStable, Permission: "fs:pick"},
"task.start": {Status: ContractStable, Permission: "task:progress"},
"task.update": {Status: ContractStable, Permission: "task:progress"},
"task.finish": {Status: ContractStable, Permission: "task:progress"},
"net.fetch": {Status: ContractStable, Permission: "net:"}, // matched against net:<origin>
"events.subscribe": {Status: ContractStable},
"events.unsubscribe": {Status: ContractStable},
}
// BridgeMethodAliases maps pre-1.0 method names to their bridgeApi 1.0 names.
var BridgeMethodAliases = map[string]string{"notify": "ui.notify"}
// BridgeEventCatalog lists bridgeApi 1.0 events.
var BridgeEventCatalog = map[string]ContractStatus{
"theme.changed": ContractStable,
"locale.changed": ContractStable,
"vm.stateChanged": ContractStable,
"view.visibilityChanged": ContractStable,
"task.updated": ContractStable,
}
// ResolveBridgeMethod maps an incoming method name to its catalog entry.
func ResolveBridgeMethod(method string) (string, BridgeMethodSpec, bool) {
if to, ok := BridgeMethodAliases[method]; ok {
method = to
}
spec, ok := BridgeMethodCatalog[method]
return method, spec, ok
}
// HostFeatures lists the stable host features advertised in the Sidecar and
// bridge handshakes, sorted. Plugins feature-detect with these instead
// of comparing version numbers.
func HostFeatures() []string {
var out []string
for k, st := range ContributionCatalog {
if st == ContractStable {
out = append(out, "contrib."+k)
}
}
for id, spec := range UISlotCatalog {
if spec.Status == ContractStable {
out = append(out, "slot."+id)
}
for kind, st := range spec.Accepts {
if st == ContractStable && kind != SlotDecoration && kind != SlotMount {
out = append(out, "slot."+id+"."+kind)
}
}
}
for loc, spec := range ViewLocationCatalog {
if spec.Status == ContractStable {
out = append(out, "view."+loc)
}
}
for id, st := range UILayerCatalog {
if st == ContractStable {
out = append(out, id)
}
}
for field, st := range ThemeFieldCatalog {
if st == ContractStable {
out = append(out, "theme."+field)
}
}
for m, spec := range BridgeMethodCatalog {
if spec.Status == ContractStable {
out = append(out, "bridge."+m)
}
}
for ev, st := range BridgeEventCatalog {
if st == ContractStable {
out = append(out, "event."+ev)
}
}
sort.Strings(out)
return out
}
var reContributionID = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
// validateUIContract checks the UI-facing parts of a manifest against the
// catalogs: unknown slots, locations, layout values or icon names are errors;
// experimental ones are accepted and reported by ContractFindings.
func validateUIContract(m Manifest) error {
channelIDs := make(map[string]bool, len(m.Contributes.Channels))
for _, channel := range m.Contributes.Channels {
if channel.ID != strings.TrimSpace(channel.ID) || !reContributionID.MatchString(channel.ID) {
return fmt.Errorf("invalid channel id %q", channel.ID)
}
if channelIDs[channel.ID] {
return fmt.Errorf("duplicate channel id %q", channel.ID)
}
channelIDs[channel.ID] = true
if channel.Framing != "jsonl" {
return fmt.Errorf("channel %q uses unsupported framing %q", channel.ID, channel.Framing)
}
}
if len(channelIDs) > 0 && strings.TrimSpace(m.Entry.Sidecar) == "" {
return fmt.Errorf("plugin channels require a Sidecar entry")
}
checkSlot := func(what, id, slot, kind string) error {
spec, ok := UISlotCatalog[slot]
if !ok {
return fmt.Errorf("%s %q targets unknown slot %q", what, id, slot)
}
if _, ok := spec.Accepts[kind]; !ok {
return fmt.Errorf("%s %q: slot %q does not accept %s contributions", what, id, slot, kind)
}
return nil
}
for _, p := range m.Contributes.Panels {
if err := checkSlot("panel", p.ID, p.Slot, SlotPanel); err != nil {
return err
}
}
for _, mc := range m.Contributes.Menus {
if err := checkSlot("menu", mc.ID, mc.Slot, SlotMenu); err != nil {
return err
}
}
for _, si := range m.Contributes.StatusItems {
if err := checkSlot("status item", si.ID, si.Slot, SlotStatusItem); err != nil {
return err
}
}
seenImageSources := map[string]bool{}
for _, src := range m.Contributes.ImageSources {
if !reContributionID.MatchString(src.ID) {
return fmt.Errorf("invalid image source id %q", src.ID)
}
if seenImageSources[src.ID] {
return fmt.Errorf("duplicate image source id %q", src.ID)
}
seenImageSources[src.ID] = true
if !src.Title.HasAny() {
return fmt.Errorf("image source %q is missing a localized title", src.ID)
}
if strings.TrimSpace(src.Native) == "" {
if strings.TrimSpace(m.Entry.PanelDir) == "" {
return fmt.Errorf("image source %q requires entry.panelDir", src.ID)
}
entry := strings.TrimSpace(src.Entry)
if entry == "" {
entry = "index.html"
}
if err := validateSafeManifestAsset(entry, ""); err != nil {
return fmt.Errorf("invalid image source %q entry %q: %w", src.ID, src.Entry, err)
}
}
}
perLocation := map[string]int{}
seenViews := map[string]bool{}
for _, v := range m.Contributes.Views {
if !reContributionID.MatchString(v.ID) {
return fmt.Errorf("invalid view id %q", v.ID)
}
if seenViews[v.ID] {
return fmt.Errorf("duplicate view id %q", v.ID)
}
seenViews[v.ID] = true
if !v.Title.HasAny() {
return fmt.Errorf("view %q is missing a localized title", v.ID)
}
spec, ok := ViewLocationCatalog[v.Location]
if !ok {
return fmt.Errorf("view %q has unknown location %q", v.ID, v.Location)
}
perLocation[v.Location]++
if perLocation[v.Location] > spec.PerPlugin {
return fmt.Errorf("too many views at location %q (at most %d per plugin)", v.Location, spec.PerPlugin)
}
if strings.TrimSpace(m.Entry.PanelDir) == "" {
return fmt.Errorf("view %q requires entry.panelDir", v.ID)
}
if err := validateSafeManifestAsset(strings.TrimSpace(v.Entry), ""); err != nil {
return fmt.Errorf("invalid view %q entry %q: %w", v.ID, v.Entry, err)
}
if icon := strings.TrimSpace(v.Icon); icon != "" {
if err := validateSafeManifestAsset(icon, ""); err != nil {
return fmt.Errorf("invalid view %q icon %q: %w", v.ID, v.Icon, err)
}
}
}
icons := map[string]bool{}
for _, n := range ThemeIconNames {
icons[n] = true
}
for _, th := range m.Contributes.Themes {
for _, d := range th.Decorations {
_, slot := UISlotCatalog[d.Slot]
_, layer := UILayerCatalog[d.Slot]
if !slot && !layer {
return fmt.Errorf("theme %q decoration %q targets unknown slot or layer %q", th.ID, d.ID, d.Slot)
}
}
for name := range th.Icons {
if !icons[name] {
return fmt.Errorf("theme %q overrides unknown icon %q", th.ID, name)
}
}
if l := th.Layout; l != nil {
for opt, val := range map[string]string{
"sidebarPosition": l.SidebarPosition, "sidebarMode": l.SidebarMode,
"density": l.Density, "titlebar": l.Titlebar,
} {
if val != "" && !containsString(ThemeLayoutCatalog[opt], val) {
return fmt.Errorf("theme %q layout.%s has unknown value %q", th.ID, opt, val)
}
}
}
}
if req := strings.TrimSpace(m.Engines.BridgeAPI); req != "" && !MatchesRange(BridgeAPIVersion, req) {
return fmt.Errorf("incompatible bridgeApi: plugin requires %s, host provides %s", req, BridgeAPIVersion)
}
return nil
}
// ContractFindings reports non-blocking contract advisories for `plugin
// doctor` and the install-time scan: experimental entries the manifest relies
// on, fields this host does not know, and missing engines ranges. raw is the
// plugin.json text the manifest was decoded from.
func ContractFindings(m Manifest, raw []byte) []ScanFinding {
var out []ScanFinding
add := func(check, target, msg, zh, en string) {
out = append(out, ScanFinding{Severity: ScanSeverityPending, Check: check, Target: target, Message: msg,
Localized: LocalizedText{ZhCN: zh, EnUS: en}})
}
experimental := func(target, what string) {
add("contract-experimental", target, what+" is experimental: the host does not act on it yet and it carries no compatibility promise",
what+" 仍是实验性契约:宿主尚未实现,不受兼容承诺约束",
what+" is experimental: the host does not act on it yet and it carries no compatibility promise")
}
for _, key := range usedContributionKeys(m.Contributes) {
if ContributionCatalog[key] == ContractExperimental {
experimental("contributes."+key, "contributes."+key)
}
}
slotUse := func(what, id, slot, kind string) {
if spec, ok := UISlotCatalog[slot]; ok && spec.Accepts[kind] == ContractExperimental {
experimental(what+":"+id, fmt.Sprintf("%s in slot %s", what, slot))
}
}
for _, p := range m.Contributes.Panels {
slotUse("panel", p.ID, p.Slot, SlotPanel)
}
for _, mc := range m.Contributes.Menus {
slotUse("menu", mc.ID, mc.Slot, SlotMenu)
}
for _, v := range m.Contributes.Views {
if spec, ok := ViewLocationCatalog[v.Location]; ok && spec.Status == ContractExperimental && ContributionCatalog["views"] == ContractStable {
experimental("view:"+v.ID, "view location "+v.Location)
}
}
for _, th := range m.Contributes.Themes {
if len(th.Icons) > 0 && ThemeFieldCatalog["icons"] == ContractExperimental {
experimental("theme:"+th.ID, "theme icons")
}
if th.BrandMark != "" && ThemeFieldCatalog["brandMark"] == ContractExperimental {
experimental("theme:"+th.ID, "theme brandMark")
}
if th.Layout != nil && ThemeFieldCatalog["layout"] == ContractExperimental {
experimental("theme:"+th.ID, "theme layout")
}
for _, d := range th.Decorations {
if spec, ok := UISlotCatalog[d.Slot]; ok && spec.Status == ContractExperimental {
experimental("theme:"+th.ID, "decoration in slot "+d.Slot)
}
}
}
if len(raw) > 0 {
dec := json.NewDecoder(bytes.NewReader(bytes.TrimPrefix(raw, []byte("\xef\xbb\xbf"))))
dec.DisallowUnknownFields()
var strict Manifest
if err := dec.Decode(&strict); err != nil && strings.Contains(err.Error(), "unknown field") {
add("contract-unknown-field", "plugin.json", err.Error(),
"清单含本宿主不认识的字段,会被忽略:"+err.Error(),
"plugin.json has a field this host does not know; it is ignored: "+err.Error())
}
}
hasIframeImageSource := false
for _, src := range m.Contributes.ImageSources {
if strings.TrimSpace(src.Native) == "" {
hasIframeImageSource = true
break
}
}
usesUI := len(m.Contributes.Themes) > 0 || len(m.Contributes.Panels) > 0 || hasIframeImageSource || len(m.Contributes.Views) > 0
if usesUI && strings.TrimSpace(m.Engines.UIAPI) == "" {
add("contract-engines", "engines.uiApi", "declare engines.uiApi so incompatible hosts refuse the plugin up front",
"建议声明 engines.uiApi,让不兼容的宿主在安装前就拒绝",
"Declare engines.uiApi so incompatible hosts refuse the plugin up front")
}
if (len(m.Contributes.Panels) > 0 || hasIframeImageSource || len(m.Contributes.Views) > 0) && strings.TrimSpace(m.Engines.BridgeAPI) == "" {
add("contract-engines", "engines.bridgeApi", "declare engines.bridgeApi for panels and views",
"面板与视图建议声明 engines.bridgeApi",
"Declare engines.bridgeApi for panels and views")
}
return out
}
// usedContributionKeys returns the JSON names of non-empty contributes lists.
func usedContributionKeys(c Contributes) []string {
var out []string
v := reflect.ValueOf(c)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
if f := v.Field(i); f.Kind() == reflect.Slice && f.Len() > 0 {
out = append(out, name)
}
}
return out
}
func containsString(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}