Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add CLI action capability discovery

rcourtmanf0bf88a89d20
diff --git a/docs/API.md b/docs/API.md
index 4d755dfa19..0a4f852a97 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -145,6 +145,10 @@ This endpoint is API-first and plan-only: it resolves the resource from the unif
CLI adapter:
```bash
+PULSE_API_TOKEN=your-token pulse actions capabilities \
+ --api-url http://localhost:7655 \
+ --resource-id vm:42
+
PULSE_API_TOKEN=your-token pulse actions plan \
--api-url http://localhost:7655 \
--request-id agent-run-123 \
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 50b0a2ece8..f53ca29efd 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -288,7 +288,10 @@ the canonical monitored-system blocked payload.
by `pkg/pulsecli/actions.go` and registered from `pkg/pulsecli/root.go`.
It must remain a thin authenticated client for `POST /api/actions/plan`
rather than importing planner internals, creating action IDs, or approving
- and executing capabilities locally.
+ and executing capabilities locally. `pulse actions capabilities` may read
+ the canonical `GET /api/resources/{id}/facets` payload to discover resource
+ capability names and parameter schemas before planning, but it must not
+ invent a parallel capability inventory or expose internal handler names.
6. Route dedicated unified-resource timeline and facet-bundle reads through `frontend-modern/src/api/resources.ts`, `internal/api/resources.go`, and `internal/api/contract_test.go` together so the backend facet contract and the frontend client stay aligned on one timeline-first surface, while capability and relationship detail stays backend-owned for AI correlation and change detection.
`/api/resources/{id}/timeline` and `/api/resources/{id}/facets` must keep
resource timelines relationship-aware by opting into the canonical
diff --git a/pkg/pulsecli/actions.go b/pkg/pulsecli/actions.go
index e22ee48430..4c25d5e8b1 100644
--- a/pkg/pulsecli/actions.go
+++ b/pkg/pulsecli/actions.go
@@ -43,10 +43,27 @@ type actionPlanOptions struct {
Params []string
}
+type actionCapabilitiesOptions struct {
+ APIURL string
+ Token string
+ ResourceID string
+}
+
+type actionCapabilitiesResponse struct {
+ ResourceID string `json:"resourceId"`
+ Count int `json:"count"`
+ Capabilities []unified.ResourceCapability `json:"capabilities"`
+}
+
+type actionResourceFacetsResponse struct {
+ ResourceID string `json:"resourceId"`
+ Capabilities []unified.ResourceCapability `json:"capabilities,omitempty"`
+}
+
func newActionsCmd(deps *ActionsDeps) *cobra.Command {
actionsCmd := &cobra.Command{
Use: "actions",
- Short: "Plan governed Pulse actions",
+ Short: "Inspect and plan governed Pulse actions",
}
opts := actionPlanOptions{
@@ -77,9 +94,32 @@ func newActionsCmd(deps *ActionsDeps) *cobra.Command {
planCmd.Flags().StringArrayVar(&opts.Params, "param", nil, "request param as key=value; repeatable, values parse as JSON when possible")
actionsCmd.AddCommand(planCmd)
+ actionsCmd.AddCommand(newActionCapabilitiesCmd(deps))
return actionsCmd
}
+func newActionCapabilitiesCmd(deps *ActionsDeps) *cobra.Command {
+ opts := actionCapabilitiesOptions{
+ APIURL: strings.TrimSpace(actionGetenv(deps, "PULSE_API_URL")),
+ Token: strings.TrimSpace(actionGetenv(deps, "PULSE_API_TOKEN")),
+ }
+ if opts.APIURL == "" {
+ opts.APIURL = defaultActionsAPIURL
+ }
+
+ cmd := &cobra.Command{
+ Use: "capabilities",
+ Short: "List capabilities advertised by a unified resource",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return runActionCapabilities(cmd, deps, opts)
+ },
+ }
+ cmd.Flags().StringVar(&opts.APIURL, "api-url", opts.APIURL, "Pulse server URL or /api base URL")
+ cmd.Flags().StringVar(&opts.Token, "token", opts.Token, "Pulse API token; defaults to PULSE_API_TOKEN")
+ cmd.Flags().StringVar(&opts.ResourceID, "resource-id", "", "canonical unified resource id")
+ return cmd
+}
+
func runActionPlan(cmd *cobra.Command, deps *ActionsDeps, opts actionPlanOptions) error {
token := strings.TrimSpace(opts.Token)
if token == "" {
@@ -120,7 +160,7 @@ func runActionPlan(cmd *cobra.Command, deps *ActionsDeps, opts actionPlanOptions
return fmt.Errorf("failed to read action plan response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return actionStatusError(resp.Status, respBody)
+ return actionStatusError("action plan request", resp.Status, respBody)
}
var plan unified.ActionPlan
@@ -136,6 +176,69 @@ func runActionPlan(cmd *cobra.Command, deps *ActionsDeps, opts actionPlanOptions
return nil
}
+func runActionCapabilities(cmd *cobra.Command, deps *ActionsDeps, opts actionCapabilitiesOptions) error {
+ token := strings.TrimSpace(opts.Token)
+ if token == "" {
+ return fmt.Errorf("api token is required (use --token or PULSE_API_TOKEN)")
+ }
+
+ resourceID := unified.CanonicalResourceID(opts.ResourceID)
+ if resourceID == "" {
+ return fmt.Errorf("resourceId is required (use --resource-id)")
+ }
+
+ endpoint, err := actionResourceFacetsEndpoint(opts.APIURL, resourceID)
+ if err != nil {
+ return err
+ }
+
+ httpReq, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, endpoint, nil)
+ if err != nil {
+ return fmt.Errorf("failed to build action capabilities request: %w", err)
+ }
+ httpReq.Header.Set("Accept", "application/json")
+ httpReq.Header.Set("Authorization", "Bearer "+token)
+
+ resp, err := actionHTTPClient(deps).Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("action capabilities request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ respBody, err := ReadBoundedHTTPBody(resp.Body, resp.ContentLength, maxActionPlanResponseBytes, "action capabilities response")
+ if err != nil {
+ return fmt.Errorf("failed to read action capabilities response: %w", err)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return actionStatusError("action capabilities request", resp.Status, respBody)
+ }
+
+ var facets actionResourceFacetsResponse
+ if err := decodeJSONBytes(respBody, &facets); err != nil {
+ return fmt.Errorf("failed to decode action capabilities response: %w", err)
+ }
+ output := actionCapabilitiesResponse{
+ ResourceID: resourceID,
+ Capabilities: facets.Capabilities,
+ Count: len(facets.Capabilities),
+ }
+ if strings.TrimSpace(facets.ResourceID) != "" {
+ if canonical := unified.CanonicalResourceID(facets.ResourceID); canonical != "" {
+ output.ResourceID = canonical
+ }
+ }
+ if output.Capabilities == nil {
+ output.Capabilities = []unified.ResourceCapability{}
+ }
+
+ encoder := json.NewEncoder(cmd.OutOrStdout())
+ encoder.SetIndent("", " ")
+ if err := encoder.Encode(output); err != nil {
+ return fmt.Errorf("failed to write action capabilities response: %w", err)
+ }
+ return nil
+}
+
func buildActionRequest(cmd *cobra.Command, opts actionPlanOptions) (unified.ActionRequest, error) {
var req unified.ActionRequest
if strings.TrimSpace(opts.RequestFile) != "" {
@@ -303,6 +406,43 @@ func actionPlanEndpoint(raw string) (string, error) {
return parsed.String(), nil
}
+func actionResourceFacetsEndpoint(raw, resourceID string) (string, error) {
+ resourceID = unified.CanonicalResourceID(resourceID)
+ if resourceID == "" {
+ return "", fmt.Errorf("resourceId is required (use --resource-id)")
+ }
+
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return "", fmt.Errorf("api url is required (use --api-url or PULSE_API_URL)")
+ }
+
+ parsed, err := url.Parse(raw)
+ if err != nil {
+ return "", fmt.Errorf("invalid api url: %w", err)
+ }
+ if parsed.Scheme != "http" && parsed.Scheme != "https" {
+ return "", fmt.Errorf("invalid api url: scheme must be http or https")
+ }
+ if parsed.Host == "" {
+ return "", fmt.Errorf("invalid api url: host is required")
+ }
+
+ path := strings.TrimRight(parsed.Path, "/")
+ resourcePath := "/resources/" + url.PathEscape(resourceID) + "/facets"
+ switch {
+ case path == "":
+ parsed.Path = "/api" + resourcePath
+ case path == "/api" || strings.HasSuffix(path, "/api"):
+ parsed.Path = path + resourcePath
+ default:
+ parsed.Path = path + "/api" + resourcePath
+ }
+ parsed.RawQuery = ""
+ parsed.Fragment = ""
+ return parsed.String(), nil
+}
+
func actionHTTPClient(deps *ActionsDeps) HTTPDoer {
if deps != nil && deps.HTTPClient != nil {
return deps.HTTPClient
@@ -317,15 +457,18 @@ func actionGetenv(deps *ActionsDeps, key string) string {
return os.Getenv(key)
}
-func actionStatusError(status string, body []byte) error {
+func actionStatusError(operation, status string, body []byte) error {
+ if strings.TrimSpace(operation) == "" {
+ operation = "request"
+ }
message := strings.TrimSpace(string(body))
if message == "" {
- return fmt.Errorf("action plan request failed: %s", status)
+ return fmt.Errorf("%s failed: %s", operation, status)
}
if len(message) > maxActionErrorBodyChars {
message = message[:maxActionErrorBodyChars] + "..."
}
- return fmt.Errorf("action plan request failed: %s: %s", status, message)
+ return fmt.Errorf("%s failed: %s: %s", operation, status, message)
}
func decodeJSONBytes(data []byte, out any) error {
diff --git a/pkg/pulsecli/actions_test.go b/pkg/pulsecli/actions_test.go
index c5a8da5054..b60f98653d 100644
--- a/pkg/pulsecli/actions_test.go
+++ b/pkg/pulsecli/actions_test.go
@@ -122,6 +122,84 @@ func TestActionsPlanCommandRequiresToken(t *testing.T) {
}
}
+func TestActionsCapabilitiesCommandFetchesResourceFacets(t *testing.T) {
+ var receivedAuth string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ t.Fatalf("method = %s, want GET", r.Method)
+ }
+ if r.URL.Path != "/api/resources/vm:42/facets" {
+ t.Fatalf("path = %s, want /api/resources/vm:42/facets", r.URL.Path)
+ }
+ receivedAuth = r.Header.Get("Authorization")
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "resourceId": "vm:42",
+ "capabilities": []map[string]any{
+ {
+ "name": "restart",
+ "type": unified.CapabilityTypeCommon,
+ "description": "Restart the VM",
+ "minimumApprovalLevel": unified.ApprovalAdmin,
+ "internalHandler": "proxmox.vm.restart",
+ "params": []map[string]any{
+ {"name": "mode", "type": "string", "enum": []string{"graceful", "force"}, "defaultValue": "graceful"},
+ },
+ },
+ },
+ "recentChanges": []any{},
+ "counts": map[string]any{"recentChanges": 0},
+ })
+ }))
+ defer server.Close()
+
+ cmd := newTestActionsRootCommand(map[string]string{
+ "PULSE_API_TOKEN": "test-token",
+ "PULSE_API_URL": server.URL + "/api",
+ })
+ cmd.SetArgs([]string{
+ "actions", "capabilities",
+ "--resource-id", "vm:42",
+ })
+ var out bytes.Buffer
+ cmd.SetOut(&out)
+
+ if err := cmd.Execute(); err != nil {
+ t.Fatalf("execute actions capabilities: %v", err)
+ }
+ if receivedAuth != "Bearer test-token" {
+ t.Fatalf("Authorization = %q", receivedAuth)
+ }
+ if strings.Contains(out.String(), "proxmox.vm.restart") {
+ t.Fatalf("capabilities output exposed internal handler: %s", out.String())
+ }
+
+ var capabilities actionCapabilitiesResponse
+ if err := json.Unmarshal(out.Bytes(), &capabilities); err != nil {
+ t.Fatalf("decode command output: %v\n%s", err, out.String())
+ }
+ if capabilities.ResourceID != "vm:42" || capabilities.Count != 1 {
+ t.Fatalf("capabilities output = %+v", capabilities)
+ }
+ if capabilities.Capabilities[0].Name != "restart" || capabilities.Capabilities[0].Params[0].Name != "mode" {
+ t.Fatalf("capabilities output = %+v", capabilities)
+ }
+}
+
+func TestActionsCapabilitiesCommandRequiresToken(t *testing.T) {
+ cmd := newTestActionsRootCommand(nil)
+ cmd.SetArgs([]string{
+ "actions", "capabilities",
+ "--api-url", "http://127.0.0.1:7655",
+ "--resource-id", "vm:42",
+ })
+
+ err := cmd.Execute()
+ if err == nil || !strings.Contains(err.Error(), "api token is required") {
+ t.Fatalf("expected token error, got %v", err)
+ }
+}
+
func TestActionsPlanCommandUsesRequestFileFromStdin(t *testing.T) {
var received unified.ActionRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {