Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions cmd/thv/app/ai_plugin_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/stacklok/toolhive/pkg/plugins"
pluginclient "github.com/stacklok/toolhive/pkg/plugins/client"
"github.com/stacklok/toolhive/pkg/skills/lockfile"
)

// newAIPluginClient creates a new Plugins API HTTP client using default settings.
Expand Down Expand Up @@ -39,6 +40,36 @@ func completeAIPluginNames(cmd *cobra.Command, args []string, _ string) ([]strin
return names, cobra.ShellCompDirectiveNoFileComp
}

// completePluginLockNames provides shell completion for plugin names present
// in the project's lock file, which is what `thv ai-plugin upgrade` acts on.
func completePluginLockNames(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
projectRoot, err := resolveProjectRoot(aiPluginUpgradeProjectRoot)
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
root, err := lockfile.OpenRoot(projectRoot)
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
lf, err := lockfile.Load(root)
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}

requested := make(map[string]struct{}, len(args))
for _, a := range args {
requested[a] = struct{}{}
}
names := make([]string, 0, len(lf.Plugins))
for _, e := range lf.Plugins {
if _, dup := requested[e.Name]; dup {
continue
}
names = append(names, e.Name)
}
return names, cobra.ShellCompDirectiveNoFileComp
}

// formatAIPluginError wraps an error with contextual information, appending a
// hint that matches the actual failure — a timed-out request and an absent
// server need different advice.
Expand Down
171 changes: 171 additions & 0 deletions cmd/thv/app/ai_plugin_upgrade.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

package app

import (
"encoding/json"
"fmt"

"github.com/spf13/cobra"

"github.com/stacklok/toolhive/pkg/plugins"
)

var (
aiPluginUpgradeProjectRoot string
aiPluginUpgradeClientsRaw string
aiPluginUpgradePreview bool
aiPluginUpgradeFailOnChanges bool
aiPluginUpgradeAllowRefChange bool
aiPluginUpgradeYes bool
aiPluginUpgradeFormat string
)

var aiPluginUpgradeCmd = &cobra.Command{
Use: "upgrade [plugin-name...]",
Short: "Upgrade project plugins to newer pinned content",
Long: `Re-resolve a project's lock entries and install newer content where available.

Plugins pinned to an immutable reference (an OCI digest or a full git commit
hash) are reported not-upgradable — there is nothing newer to resolve to.
Use --preview to see what would change without persisting anything (OCI
sources are still fetched into the local artifact store to compare digests),
and --allow-ref-change to permit the artifact moving to a different
repository (a version bump within the same repository is not a change
this guard blocks).
--fail-on-changes evaluates the same plan and never installs: it is a CI
freshness gate.

Unless --preview is set, upgrade prompts for confirmation before installing —
plugin content is a set of AI-followed instructions. Pass --yes to skip the
prompt (required in non-interactive contexts such as CI).

Requires TOOLHIVE_PLUGINS_LOCK_ENABLED=true.`,
PreRunE: chainPreRunE(
ValidateFormat(&aiPluginUpgradeFormat),
),
ValidArgsFunction: completePluginLockNames,
RunE: aiPluginUpgradeCmdFunc,
}
Comment thread
JAORMX marked this conversation as resolved.
Comment thread
JAORMX marked this conversation as resolved.

func init() {
aiPluginCmd.AddCommand(aiPluginUpgradeCmd)

aiPluginUpgradeCmd.Flags().StringVar(&aiPluginUpgradeProjectRoot, "project-root", "",
"Project root path (default: auto-detected from the current directory)")
aiPluginUpgradeCmd.Flags().StringVar(&aiPluginUpgradeClientsRaw, "clients", "",
`Comma-separated target client apps (e.g. claude-code,opencode), or "all" for every available client`)
aiPluginUpgradeCmd.Flags().BoolVar(&aiPluginUpgradePreview, "preview", false,
"Report what would change without persisting anything (OCI sources are still fetched to compare digests)")
aiPluginUpgradeCmd.Flags().BoolVar(&aiPluginUpgradeFailOnChanges, "fail-on-changes", false,
"Report what would change without installing anything; a CI freshness gate")
aiPluginUpgradeCmd.Flags().BoolVar(&aiPluginUpgradeAllowRefChange, "allow-ref-change", false,
"Permit the artifact to move to a different repository during upgrade")
aiPluginUpgradeCmd.Flags().BoolVar(&aiPluginUpgradeYes, "yes", false,
"Skip the confirmation prompt (required when not running interactively)")
AddFormatFlag(aiPluginUpgradeCmd, &aiPluginUpgradeFormat)
}

