mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
* feat(pi): manage individual extensions per target Keep package lifecycle in Plugins while letting global, account, and project Pi targets configure individual extensions with reviewed, lossless changes. Project overrides save only project settings and never grant trust. Bind edits to native version contracts, settings snapshots, source ownership, and discovery; preserve unrelated resources and enforce renewable native locks, stale rejection, and backups. Verify Pi 0.99.2 and 1.0.0 without running extension factories. Simplify configured-state UI and distinguish Skillshare-managed packages from native tool registrations, with localized guidance and regression coverage. Closes #342. * fix(pi): address project extensions review findings Keep exact project delta rules visible when their extension files are missing so users can remove stale rules without changing global settings or trust. Show the project Extensions tab only when its generated Pi target resolves. Cover missing and agents-only projects, absent targets, and another project target with regression tests. * fix(pi): recognize official Windows account launchers Accept pi.cmd and pi.exe account launcher names on Windows, including case-insensitive and native Windows paths, before probing the existing exact-version gate. Preserve POSIX behavior and never probe unrecognized forks or stacked launcher suffixes. Add platform-name and account-gate regressions covering verified, unsupported, and missing CLI versions. Focused race tests, make check, and Windows amd64/arm64 test cross-compilation pass; real Windows runtime remains unverified because the UTM guest is stopped. * fix(pi): align rule removal and backup descriptions Offer Remove rule only for owned exact +/- rules, not project delta globs that the apply path cannot remove. Keep supported glob rows switchable and cover delta and deltaOnly forms with RED/GREEN regressions. Describe retained artifacts as extension-list and file-hash records rather than complete settings backups in English, all four website translations, and the implementation report. * fix(pi): discard records for aborted extension applies Require a validated preview and owned native lock before recording an extension change. Discard only the newly created record if final revalidation, lock ownership, or the atomic settings write fails; retain successful history and propagate cleanup errors with the original failure. Keep discovery revalidation after record I/O so cleanup does not weaken the write-boundary guard. Cover global and new/existing project settings with nine RED/GREEN regressions, including injected commit failures. Align English and translated docs with the retained-record lifecycle. * fix(pi): retain anonymous global packages in projects Keep ordered anonymous registrations separate from the proven-identity map so unsupported query-bearing sources remain visible as redacted read-only packages, rather than being dropped or associated with a project override. Preserve first-global-entry precedence for known identities. Add RED/GREEN coverage for string and object registrations, query/userinfo redaction, project entries, zero-write refusal, ordering, and continued editing of known packages. * fix(pi): deduplicate only proven project identities Exclude unresolved identities from project duplicate tracking. Preserve each anonymous registration as sourceUnknown instead of pretending unrelated query-bearing URLs are the same package. Cover mixed string/object anonymous project sources, redaction and zero-write refusals, retained anonymous globals, and last-project-entry precedence for known packages. Verify known project entries remain editable. * fix(pi): guard unresolved package precedence An unresolved earlier global registration may own a later known package, and an unresolved later project registration may supersede an earlier known entry. Keep those potentially shadowed entries and inherited deltas Unknown/read-only instead of offering edits to ignored registrations. Do not infer identities by dropping credentials or queries. Cover both ordering directions for global, inherited, project-owned, and delta views with RED/GREEN tests. Execute native query identity and dedupe evidence on Pi 0.99.2 and 1.0.0 through core and CLI-bundle contracts, now 28 scenarios and 87 assertions each. Align docs and evidence while retaining independent anonymous entries. * fix(pi): propagate unreadable source ambiguity Treat badSource entries as unresolved instead of letting an unreadable source expose editable later global registrations. Preserve the same uncertainty in inherited globals and before unreadable later project entries. Add twelve global/inherited/project regressions for null, empty, whitespace and invalid UTF-8 sources. Native core and CLI-bundle evidence confirms invalid UTF-8 can decode to and own the same identity as a later valid source on both supported Pi versions; the executed contracts now pass 29 scenarios and 90 assertions. * feat(pi): preserve filtered imports and reclaim stale locks Adopt native object registrations without changing their configured resources. Keep lossless entries in scoped private state, retain current rules across lifecycle operations, restore filters before native installation, and preserve pending retries after failures. Reclaim only unchanged empty directories after the native stale threshold, retaining renewed, replaced, nonempty and non-directory locks. Verify exact supported Pi contracts and keep unsupported cases read-only. * docs(pi): record filtered import verification after branch sync Document the current merged UI test count and repeated checks while retaining the native and visual verification limitations. * docs(pi): clarify stale acquisition exception Keep the lock safety summary consistent with the approved acquisition policy while preserving strict ownership for renewal and release. * fix(pi): keep legacy npm fallback installations unknown A missing user-scoped managed npm root cannot prove a package is absent because native Pi may use a legacy global npm or pnpm root. Keep it read-only without probing host-global state, while retaining missing-state behavior for project npm packages. * fix(pi): preserve project precedence and batch restore ownership Retain empty winning overrides when deleting them could expose older resource filters. Advance filtered restore batches only to exact writes made by the same Apply, while rejecting external changes and retaining failed native retries. Match Pi strict-false autoload semantics instead of treating null as a delta.
268 lines
8.5 KiB
Go
268 lines
8.5 KiB
Go
package plugin
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// NormalizeTarget resolves the Antigravity CLI nickname without changing stored keys.
|
|
func NormalizeTarget(target string) string {
|
|
if target == "agy" {
|
|
return "antigravity"
|
|
}
|
|
return target
|
|
}
|
|
|
|
// ProjectSupported never falls back to a user-scoped installation.
|
|
func ProjectSupported(target string) bool {
|
|
for _, d := range TargetDefinitions() {
|
|
if d.Target == target {
|
|
return d.Project
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// validTargetID checks an identifier for the Agent that installs it. An empty target is
|
|
// an account whose Agent the caller could not resolve; every Agent that can have one
|
|
// writes its plugins as name@marketplace.
|
|
func validTargetID(target, id string) bool {
|
|
switch target {
|
|
case "":
|
|
return validID(id)
|
|
case "claude", "codex":
|
|
return validID(id)
|
|
case "cursor", "antigravity", "antigravity-cli", "grok", "kimi", "hermes", "devin":
|
|
return namePattern.MatchString(id)
|
|
case "copilot":
|
|
return namePattern.MatchString(id) || validID(id)
|
|
case "pi", "opencode":
|
|
return id != "" && !strings.HasPrefix(id, "-") && !strings.ContainsAny(id, "\x00\r\n")
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (s *Service) snapshotPath(b Binding, target string) string {
|
|
market := "skillshare-" + hash([]byte(s.ConfigPath + "\x00" + b.Source + "\x00" + b.Plugin + "\x00" + target))[:16]
|
|
if agent := s.agentOf(target); agent == "claude" || agent == "codex" {
|
|
_, market, _ = strings.Cut(b.ID, "@")
|
|
}
|
|
return filepath.Join(s.managedRoot(), market)
|
|
}
|
|
|
|
// Require an explicit, existing entry. Do not execute package code to discover it.
|
|
func openCodeEntry(root string, explicit ...string) (string, error) {
|
|
data, err := os.ReadFile(filepath.Join(root, "package.json"))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var m struct {
|
|
Main string `json:"main"`
|
|
Exports json.RawMessage `json:"exports"`
|
|
}
|
|
if err = json.Unmarshal(data, &m); err != nil {
|
|
return "", err
|
|
}
|
|
entry := m.Main
|
|
if len(m.Exports) > 0 && (len(explicit) == 0 || explicit[0] == "") {
|
|
if json.Unmarshal(m.Exports, &entry) != nil {
|
|
var exports map[string]json.RawMessage
|
|
if json.Unmarshal(m.Exports, &exports) != nil || json.Unmarshal(exports["."], &entry) != nil {
|
|
return "", agentError{key: "plugins.problem.opencodeExports", message: "OpenCode package needs an unambiguous string root export; conditional exports are not supported"}
|
|
}
|
|
}
|
|
}
|
|
if len(explicit) > 0 && explicit[0] != "" {
|
|
entry = explicit[0]
|
|
}
|
|
if entry == "" {
|
|
entry = "index.js"
|
|
}
|
|
clean := filepath.Clean(entry)
|
|
if filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
|
|
return "", agentError{key: "plugins.problem.opencodeEscapes", message: "OpenCode package entry escapes its directory"}
|
|
}
|
|
ext := filepath.Ext(clean)
|
|
if ext != ".js" && ext != ".mjs" && ext != ".ts" {
|
|
return "", agentError{key: "plugins.problem.opencodeEntryType", message: "OpenCode package requires a built JavaScript or TypeScript entry"}
|
|
}
|
|
info, err := os.Lstat(filepath.Join(root, clean))
|
|
if err != nil || !info.Mode().IsRegular() {
|
|
return "", agentError{key: "plugins.problem.opencodeEntryMissing", message: fmt.Sprintf("OpenCode package entry %s is missing; build the package before adding it", clean), args: map[string]string{"entry": clean}}
|
|
}
|
|
return clean, nil
|
|
}
|
|
|
|
func (s *Service) additionalHost(ctx context.Context, target string) Host {
|
|
agent := s.agentOf(target)
|
|
h := Host{Target: target, Status: HostReady, Installed: []Installed{}}
|
|
if problem := automationProblem(agent); problem != "" {
|
|
h.block("plugins.problem."+agent, problem)
|
|
return h
|
|
}
|
|
if commandTarget(agent) {
|
|
return s.commandHost(ctx, target)
|
|
}
|
|
if s.ProjectRoot != "" && !ProjectSupported(agent) {
|
|
h.block("plugins.error.userScoped", agent+" plugins are user-scoped; use global mode. Project operations never fall back to global.")
|
|
return h
|
|
}
|
|
var err error
|
|
switch agent {
|
|
case "cursor":
|
|
h.NoteKey = "plugins.note.cursor"
|
|
h.Note = "Local plugin files only. Reload Cursor and allow local plugin imports; marketplace installations take precedence."
|
|
h.Installed, h.Fingerprint, err = s.localInventory(agent)
|
|
case "antigravity":
|
|
h.NoteKey = "plugins.note.antigravity"
|
|
h.Note = "Custom plugin files for Antigravity desktop/workspaces; verify loading in Antigravity. The standalone agy CLI uses a separate plugin store."
|
|
h.Installed, h.Fingerprint, err = s.localInventory(agent)
|
|
case "pi":
|
|
var data []byte
|
|
data, err = s.run(ctx, target, "--version")
|
|
h.Version = strings.TrimSpace(string(data))
|
|
if err == nil {
|
|
h.Installed, h.Fingerprint, err = s.piInventory(target)
|
|
}
|
|
if err == nil && filepath.IsAbs(s.StateDir) && slices.ContainsFunc(h.Installed, func(i Installed) bool { return i.Filtered }) {
|
|
if _, why := s.piGate(ctx, target); why == "" {
|
|
for i := range h.Installed {
|
|
if h.Installed[i].Filtered {
|
|
_, _, _, entryErr := s.piRegistrationEntry(target, h.Installed[i].ID)
|
|
h.Installed[i].Importable = entryErr == nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
h.NoteKey = "plugins.note.pi"
|
|
h.Note = "Package registrations from Pi settings; resource loading is verified in Pi."
|
|
case "opencode":
|
|
var data []byte
|
|
data, err = s.run(ctx, target, "--version")
|
|
h.Version = strings.TrimSpace(string(data))
|
|
if err == nil {
|
|
h.Installed, h.Fingerprint, err = s.openCodeInventory(h.Version)
|
|
}
|
|
h.NoteKey = "plugins.note.opencode"
|
|
h.Note = "Plugin registrations only. OpenCode loads code and resolves dependencies on startup."
|
|
default:
|
|
err = fmt.Errorf("unsupported plugin target %q", target)
|
|
}
|
|
if err != nil {
|
|
h.fail(err)
|
|
}
|
|
return h
|
|
}
|
|
|
|
func (s *Service) verifyAdditional(ctx context.Context, target, action, id string) error {
|
|
agent := s.agentOf(target)
|
|
if commandTarget(agent) {
|
|
return s.verifyNativeTarget(ctx, target, action, id)
|
|
}
|
|
if s.ProjectRoot != "" && !ProjectSupported(agent) {
|
|
return fmt.Errorf("%s project plugins are unsupported", target)
|
|
}
|
|
if !validTargetID(agent, id) {
|
|
return fmt.Errorf("invalid native plugin identifier")
|
|
}
|
|
if !slices.Contains([]string{"install", "update", "remove", "uninstall"}, action) {
|
|
return fmt.Errorf("unsupported plugin action %s", action)
|
|
}
|
|
if agent == "cursor" || agent == "antigravity" || agent == "opencode" {
|
|
return nil
|
|
}
|
|
command := action
|
|
if action == "remove" || action == "uninstall" {
|
|
command = "remove"
|
|
}
|
|
args := []string{command, "--help"}
|
|
_, err := s.run(ctx, target, args...)
|
|
return err
|
|
}
|
|
|
|
func (s *Service) applyAdditional(ctx context.Context, c Change, b Binding) error {
|
|
var root string
|
|
if (c.Action == "install" || c.Action == "update") && b.Source != "" {
|
|
snapshot, err := s.materialize(ctx, b, c.Target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d, err := discoverRoot(filepath.Join(snapshot, "content"), b.Source, b.Entry)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, candidate := range d.Candidates {
|
|
if candidate.Name == b.Plugin {
|
|
root = filepath.Join(snapshot, "content", candidate.pathFor(s.agentOf(c.Target)))
|
|
}
|
|
}
|
|
if root == "" {
|
|
return fmt.Errorf("plugin missing from snapshot")
|
|
}
|
|
}
|
|
if commandTarget(s.agentOf(c.Target)) {
|
|
return s.applyNativeTarget(ctx, c, b, root)
|
|
}
|
|
remove := c.Action == "remove" || c.Action == "uninstall"
|
|
switch s.agentOf(c.Target) {
|
|
case "cursor", "antigravity":
|
|
return s.applyLocal(c, b, root)
|
|
case "opencode":
|
|
return s.applyOpenCode(ctx, c, b)
|
|
case "pi":
|
|
if c.Action == "update" {
|
|
// An imported package updates natively; pi update keeps its settings entry.
|
|
// Local Pi packages load directly from the managed snapshot.
|
|
if root == "" {
|
|
if _, err := s.run(ctx, c.Target, "update", b.ID); err != nil {
|
|
return fmt.Errorf("Pi update failed: %w", err)
|
|
}
|
|
}
|
|
} else {
|
|
if c.Action == "install" && b.PiRegistration != "" {
|
|
if err := s.restorePiRegistration(c, b); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
command := "install"
|
|
if remove {
|
|
command = "remove"
|
|
}
|
|
args := []string{command, b.ID}
|
|
if s.ProjectRoot != "" {
|
|
args = append(args, "--local")
|
|
}
|
|
if _, err := s.run(ctx, c.Target, args...); err != nil {
|
|
return fmt.Errorf("Pi operation failed; project packages require trust established in Pi: %w", err)
|
|
}
|
|
}
|
|
}
|
|
h := s.host(ctx, c.Target)
|
|
if h.Error != "" {
|
|
return fmt.Errorf("native verification failed: %s", h.Error)
|
|
}
|
|
for _, i := range h.Installed {
|
|
if i.ID == b.ID {
|
|
if remove {
|
|
return fmt.Errorf("plugin remains registered")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
}
|
|
if remove {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("plugin not found after native operation")
|
|
}
|
|
|
|
func fileURL(path string) string {
|
|
return (&url.URL{Scheme: "file", Path: filepath.ToSlash(path)}).String()
|
|
}
|