mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
* fix(plugins): separate shared intent from machine-local receipts Shared configs currently carry native paths, reviewed snapshots and pending failures, so one host can publish local progress over another host's target selection. Persist versioned declarations separately from local applied and pending receipts, and reconcile reviewed installs, imports and cleanup against this machine's native inventory without rewriting intent during sync/update. Keep snapshot names and adapter safeguards, move the operation lock locally, validate legacy adoption with local evidence, and invalidate approval on local state or native-context changes. Preserve source recipes after native adoption, require local import for absent native-only targets, and document the shared writer upgrade boundary in schemas and translated references. Cover two-host behavior, generated legacy fixtures, failure/recovery, stale intent, cleanup, npm recipes and the existing CLI/API/UI consumers with focused resource-capped tests. Fixes #651. * fix(plugins): preserve intent and ownership across host transitions Repeat-add must retain shared target selection, and update previews must resolve the requested ref before reviewing fresh or replacement installs. Keep disabled targets on the uninstall path and reject refs unsupported by native-only/npm intent before they can produce invalid shared declarations. Block changed-context add/import before Pi registration preparation so a new account cannot overwrite the old receipt. Preserve unresolved legacy bindings as passive private proof candidates before rewriting shared YAML, retaining original intent/store for later verified adoption and cleanup. Never compose these hints as executable state, and persist their explicit resolution. Cover the five review classes, native/private failure boundaries, requested-ref retry, and original-context hint proofs with isolated focused regressions. Keep local format v1 and baseline account validation unchanged. Refs #651. * fix(plugins): allow receipt-only orphan cleanup to complete An installation already removed on this host can retain a local receipt when another host removes or replaces shared intent. Sync correctly plans forget, but native command verification rejects that metadata-only action and blocks all targets before the receipt can be cleared. Exclude forget from native command verification while retaining host inventory checks and OMP scoped cleanup preparation. The existing completion path then persists receipt deletion, including pending work and passive legacy hints. Cover the cross-host disable/re-enable/remove walk, five native adapters, failed work with a legacy hint, and absent source replacement alongside a healthy target. Assert Apply completion, unchanged shared bytes/mtime, and a quiet second sync. Refs #651. * fix(plugin): reconcile ref intent across inventory consumers Validate explicit ref changes before disabled targets can save them and reuse one reviewed discovery throughout a preview. Surface shared ref changes as local reconciliation work while preserving the applied native identity and receipts. Reuse scoped legacy proofs for Pi extension ownership and make full inventory the dashboard's authoritative package/host pair. Cover invalid and replacement refs, read-only ownership, and shared-state properties without new persisted state or dependencies. * test(plugin): repair and consolidate host-state fixtures Create source intent and a pending imported Claude update through supported operations so direct and batch updates exercise the intended fixture. Keep the marketplace-loss case locally owned before testing its skipped reinstall. Consolidate cross-host repeat-add and requested-ref replacement/orphan retries at their existing owners, retaining failure recovery and shared-byte checks. Trim duplicate HTTP and translated-text assertions from consumer tests. * fix(plugin): reconcile legacy snapshot reads and native imports Resolve legacy snapshot ownership through existing scoped proofs before listing, reading or discovering cached source files. Keep adoption read-only and limit proof work to the requested package and targets; current receipts need no CLI. Only preserve reviewed source metadata on reimport when intent remains source managed. Native-only intent must not resurrect an older Git source after a same-ID local import. Retain identity mismatch and reviewed-source safeguards. Remove the unused source-folding helper left by the old shared runtime writer. * Preserve reviewed package versions locally * Fix reviewed package version lifecycle * fix(plugin): report missing local imports in doctor Show the local-import instruction instead of claiming a skipped imported plugin is healthy. Preserve the missing-CLI warning and shared config bytes. Keep fixture native settings inside scratch XDG directories and serialize the fake CLI calls used by concurrent inventories. Update assertions to separate shared declarations from local versions and native IDs, and align the raw-write audit with private plugin state and operation locks. * test(plugin): use declarations for doctor source fixture The missing-CLI case has no native ID, so encode it with the version 2 declaration schema. Keep the native-only import case in legacy syntax. * fix(plugin): install shared sources from reviewed snapshots When a source target is already declared, first sync must install its reviewed local snapshot even if the native client has a package from the same marketplace. Keep explicit add adoption and native-only import intact. Extend the existing two-host adoption check to cover an independent native installation on the second host and verify a quiet subsequent sync. * fix(plugin): preserve reviewed retries and native collision boundaries Retry a pending source update through the existing reviewed update path, so a rolled-back native failure cannot clear progress at the old snapshot. Record default-source versions for add, sync, and update while retaining the recipe fingerprint and generic-version checks for target overrides. Keep explicit native adoption, but block shared Claude sources when an independent same-name native plugin could shadow their hooks. Extract the existing adoption decision so the preview function becomes smaller. * test(plugin): respect OMP update safety in version control Check generic and target versions during review, then confirm the existing OMP upgrade guard preserves the installed and default-source versions. * fix(plugin): declare first local native imports explicitly A first local import into a shared source target now changes that target to native-only intent while preserving its sync selection. Verified source reimports retain their reviewed source and the preview discloses conversion. Cover the explicit import, local sync, and other-host cleanup flow, and remove the unconsumed internal observation assertion from the OMP test. * docs(plugin): explain first local import intent changes Describe the shared native-only target conversion and its effect on other machines, while distinguishing verified source reimports. * fix(plugin): verify checked sources before native reinstalls A checked update that becomes an install after native removal must still match the source digest the user approved. Reject moved or unchecked sources before native work, and allow a stable approved reinstall. Clear completed reinstalls from dashboard update availability while keeping failed targets available for retry. Cover both native presence states in the existing checked-update tests and the dashboard outcome rule. * fix(plugin): guard replacement before cleanup * fix(plugin): refresh discovery for each manager action A later Add action must review the current source even when the manager previously observed that source. Keep discovery sharing across one action while ending its cache before the next wizard invocation. Exercise a fresh source version after an earlier Add preview without TTY input or native writes, using an unavailable client to stop at review. * test(plugin): cover desired checks and final update outcomes Consolidate checked batch approval and dashboard completion tests while retaining removed-native, digest, version and approval controls. Reproduce stale shared recipes and failed or unfinished replacement installs. * test(plugin): make stale source discovery observable Remove the old repository before native-only and npm desired checks so those existing cases cannot pass by reading the applied source. * fix(plugin): check desired source and final outcome * test(plugin): bind checked updates to the observed recipe Reproduce a shared candidate change with equal version, commit and digest, and preserve a freshly checked replacement whose native ID differs. Use actual check observations in approval and native update controls, reject missing source identity, and verify the UI carries the observation through. * fix(plugin): bind checked update to source recipe * fix(ui): classify npm recipes as Pi packages * fix(plugin): retain legacy removal intent during migration Omit pending removals from shared declarations while retaining original local ownership proof so sync retries cleanup. Verification: focused regression passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4). * fix(plugin): keep imports local to an existing shared recipe Adopt a native installation into its local receipt without converting the shared source target or removing other machines installations. Verification: focused import regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4). * fix(plugin): capture legacy evidence on first read Persist passive hints before another machine writes v2 and save verified adoption on reads. Apply reuses preview receipts instead of querying every legacy binding again. Document the per-machine pre-migration read. Verification: migration regressions passed in isolated Linux Codex container runs, not the devcontainer (GOMAXPROCS=4, -p=4). * fix(plugin): target named declarations in interactive imports Offer unresolved package names in dashboard and TUI imports and pass the selected name in single and batch requests. Drop display-only rendered assertions. Verification: 47 UI tests passed with at most four workers in an isolated Linux Codex container, not the devcontainer. * fix(plugin): localize shared intent plan guidance Add message keys for local imports, account changes, cleanup and native collisions across all dashboard locales. Localized guidance contains no CLI flags. Verification: failing localization regression now passes in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4). * refactor(plugin): reuse preview inventory and guard apply boundaries Capture hints on first load without persisting in-memory adoption during preview, keeping approval revisions stable. Apply reuses preview inventory. Reuse accountEnv and guard applyChange plus native write boundaries without inspecting argv. Verification: migration, receipt, account and sync regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4). * test(plugin): organize host state coverage around lifecycle scenarios Group migration, ref drift, account context and cleanup tests behind shared host fixtures and public Preview/Apply assertions. Cover Codex, Cursor, Antigravity and project scopes; add second-machine doctor coverage and the two-machine runbook. Consolidate package-version tests and remove the unused private-record fixture. Verification: focused plugin regressions passed in an isolated Linux Codex container, not the devcontainer (GOMAXPROCS=4, -p=4). * docs(plugin): explain local imports and per-machine migration Document local receipts, per-machine review and commit pinning, config-path state identity and the required legacy read on every machine. Align sharing, doctor, troubleshooting, file-layout and four translated plugin references; restore schema editing guidance. Verification: context-router check passed. Runtime verification uses an isolated Linux Codex container, not the devcontainer. * refactor(plugin): separate unrelated review scope Move project OMP configuration, plugin list ordering, and npm Pi classification to independent local branches based on upstream/main. Keep the shared intent change focused and cover named import selection in the pure flow helper. The three local branches have passing builds in a Linux Codex container, not the devcontainer, with isolated test homes and capped parallelism. * perf(plugin): avoid recapturing v2 state on reads Only compare and persist passive migration hints when legacy bindings exist. Native v2 reads need no state serialization for migration. Verification: pending removal and first-read/import regressions passed in a Linux Codex container, not the devcontainer, with isolated HOME/XDG/TMPDIR and GOMAXPROCS=4 GOFLAGS=-p=4. * docs(plugin): clarify native marketplace repair after import A local import receipt is not a reviewed reinstall source. Correct the remaining troubleshooting instruction and its four translations to require native-client repair, and align the nearby code comment. Validation: checked against prepareChange, context-router check and git diff --check passed. Verification for this review ran in a Linux Codex container, not the devcontainer. * fix(plugins): preserve local ownership across shared intent changes Retain completed legacy migration markers so unchanged v1 YAML cannot uninstall a later manual reinstall. Serialize read-side hint persistence with native operations and keep local imports when shared recipes change. Require explicit dashboard import names and validate recipe identities. Correct schema descriptions, messages, CLI ref status, translated migration guidance and runbooks. Add failing-first Preview/Apply regressions and a real two-ssenv CLI lifecycle script. * fix(plugins): preserve migration history and show retained import guidance Mark existing legacy hints and receipts as captured before cleanup so state from the previous serializer cannot re-adopt a later manual installation. Keep recipe-change guidance in unchanged sync outcomes and visible dashboard rows, and resolve nested OpenCode entries through their package manifest. Cover public migration, ref, account, import and message contracts across adapters. Correct the real two-host Cursor assertions, explicit dashboard selection flow, and remaining localized guidance. * fix(plugins): retain explicit OpenCode entry during import matching Standalone OpenCode packages can rely on a reviewed explicit entry rather than an SDK dependency. Preserve that entry when reading native package identity so matching nested imports remain supported. * fix(plugins): preserve migrated imports and verify native entry identity Recognize older native-only receipts by their existing declaration fingerprint so remote source recipe edits cannot replace migrated imports. Keep managed npm receipts distinct through their source fingerprints. Only borrow an ancestor OpenCode package identity when its resolved entry is the actual registered file. Retain nested and explicit entry support. Add public two-host migration and mismatching-entry regressions. * fix(plugins): retain imported ownership through repeated adds Persist inferred imported ownership when a matching add refreshes the receipt intent, so later shared recipe changes still preserve local native installations. Keep the legacy replacement regression aligned with that ownership contract while retaining removed-intent cleanup. Reject missing or unstatable absolute OpenCode entries before identity matching rather than falling back to the file name. Cover both paths through public Preview and Apply regressions. * test(plugins): isolate OpenCode adapter fixtures from host config Keep native registration fixtures inside their fake agent home by setting XDG_CONFIG_HOME and clearing inherited OpenCode overrides. Ambient config writes can otherwise leak into config-discovery tests in other packages. Cover the XDG, file, directory and inline override cases with temporary config sentinels, while retaining the existing MCP listing expectation. * fix(plugin): let local imports return to the shared source Add a local unimport action that removes only this machine’s installation and receipt while preserving the shared source declaration. Keep retained-import guidance visible across matching adds, list, doctor and dashboard consumers. Avoid idle OMP guidance and unchanged legacy-read locks, preserve localized errors, keep import identity checks offline, and normalize OpenCode drive URLs. Cover the A/B transition and align translations, runbooks and environment cleanup. * fix(plugin): complete unimport validation and guidance Reject missing targets before planning local unimports and share per-target eligibility with the wizard. Make native uninstall effects explicit in help and translated docs, preserve structured update guidance, and cover error paths and shell completion.
382 lines
13 KiB
Go
382 lines
13 KiB
Go
package plugin
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// ErrCLIMissing marks the one host failure fixed by installing something rather than
|
|
// by opening the Agent. Hosts carrying it are grouped together in the dashboard, so the
|
|
// same sentence is not repeated once per Agent.
|
|
var ErrCLIMissing = errors.New("native CLI not on PATH")
|
|
|
|
// agentError names a fixed failure template so the dashboard can show it in the reader's
|
|
// language. message stays the English the CLI prints and is the fallback; cause is
|
|
// ErrCLIMissing when installing something, not opening the Agent, is the remedy. args fill
|
|
// the {placeholders} of the translated sentence, for the part only known at runtime.
|
|
type agentError struct {
|
|
cause error
|
|
key string
|
|
message string
|
|
args map[string]string
|
|
}
|
|
|
|
func (e agentError) Error() string { return e.message }
|
|
func (e agentError) Unwrap() error { return e.cause }
|
|
|
|
// ErrorKey is the translation key and arguments of a fixed failure, "" when the message
|
|
// was assembled at runtime.
|
|
func ErrorKey(err error) (string, map[string]string) {
|
|
var keyed agentError
|
|
if errors.As(err, &keyed) {
|
|
return keyed.key, keyed.args
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
// gitFailure sorts a git failure by the words in its stderr, so the dashboard can say
|
|
// whether the network or the source is at fault. Only the key leaves this function:
|
|
// stderr can echo a URL with credentials. LC_ALL=C keeps the words English.
|
|
func gitFailure(stderr string) (agentError, bool) {
|
|
lower := strings.ToLower(stderr)
|
|
// GitHub asks for a username when the repository does not exist or is private. A bare
|
|
// "not found" is not enough: a missing git-lfs says "command not found".
|
|
missing := strings.Contains(lower, "fatal: repository '") && strings.Contains(lower, "' not found")
|
|
for _, s := range []string{"repository not found", "does not appear to be a git repository", "couldn't find remote ref", "returned error: 404", "could not read username"} {
|
|
missing = missing || strings.Contains(lower, s)
|
|
}
|
|
if missing {
|
|
return agentError{key: "plugins.error.sourceNotFound", message: "plugin source not found; check the repository address and branch"}, true
|
|
}
|
|
// Not "unable to access": git opens every HTTPS failure with it, a bad certificate or a
|
|
// 403 included, and those are not the network's fault.
|
|
for _, s := range []string{"could not resolve host", "failed to connect", "connection timed out", "connection refused", "operation timed out", "network is unreachable", "resolving timed out"} {
|
|
if strings.Contains(lower, s) {
|
|
return agentError{key: "plugins.error.network", message: "could not reach the plugin source; check the network connection and try again"}, true
|
|
}
|
|
}
|
|
return agentError{}, false
|
|
}
|
|
|
|
// missingPath reports whether bin is a path that does not exist, which is as missing as a
|
|
// name not on PATH. A missing working directory fails with the same error, so check bin.
|
|
func missingPath(bin string, err error) bool {
|
|
if !filepath.IsAbs(bin) || !errors.Is(err, os.ErrNotExist) {
|
|
return false
|
|
}
|
|
_, statErr := os.Stat(bin)
|
|
return errors.Is(statErr, os.ErrNotExist)
|
|
}
|
|
|
|
func runCommand(ctx context.Context, dir string, env []string, bin string, args ...string) ([]byte, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, bin, args...)
|
|
cmd.Dir = dir
|
|
// No shell, inherited stdin, or automatic native trust/command confirmation.
|
|
cmd.Env = append(append(os.Environ(), "GIT_TERMINAL_PROMPT=0"), env...)
|
|
if bin == "git" {
|
|
cmd.Env = append(cmd.Env, "LC_ALL=C")
|
|
}
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
if err := cmd.Run(); err != nil {
|
|
if errors.Is(err, exec.ErrNotFound) || missingPath(bin, err) {
|
|
return nil, agentError{cause: ErrCLIMissing, key: "plugins.error.cliMissing", message: fmt.Sprintf("%s CLI is not installed or not on PATH on the machine running Skillshare; install it there before syncing plugins", bin)}
|
|
}
|
|
if ctx.Err() != nil {
|
|
return nil, agentError{key: "plugins.error.timeout", message: fmt.Sprintf("%s timed out or was cancelled; inspect native status before retrying", bin)}
|
|
}
|
|
if bin == "git" {
|
|
if failure, ok := gitFailure(stderr.String()); ok {
|
|
return nil, failure
|
|
}
|
|
}
|
|
// Native output can contain credentials or command-source scripts.
|
|
return nil, agentError{key: "plugins.error.commandFailed", message: fmt.Sprintf("%s command failed; open the native client to resolve authentication, trust, or configuration", bin)}
|
|
}
|
|
// Some CLIs (Pi) print their version to stderr.
|
|
if stdout.Len() == 0 && slices.Equal(args, []string{"--version"}) {
|
|
return stderr.Bytes(), nil
|
|
}
|
|
return stdout.Bytes(), nil
|
|
}
|
|
|
|
func (s *Service) run(ctx context.Context, target string, args ...string) ([]byte, error) {
|
|
run := s.Run
|
|
if run == nil {
|
|
run = runCommand
|
|
}
|
|
dir := s.ProjectRoot
|
|
if dir == "" {
|
|
var err error
|
|
dir, err = os.UserHomeDir()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
// An account runs its Agent's CLI against the account's own config directory.
|
|
var env []string
|
|
bin := s.agentOf(target)
|
|
if bin == "antigravity-cli" {
|
|
bin = "agy"
|
|
}
|
|
explicit := false
|
|
if account, ok := s.account(target); ok {
|
|
env = account.env()
|
|
if account.CLI != "" {
|
|
bin, explicit = account.CLI, true
|
|
}
|
|
}
|
|
// Only the default codex is searched for; an account's cli, even "codex", is kept.
|
|
if bin != "codex" || explicit {
|
|
return run(ctx, dir, env, bin, args...)
|
|
}
|
|
find := s.findCodex
|
|
if find == nil {
|
|
find = newCodexFinder().find
|
|
}
|
|
bin, looked := find()
|
|
out, err := run(ctx, dir, env, bin, args...)
|
|
if errors.Is(err, ErrCLIMissing) {
|
|
where := strings.Join(looked, ", ")
|
|
return nil, agentError{cause: ErrCLIMissing, key: "plugins.error.codexMissing", args: map[string]string{"looked": where},
|
|
message: fmt.Sprintf("Codex CLI not found on the machine running Skillshare (looked in: %s); install it there, or set %s to its path", where, codexCLIEnv)}
|
|
}
|
|
return out, err
|
|
}
|
|
|
|
func parseInventory(target string, data []byte, project string) ([]Installed, error) {
|
|
if target == "omp" {
|
|
return parseOMPInventory(data, project)
|
|
}
|
|
result := []Installed{}
|
|
if target == "codex" {
|
|
var envelope struct {
|
|
Installed json.RawMessage `json:"installed"`
|
|
}
|
|
if json.Unmarshal(data, &envelope) != nil || len(envelope.Installed) == 0 {
|
|
return nil, fmt.Errorf("unrecognized Codex plugin list schema")
|
|
}
|
|
if err := json.Unmarshal(envelope.Installed, &result); err != nil {
|
|
return nil, fmt.Errorf("invalid Codex installed list")
|
|
}
|
|
for i := range result {
|
|
r := &result[i]
|
|
r.ID = r.PluginID
|
|
if r.ID == "" && r.Name != "" && r.Marketplace != "" {
|
|
r.ID = r.Name + "@" + r.Marketplace
|
|
}
|
|
r.Scope = "user"
|
|
}
|
|
} else {
|
|
if err := json.Unmarshal(data, &result); err != nil || result == nil {
|
|
return nil, fmt.Errorf("unrecognized Claude plugin list schema")
|
|
}
|
|
}
|
|
filtered := []Installed{}
|
|
for _, item := range result {
|
|
item.EnabledKnown = true
|
|
// Filter by scope before validating: Claude also lists other scopes' plugins
|
|
// (e.g. "(suppressed)@skills-dir" for the folder it runs in), and an entry this
|
|
// scope never uses must not block the whole target.
|
|
if target == "claude" {
|
|
if project == "" && item.Scope != "user" {
|
|
continue
|
|
}
|
|
if project != "" && (item.Scope != "project" || filepath.Clean(item.ProjectPath) != filepath.Clean(project)) {
|
|
continue
|
|
}
|
|
}
|
|
if !validID(item.ID) {
|
|
return nil, fmt.Errorf("native plugin list contains an unsupported plugin identifier")
|
|
}
|
|
filtered = append(filtered, item)
|
|
}
|
|
return filtered, nil
|
|
}
|
|
|
|
func validID(id string) bool {
|
|
name, market, ok := strings.Cut(id, "@")
|
|
return ok && namePattern.MatchString(name) && namePattern.MatchString(market)
|
|
}
|
|
|
|
func (s *Service) host(ctx context.Context, target string) Host {
|
|
agent := s.agentOf(target)
|
|
if !marketplaceAgent(agent) {
|
|
return s.additionalHost(ctx, target)
|
|
}
|
|
h := Host{Target: target, Status: HostReady, Installed: []Installed{}}
|
|
if agent == "codex" && s.ProjectRoot != "" {
|
|
h.block("plugins.error.userScoped", "Codex native plugin installation is user-scoped; use global mode. Project operations never fall back to global.")
|
|
return h
|
|
}
|
|
if agent == "omp" {
|
|
if key, message := s.ompHostProblem(); key != "" {
|
|
h.block(key, message)
|
|
return h
|
|
}
|
|
h.NoteKey, h.Note = "plugins.note.omp", "Marketplace plugins only; npm, Git and linked plugins are installed by bun and stay managed in omp. OMP loads plugin extension modules in-process when it starts."
|
|
}
|
|
version, err := s.run(ctx, target, "--version")
|
|
if err != nil {
|
|
h.fail(err)
|
|
return h
|
|
}
|
|
h.Version = strings.TrimSpace(string(version))
|
|
data, err := s.run(ctx, target, "plugin", "list", "--json")
|
|
if err != nil {
|
|
h.fail(err)
|
|
return h
|
|
}
|
|
h.Installed, err = parseInventory(agent, data, s.ProjectRoot)
|
|
if err != nil {
|
|
h.fail(err)
|
|
return h
|
|
}
|
|
if agent == "omp" {
|
|
h.ompCacheRoot = ompDefaultCacheRoot()
|
|
}
|
|
// Marketplaces stays nil when the list cannot be read: planning then keeps a removal
|
|
// pending instead of guessing that nothing is left to clean up.
|
|
if markets, err := s.marketplaces(ctx, target); err == nil {
|
|
h.Marketplaces = markets
|
|
// omp has one marketplace registry for every scope and project, so a Skillshare
|
|
// marketplace is never counted as this configuration's to remove (see removeMarketplace).
|
|
if agent == "omp" {
|
|
return h
|
|
}
|
|
for name, root := range markets {
|
|
// A name also declared elsewhere ("") stays claimed, so removal reports the clash
|
|
// instead of forgetting the binding.
|
|
if strings.HasPrefix(name, "skillshare-") && (root == "" || filepath.Clean(root) == filepath.Join(s.managedRoot(), name)) {
|
|
h.ManagedMarketplaces = append(h.ManagedMarketplaces, name)
|
|
}
|
|
}
|
|
slices.Sort(h.ManagedMarketplaces)
|
|
}
|
|
return h
|
|
}
|
|
|
|
// Packages is the part of the inventory that config alone answers, so the dashboard can
|
|
// draw the plugin list while Inventory is still waiting on each Agent's CLI.
|
|
func (s *Service) Packages() (*Inventory, error) {
|
|
cfg, err := s.load()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Inventory{TargetDefinitions: s.TargetDefinitions(), Packages: cfg.packages, Hosts: []Host{}}, nil
|
|
}
|
|
|
|
func (s *Service) Inventory(ctx context.Context) (*Inventory, error) {
|
|
result, err := s.Packages()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Each Agent answers through its own CLI and none depends on another, so the slowest
|
|
// one sets the wait instead of the sum of all of them.
|
|
targets := s.targets()
|
|
result.Hosts = make([]Host, len(targets))
|
|
var wg sync.WaitGroup
|
|
for i, target := range targets {
|
|
wg.Go(func() { result.Hosts[i] = s.host(ctx, target) })
|
|
}
|
|
wg.Wait()
|
|
d, err := s.load()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.adoptLegacy(d, func(target string) Host {
|
|
for _, h := range result.Hosts {
|
|
if h.Target == target {
|
|
return h
|
|
}
|
|
}
|
|
return Host{Error: "inventory unavailable"}
|
|
})
|
|
result.Packages = d.packages
|
|
return result, nil
|
|
}
|
|
|
|
func (s *Service) nativeArgs(target, action, id string) ([]string, error) {
|
|
if action == "uninstall" {
|
|
action = "remove"
|
|
}
|
|
if !validID(id) {
|
|
return nil, fmt.Errorf("invalid plugin identity")
|
|
}
|
|
agent := s.agentOf(target)
|
|
if agent == "codex" {
|
|
if s.ProjectRoot != "" {
|
|
return nil, fmt.Errorf("Codex project plugin operations are unsupported")
|
|
}
|
|
switch action {
|
|
// Codex has no update command; add replaces an installed plugin with the
|
|
// marketplace's current copy.
|
|
case "install", "update":
|
|
return []string{"plugin", "add", id, "--json"}, nil
|
|
case "remove":
|
|
return []string{"plugin", "remove", id, "--json"}, nil
|
|
}
|
|
return nil, fmt.Errorf("Codex has no verified native %s command; manage this operation in Codex", action)
|
|
}
|
|
if agent != "claude" && agent != "omp" {
|
|
return nil, fmt.Errorf("unsupported plugin target %q", target)
|
|
}
|
|
if action == "install" || action == "update" || action == "remove" {
|
|
command := action
|
|
if action == "remove" {
|
|
command = "uninstall"
|
|
}
|
|
// omp has no update: upgrade reinstalls from the marketplace and keeps the plugin's
|
|
// enabled state, feature selection and settings.
|
|
if action == "update" && agent == "omp" {
|
|
command = "upgrade"
|
|
}
|
|
scope := "user"
|
|
if s.ProjectRoot != "" {
|
|
scope = "project"
|
|
}
|
|
args := []string{"plugin", command, id, "--scope", scope}
|
|
if (action == "install" || action == "update") && agent == "claude" {
|
|
args = append(args, "--json")
|
|
}
|
|
return args, nil
|
|
}
|
|
return nil, fmt.Errorf("unsupported plugin action %q", action)
|
|
}
|
|
|
|
func (s *Service) verifyCommand(ctx context.Context, target, action, id string) error {
|
|
if s.agentOf(target) == "omp" && (action == "remove" || action == "uninstall" || action == "forget") {
|
|
return nil // Scoped removal does not call OMP's destructive uninstall.
|
|
}
|
|
if !marketplaceAgent(s.agentOf(target)) {
|
|
return s.verifyAdditional(ctx, target, action, id)
|
|
}
|
|
args, err := s.nativeArgs(target, action, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
help, err := s.run(ctx, target, "plugin", args[1], "--help")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, flag := range args {
|
|
if strings.HasPrefix(flag, "--") && !strings.Contains(string(help), flag) {
|
|
return fmt.Errorf("installed %s does not support %s for %s; upgrade the native CLI", target, flag, action)
|
|
}
|
|
}
|
|
return nil
|
|
}
|