func aiPluginUpgradeCmdFunc(cmd *cobra.Command, args []string) error {
projectRoot, err := resolveProjectRoot(aiPluginUpgradeProjectRoot)
if err != nil {
return err
}

if !aiPluginUpgradePreview && !aiPluginUpgradeFailOnChanges {
if !aiPluginUpgradeYes {
printPluginLockEntriesSummary(projectRoot)
}
confirmed, confirmErr := requireConfirmation("Upgrade plugins for "+projectRoot, aiPluginUpgradeYes)
if confirmErr != nil {
return confirmErr
}
if !confirmed {
fmt.Println("Upgrade cancelled.")
return nil
}
}

c := newAIPluginClient(cmd.Context())
result, err := c.Upgrade(cmd.Context(), plugins.UpgradeOptions{
ProjectRoot: projectRoot,
Names: args,
Clients: parseSkillInstallClients(aiPluginUpgradeClientsRaw),
Preview: aiPluginUpgradePreview,
FailOnChanges: aiPluginUpgradeFailOnChanges,
AllowRefChange: aiPluginUpgradeAllowRefChange,
})
if err != nil {
return formatAIPluginError("upgrade plugins", err)
}

planOnly := aiPluginUpgradePreview || aiPluginUpgradeFailOnChanges
if err := printPluginUpgradeResult(result, aiPluginUpgradeFormat, planOnly); err != nil {
return err
}
return pluginUpgradeExitError(result, aiPluginUpgradePreview, aiPluginUpgradeFailOnChanges)
}

func pluginUpgradeExitError(result *plugins.UpgradeResult, preview, failOnChanges bool) error {
tally := tallyUpgradeOutcomes(result)
failed, refBlocked, wouldChange := tally.failed, tally.refBlocked, tally.wouldChange
if failed > 0 {
return withExitCode(fmt.Errorf("upgrade failed for %d plugin(s)", failed), ExitCodePartialFailure)
}
if failOnChanges && wouldChange > 0 {
return withExitCode(
fmt.Errorf("%d plugin(s) would change; the lock file is stale", wouldChange),
ExitCodeCheckFailure,
)
}
if !preview && !failOnChanges && refBlocked > 0 {
return withExitCode(
fmt.Errorf("%d plugin(s) blocked by a repository change; use --allow-ref-change", refBlocked),
ExitCodePolicyRejection,
)
}
return nil
}

func printPluginUpgradeResult(result *plugins.UpgradeResult, format string, planOnly bool) error {
if format == FormatJSON {
data, err := json.MarshalIndent(result, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
fmt.Println(string(data))
return nil
}

if len(result.Outcomes) == 0 {
fmt.Println("No plugins in the project's lock file")
return nil
}
upgradedVerb := "upgraded"
if planOnly {
upgradedVerb = "would upgrade"
}
for _, o := range result.Outcomes {
switch o.Status {
case plugins.UpgradeStatusUpgraded:
fmt.Printf("%s: %s %s -> %s\n", o.Name, upgradedVerb, o.OldDigest, o.NewDigest)
case plugins.UpgradeStatusUpToDate:
fmt.Printf("%s: up to date\n", o.Name)
case plugins.UpgradeStatusNotUpgradable:
fmt.Printf("%s: not upgradable (pinned to an immutable reference)\n", o.Name)
case plugins.UpgradeStatusRefChangeBlocked:
fmt.Printf("%s: repository change blocked (would move to %s; use --allow-ref-change)\n",
o.Name, o.NewResolvedReference)
case plugins.UpgradeStatusSignerChangeBlocked:
newSigner := o.NewSignerIdentity
if newSigner == "" {
newSigner = "unsigned"
}
fmt.Printf("%s: signer change blocked (candidate is %s; use --allow-signer-change)\n", o.Name, newSigner)
case plugins.UpgradeStatusFailed:
fmt.Printf("%s: failed [%s]: %s\n", o.Name, o.Reason, o.Error)
}
}
return nil
}
1 change: 1 addition & 0 deletions docs/cli/thv_ai-plugin.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

62 changes: 62 additions & 0 deletions docs/cli/thv_ai-plugin_upgrade.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading