From a616aa657deaa421c5b2918b49a735463e1c0f03 Mon Sep 17 00:00:00 2001 From: huanghuoguoguo <60681390+huanghuoguoguo@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:18:42 +0800 Subject: [PATCH] feat(cli): add schedule command family --- internal/api/client.go | 12 ++ internal/api/operations.go | 57 ++++++ internal/api/schedule.go | 193 ++++++++++++++++++ internal/api/schedule_test.go | 62 ++++++ internal/app/schedule.go | 197 +++++++++++++++++++ internal/command/command.go | 1 + internal/command/schedule.go | 316 ++++++++++++++++++++++++++++++ internal/command/schedule_test.go | 23 +++ internal/command/schema.go | 12 ++ internal/output/default.go | 17 ++ 10 files changed, 890 insertions(+) create mode 100644 internal/api/schedule.go create mode 100644 internal/api/schedule_test.go create mode 100644 internal/app/schedule.go create mode 100644 internal/command/schedule.go create mode 100644 internal/command/schedule_test.go diff --git a/internal/api/client.go b/internal/api/client.go index 2dd95d3..c938a1a 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -221,6 +221,18 @@ var capabilityOperationIDs = []string{ "mcp_server.resource_read", "mcp_server.logs", "mcp_server.test", + "schedule.list", + "schedule.get", + "schedule.preview", + "schedule.create", + "schedule.update", + "schedule.pause", + "schedule.resume", + "schedule.archive", + "schedule.delete", + "schedule.trigger", + "schedule.runs", + "schedule.run_cancel", } // CapabilityOperationIDs 返回 CLI 支持展示的稳定操作顺序。 diff --git a/internal/api/operations.go b/internal/api/operations.go index cff945e..90f139c 100644 --- a/internal/api/operations.go +++ b/internal/api/operations.go @@ -39,6 +39,10 @@ func ResolveOperation(method, requestPath string) (Operation, bool) { operation, ok = resolveGetOperation(path) } else if method == http.MethodPost { operation, ok = resolvePostOperation(path) + } else if method == http.MethodPut { + operation, ok = resolvePutOperation(path) + } else if method == http.MethodDelete { + operation, ok = resolveDeleteOperation(path) } else { return Operation{}, false } @@ -59,6 +63,10 @@ func validOperationQuery(operation string, query url.Values) bool { allowed = map[string]bool{"type": true, "kind": true} case "plugin.logs", "mcp_server.logs": allowed = map[string]bool{"level": true, "limit": true} + case "schedule.list": + allowed = map[string]bool{"status": true, "owner_type": true, "action_type": true, "include_archived": true} + case "schedule.runs": + allowed = map[string]bool{"limit": true} case "skill.files.list": allowed = map[string]bool{"path": true, "include_hidden": true} default: @@ -81,6 +89,9 @@ func validOperationQuery(operation string, query url.Values) bool { if values, ok := query["include_hidden"]; ok && values[0] != "true" && values[0] != "false" { return false } + if values, ok := query["include_archived"]; ok && values[0] != "true" && values[0] != "false" { + return false + } if values, ok := query["path"]; ok { if _, err := safeFilePath(values[0]); err != nil { return false @@ -102,6 +113,18 @@ func resolveGetOperation(path string) (Operation, bool) { if op, ok := resolveSandboxOperation(path); ok { return op, true } + if path == schedulesPath { + return Operation{ID: "schedule.list", Method: http.MethodGet, Path: path, ReadOnly: true, Permission: "resource.view"}, true + } + if strings.HasPrefix(path, schedulesPath+"/") && strings.HasSuffix(path, "/runs") { + value := strings.TrimSuffix(strings.TrimPrefix(path, schedulesPath+"/"), "/runs") + if safeSegments(value, 1, false) { + return Operation{ID: "schedule.runs", Method: http.MethodGet, Path: path, ReadOnly: true, Permission: "resource.view"}, true + } + } + if identifierPath(path, schedulesPath) { + return Operation{ID: "schedule.get", Method: http.MethodGet, Path: path, ReadOnly: true, Permission: "resource.view"}, true + } switch path { case tasksPath: return Operation{ID: "task.list", Method: http.MethodGet, Path: path, ReadOnly: true, Permission: "resource.view"}, true @@ -160,6 +183,26 @@ func resolveGetOperation(path string) (Operation, bool) { } func resolvePostOperation(path string) (Operation, bool) { + if path == schedulesPath+"/preview" { + return Operation{ID: "schedule.preview", Method: http.MethodPost, Path: path, ReadOnly: true, Permission: "resource.view"}, true + } + if path == schedulesPath { + return Operation{ID: "schedule.create", Method: http.MethodPost, Path: path, Permission: "resource.manage"}, true + } + if strings.HasPrefix(path, schedulesPath+"/") { + value := strings.TrimPrefix(path, schedulesPath+"/") + parts := strings.Split(value, "/") + if len(parts) == 2 && safeSegments(parts[0], 1, false) && parts[1] != "runs" { + for _, action := range []string{"pause", "resume", "archive", "trigger"} { + if parts[1] == action { + return Operation{ID: "schedule." + action, Method: http.MethodPost, Path: path, Permission: "resource.manage"}, true + } + } + } + if len(parts) == 4 && parts[1] == "runs" && parts[3] == "cancel" && safeSegments(parts[0], 1, false) && safeSegments(parts[2], 1, false) { + return Operation{ID: "schedule.run_cancel", Method: http.MethodPost, Path: path, Permission: "resource.manage"}, true + } + } if nestedPath(path, knowledgeBasesPath, 1, "retrieve") { return Operation{ID: "knowledge_base.retrieve", Method: http.MethodPost, Path: path, ReadOnly: true, Permission: "resource.view"}, true } @@ -169,6 +212,20 @@ func resolvePostOperation(path string) (Operation, bool) { return Operation{}, false } +func resolvePutOperation(path string) (Operation, bool) { + if identifierPath(path, schedulesPath) { + return Operation{ID: "schedule.update", Method: http.MethodPut, Path: path, Permission: "resource.manage"}, true + } + return Operation{}, false +} + +func resolveDeleteOperation(path string) (Operation, bool) { + if identifierPath(path, schedulesPath) { + return Operation{ID: "schedule.delete", Method: http.MethodDelete, Path: path, Permission: "resource.manage"}, true + } + return Operation{}, false +} + func identifierPath(path, base string) bool { value := strings.TrimPrefix(path, base+"/") return value != path && safeSegments(value, 1, false) diff --git a/internal/api/schedule.go b/internal/api/schedule.go new file mode 100644 index 0000000..d140db2 --- /dev/null +++ b/internal/api/schedule.go @@ -0,0 +1,193 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/langbot-app/langbot-cli/internal/result" +) + +const schedulesPath = "/api/v1/schedules" + +// ScheduleRequest is the common authenticated transport used by the schedule +// resource. Core returns the resource payload in the normal API envelope. +func (c Client) ScheduleRequest(ctx context.Context, target Target, method, path string, body map[string]any) (any, error) { + if !strings.HasPrefix(path, schedulesPath) { + return nil, result.New("input", "invalid schedule path") + } + var reader io.Reader + if method != http.MethodGet && method != http.MethodDelete { + encoded, err := json.Marshal(bodyOrEmpty(body)) + if err != nil || len(encoded) > maxRequestBytes { + return nil, result.New("input", "schedule request body is invalid or too large") + } + reader = bytes.NewReader(encoded) + } + resp, err := c.do(ctx, target, method, path, reader, method != http.MethodGet) + if err != nil { + return nil, err + } + return redactConnectionSecret(resp.Data, target.secret()), nil +} + +func (c Client) Schedules(ctx context.Context, target Target, status, ownerType, actionType string, includeArchived bool) ([]map[string]any, error) { + query := url.Values{} + for key, value := range map[string]string{"status": status, "owner_type": ownerType, "action_type": actionType} { + if strings.TrimSpace(value) != "" { + query.Set(key, value) + } + } + if includeArchived { + query.Set("include_archived", "true") + } + path := schedulesPath + if encoded := query.Encode(); encoded != "" { + path += "?" + encoded + } + data, err := c.ScheduleRequest(ctx, target, http.MethodGet, path, nil) + if err != nil { + return nil, err + } + object, ok := data.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule list response") + } + rows, ok := object["schedules"].([]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule list response") + } + resultRows := make([]map[string]any, 0, len(rows)) + for _, item := range rows { + row, ok := item.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule response") + } + resultRows = append(resultRows, row) + } + return resultRows, nil +} + +func (c Client) Schedule(ctx context.Context, target Target, identifier string) (map[string]any, error) { + path, err := resourcePath(schedulesPath, identifier) + if err != nil { + return nil, err + } + data, err := c.ScheduleRequest(ctx, target, http.MethodGet, path, nil) + if err != nil { + return nil, err + } + row, ok := data.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule response") + } + return row, nil +} + +func (c Client) SchedulePreview(ctx context.Context, target Target, body map[string]any) (map[string]any, error) { + data, err := c.ScheduleRequest(ctx, target, http.MethodPost, schedulesPath+"/preview", body) + if err != nil { + return nil, err + } + row, ok := data.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule preview response") + } + return row, nil +} + +func (c Client) ScheduleCreate(ctx context.Context, target Target, body map[string]any) (map[string]any, error) { + data, err := c.ScheduleRequest(ctx, target, http.MethodPost, schedulesPath, body) + if err != nil { + return nil, err + } + row, ok := data.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule create response") + } + return row, nil +} + +func (c Client) ScheduleUpdate(ctx context.Context, target Target, identifier string, body map[string]any) (map[string]any, error) { + path, err := resourcePath(schedulesPath, identifier) + if err != nil { + return nil, err + } + data, err := c.ScheduleRequest(ctx, target, http.MethodPut, path, body) + if err != nil { + return nil, err + } + row, ok := data.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule update response") + } + return row, nil +} + +func (c Client) ScheduleAction(ctx context.Context, target Target, identifier, action string, body map[string]any) (any, error) { + if action != "pause" && action != "resume" && action != "archive" && action != "trigger" { + return nil, result.New("input", "invalid schedule action") + } + path, err := resourcePath(schedulesPath, identifier) + if err != nil { + return nil, err + } + return c.ScheduleRequest(ctx, target, http.MethodPost, path+"/"+action, body) +} + +func (c Client) ScheduleDelete(ctx context.Context, target Target, identifier string) (any, error) { + path, err := resourcePath(schedulesPath, identifier) + if err != nil { + return nil, err + } + return c.ScheduleRequest(ctx, target, http.MethodDelete, path, nil) +} + +func (c Client) ScheduleRuns(ctx context.Context, target Target, identifier string, limit int) ([]map[string]any, error) { + path, err := resourcePath(schedulesPath, identifier) + if err != nil { + return nil, err + } + path += "/runs" + if limit > 0 { + path += "?limit=" + strconv.Itoa(limit) + } + data, err := c.ScheduleRequest(ctx, target, http.MethodGet, path, nil) + if err != nil { + return nil, err + } + object, ok := data.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule runs response") + } + raw, ok := object["runs"].([]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule runs response") + } + rows := make([]map[string]any, 0, len(raw)) + for _, item := range raw { + row, ok := item.(map[string]any) + if !ok { + return nil, result.New("incompatible", "invalid schedule run response") + } + rows = append(rows, row) + } + return rows, nil +} + +func (c Client) ScheduleRunCancel(ctx context.Context, target Target, identifier, runIdentifier string) (any, error) { + path, err := resourcePath(schedulesPath, identifier) + if err != nil { + return nil, err + } + runPath, err := resourcePath(path+"/runs", runIdentifier) + if err != nil { + return nil, err + } + return c.ScheduleRequest(ctx, target, http.MethodPost, runPath+"/cancel", nil) +} diff --git a/internal/api/schedule_test.go b/internal/api/schedule_test.go new file mode 100644 index 0000000..66b76a8 --- /dev/null +++ b/internal/api/schedule_test.go @@ -0,0 +1,62 @@ +package api + +import ( + "context" + "io" + "net/http" + "strings" + "testing" +) + +func TestScheduleListBuildsFiltersAndParsesRows(t *testing.T) { + var request *http.Request + client := Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + request = r + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"schedules":[{"uuid":"s1"}]}}`))}, nil + })} + rows, err := client.Schedules(context.Background(), Target{Endpoint: "http://example.test"}, "active", "user", "agent", true) + if err != nil { + t.Fatalf("Schedules() error = %v", err) + } + if len(rows) != 1 || rows[0]["uuid"] != "s1" { + t.Fatalf("Schedules() rows = %#v", rows) + } + if request.URL.Path != "/api/v1/schedules" || request.URL.Query().Get("status") != "active" || request.URL.Query().Get("owner_type") != "user" || request.URL.Query().Get("action_type") != "agent" || request.URL.Query().Get("include_archived") != "true" { + t.Fatalf("schedule list request = %s", request.URL.String()) + } +} + +func TestScheduleRunsAppendsLimitAfterResourcePath(t *testing.T) { + var request *http.Request + client := Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + request = r + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"code":0,"data":{"runs":[]}}`))}, nil + })} + if _, err := client.ScheduleRuns(context.Background(), Target{Endpoint: "http://example.test"}, "s1", 20); err != nil { + t.Fatalf("ScheduleRuns() error = %v", err) + } + if request.URL.Path != "/api/v1/schedules/s1/runs" || request.URL.Query().Get("limit") != "20" { + t.Fatalf("schedule runs request = %s", request.URL.String()) + } +} + +func TestScheduleOperationRegistryCoversLifecycleRoutes(t *testing.T) { + cases := []struct { + method, path, id string + }{ + {http.MethodGet, "/api/v1/schedules?status=active", "schedule.list"}, + {http.MethodGet, "/api/v1/schedules/s1", "schedule.get"}, + {http.MethodPost, "/api/v1/schedules/preview", "schedule.preview"}, + {http.MethodPost, "/api/v1/schedules/s1/trigger", "schedule.trigger"}, + {http.MethodGet, "/api/v1/schedules/s1/runs?limit=20", "schedule.runs"}, + {http.MethodPost, "/api/v1/schedules/s1/runs/r1/cancel", "schedule.run_cancel"}, + {http.MethodPut, "/api/v1/schedules/s1", "schedule.update"}, + {http.MethodDelete, "/api/v1/schedules/s1", "schedule.delete"}, + } + for _, test := range cases { + op, ok := ResolveOperation(test.method, test.path) + if !ok || op.ID != test.id { + t.Errorf("ResolveOperation(%s, %s) = %#v, %v", test.method, test.path, op, ok) + } + } +} diff --git a/internal/app/schedule.go b/internal/app/schedule.go new file mode 100644 index 0000000..2981e1c --- /dev/null +++ b/internal/app/schedule.go @@ -0,0 +1,197 @@ +package app + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/langbot-app/langbot-cli/internal/api" + "github.com/langbot-app/langbot-cli/internal/i18n" + "github.com/langbot-app/langbot-cli/internal/result" +) + +func scheduleTarget(preflight WritePreflight) api.Target { + return api.Target{Endpoint: preflight.Connection.Endpoint, APIKey: preflight.Connection.APIKey, UserToken: preflight.Connection.UserToken, Timeout: preflight.Connection.Timeout} +} + +func (s *Service) scheduleRead(ctx context.Context, operation string, options CheckOptions) (WritePreflight, api.Client, error) { + preflight, err := s.readPreflight(ctx, operation, "resource.view", options) + return preflight, api.Client{Transport: s.deps.Transport}, err +} + +func (s *Service) ScheduleList(ctx context.Context, status, ownerType, actionType string, includeArchived bool, options CheckOptions) (Result, error) { + preflight, client, err := s.scheduleRead(ctx, "schedule.list", options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + rows, err := client.Schedules(ctx, scheduleTarget(preflight), status, ownerType, actionType, includeArchived) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + for _, row := range rows { + row["schedule"] = scheduleDescription(row) + row["recent_runs"] = recentRunSummary(row["recent_runs_json"]) + } + return Result{Data: map[string]any{"schedules": rows}, Meta: preflight.Meta()}, nil +} + +func scheduleDescription(row map[string]any) string { + switch row["schedule_type"] { + case "cron": + if value, ok := row["cron_expression"].(string); ok { + return value + } + case "interval": + return fmt.Sprintf("every %v seconds", row["interval_seconds"]) + case "once": + return fmt.Sprintf("once at %v", row["run_at"]) + } + return "" +} + +func recentRunSummary(value any) string { + items, ok := value.([]any) + if !ok { + return "" + } + resultValue := make([]string, 0, len(items)) + for _, item := range items { + status := "" + if row, ok := item.(map[string]any); ok { + status, _ = row["status"].(string) + } + symbol := "·" + switch status { + case "completed": + symbol = "✓" + case "failed", "interrupted": + symbol = "✗" + case "running": + symbol = "…" + case "skipped", "cancelled": + symbol = "–" + } + resultValue = append(resultValue, symbol) + } + return strings.Join(resultValue, " ") +} + +func (s *Service) ScheduleGet(ctx context.Context, identifier string, options CheckOptions) (Result, error) { + preflight, client, err := s.scheduleRead(ctx, "schedule.get", options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + row, err := client.Schedule(ctx, scheduleTarget(preflight), identifier) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: map[string]any{"schedule": row}, Meta: preflight.Meta()}, nil +} + +func (s *Service) SchedulePreview(ctx context.Context, body map[string]any, options CheckOptions) (Result, error) { + preflight, client, err := s.scheduleRead(ctx, "schedule.preview", options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + row, err := client.SchedulePreview(ctx, scheduleTarget(preflight), body) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: row, Meta: preflight.Meta()}, nil +} + +func (s *Service) ScheduleRuns(ctx context.Context, identifier string, limit int, options CheckOptions) (Result, error) { + if limit < 1 || limit > 500 { + return Result{}, result.New("input", i18n.T("limit must be 1..500")) + } + preflight, client, err := s.scheduleRead(ctx, "schedule.runs", options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + rows, err := client.ScheduleRuns(ctx, scheduleTarget(preflight), identifier, limit) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: map[string]any{"runs": rows}, Meta: preflight.Meta()}, nil +} + +func (s *Service) ScheduleCreate(ctx context.Context, body map[string]any, options CheckOptions) (Result, error) { + return s.scheduleWrite(ctx, "schedule.create", http.MethodPost, "", body, options) +} + +func (s *Service) ScheduleUpdate(ctx context.Context, identifier string, body map[string]any, options CheckOptions) (Result, error) { + return s.scheduleWrite(ctx, "schedule.update", http.MethodPut, identifier, body, options) +} + +func (s *Service) scheduleWrite(ctx context.Context, operation, method, identifier string, body map[string]any, options CheckOptions) (Result, error) { + preflight, err := s.WritePreflight(ctx, operation, options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + client := api.Client{Transport: s.deps.Transport} + var row map[string]any + if method == http.MethodPost && identifier == "" { + row, err = client.ScheduleCreate(ctx, scheduleTarget(preflight), body) + } else { + row, err = client.ScheduleUpdate(ctx, scheduleTarget(preflight), identifier, body) + } + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: map[string]any{"schedule": row}, Meta: preflight.Meta()}, nil +} + +func (s *Service) ScheduleAction(ctx context.Context, operation, identifier, action string, body map[string]any, options CheckOptions) (Result, error) { + preflight, err := s.WritePreflight(ctx, operation, options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + data, err := (api.Client{Transport: s.deps.Transport}).ScheduleAction(ctx, scheduleTarget(preflight), identifier, action, body) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: data, Meta: preflight.Meta()}, nil +} + +func (s *Service) ScheduleDelete(ctx context.Context, identifier string, confirmed bool, options CheckOptions) (Result, error) { + if !confirmed { + return Result{}, result.New("input", i18n.T("Deleting a schedule requires --yes")) + } + preflight, err := s.WritePreflight(ctx, "schedule.delete", options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + data, err := (api.Client{Transport: s.deps.Transport}).ScheduleDelete(ctx, scheduleTarget(preflight), identifier) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: data, Meta: preflight.Meta()}, nil +} + +func (s *Service) ScheduleTrigger(ctx context.Context, identifier string, wait bool, options CheckOptions) (Result, error) { + resultValue, err := s.ScheduleAction(ctx, "schedule.trigger", identifier, "trigger", nil, options) + if err != nil || !wait { + return resultValue, err + } + status := "" + if row, ok := resultValue.Data.(map[string]any); ok { + status, _ = row["status"].(string) + } + if status != "completed" { + return resultValue, result.New("server", i18n.T("Scheduled run did not complete successfully")) + } + return resultValue, nil +} + +func (s *Service) ScheduleRunCancel(ctx context.Context, identifier, runIdentifier string, options CheckOptions) (Result, error) { + preflight, err := s.WritePreflight(ctx, "schedule.run_cancel", options) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + data, err := (api.Client{Transport: s.deps.Transport}).ScheduleRunCancel(ctx, scheduleTarget(preflight), identifier, strings.TrimSpace(runIdentifier)) + if err != nil { + return Result{Meta: preflight.Meta()}, err + } + return Result{Data: data, Meta: preflight.Meta()}, nil +} diff --git a/internal/command/command.go b/internal/command/command.go index f5daac6..bc01d6b 100644 --- a/internal/command/command.go +++ b/internal/command/command.go @@ -262,6 +262,7 @@ func newRoot(deps Dependencies, flags *globalFlags, service *app.Service) *cobra root.AddCommand(newProviderCommand(service, deps, flags)) root.AddCommand(newModelCommand(service, deps, flags)) root.AddCommand(newTaskCommand(service, deps, flags)) + root.AddCommand(newScheduleCommand(service, deps, flags)) root.AddCommand(newKnowledgeBaseCommand(service, deps, flags)) root.AddCommand(newKnowledgeEngineCommand(service, deps, flags), newKnowledgeParserCommand(service, deps, flags)) root.AddCommand(newMonitoringCommand(service, deps, flags)) diff --git a/internal/command/schedule.go b/internal/command/schedule.go new file mode 100644 index 0000000..1b795c4 --- /dev/null +++ b/internal/command/schedule.go @@ -0,0 +1,316 @@ +package command + +import ( + "encoding/json" + "os" + "strconv" + "strings" + + "github.com/langbot-app/langbot-cli/internal/app" + "github.com/langbot-app/langbot-cli/internal/i18n" + "github.com/langbot-app/langbot-cli/internal/result" + "github.com/spf13/cobra" + "go.yaml.in/yaml/v3" +) + +func newScheduleCommand(service *app.Service, deps Dependencies, flags *globalFlags) *cobra.Command { + root := &cobra.Command{Use: "schedule", Short: i18n.T("Manage scheduled tasks"), Args: cobra.NoArgs} + + var status, ownerType, actionType string + var includeArchived, listJSON bool + list := &cobra.Command{Use: "list", Short: i18n.T("List scheduled tasks"), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + if err := validateScheduleFilters(status, ownerType, actionType); err != nil { + return emitCommand(deps, flags, app.Result{}, err) + } + setJSONOutput(flags, listJSON) + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleList(cmd.Context(), status, ownerType, actionType, includeArchived, connectionOptions(flags)) + }) + }} + list.Flags().StringVar(&status, "status", "", i18n.T("Filter status")) + list.Flags().StringVar(&ownerType, "owner-type", "", i18n.T("Filter owner type: user, plugin or workflow")) + list.Flags().StringVar(&ownerType, "source", "", i18n.T("Alias for --owner-type")) + list.Flags().StringVar(&actionType, "action-type", "", i18n.T("Filter action type")) + list.Flags().BoolVar(&includeArchived, "include-archived", false, i18n.T("Include archived schedules")) + list.Flags().BoolVar(&listJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(list) + + var getJSON bool + get := &cobra.Command{Use: "get ", Short: i18n.T("Read a scheduled task"), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, getJSON) + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleGet(cmd.Context(), args[0], connectionOptions(flags)) + }) + }} + get.Flags().BoolVar(&getJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(get) + + var previewFile, previewCron, previewInterval, previewRunAt, previewTimezone string + var previewCount int + var previewJSON bool + preview := &cobra.Command{Use: "preview", Short: i18n.T("Preview future schedule runs"), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + if previewCount < 1 || previewCount > 100 { + return emitCommand(deps, flags, app.Result{}, result.New("input", i18n.T("count must be 1..100"))) + } + setJSONOutput(flags, previewJSON) + body, err := scheduleBody(previewFile, previewCron, previewInterval, previewRunAt, previewTimezone, "", "", "", "", "", "", "", "", "", "", "") + if err != nil { + return emitCommand(deps, flags, app.Result{}, err) + } + body["count"] = previewCount + return emitCall(deps, flags, func() (app.Result, error) { + return service.SchedulePreview(cmd.Context(), body, connectionOptions(flags)) + }) + }} + preview.Flags().StringVar(&previewFile, "file", "", i18n.T("JSON/YAML request body file")) + preview.Flags().StringVar(&previewCron, "cron", "", i18n.T("Cron expression")) + preview.Flags().StringVar(&previewInterval, "interval", "", i18n.T("Interval in seconds")) + preview.Flags().StringVar(&previewRunAt, "run-at", "", i18n.T("One-shot RFC3339 time")) + preview.Flags().StringVar(&previewTimezone, "timezone", "", i18n.T("IANA timezone")) + preview.Flags().IntVar(&previewCount, "count", 3, i18n.T("Number of future runs")) + preview.Flags().BoolVar(&previewJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(preview) + + root.AddCommand(newScheduleWriteCommand(service, deps, flags, "create", false)) + root.AddCommand(newScheduleWriteCommand(service, deps, flags, "update", true)) + + for _, action := range []string{"pause", "resume", "archive"} { + root.AddCommand(newScheduleActionCommand(service, deps, flags, action)) + } + var deleteYes, deleteJSON bool + deleteCommand := &cobra.Command{Use: "delete ", Short: i18n.T("Delete a scheduled task"), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, deleteJSON) + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleDelete(cmd.Context(), args[0], deleteYes, connectionOptions(flags)) + }) + }} + deleteCommand.Flags().BoolVar(&deleteYes, "yes", false, i18n.T("Confirm deletion")) + deleteCommand.Flags().BoolVar(&deleteJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(deleteCommand) + + var triggerWait, triggerJSON bool + trigger := &cobra.Command{Use: "trigger ", Short: i18n.T("Run a scheduled task now"), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, triggerJSON) + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleTrigger(cmd.Context(), args[0], triggerWait, connectionOptions(flags)) + }) + }} + trigger.Flags().BoolVar(&triggerWait, "wait", false, i18n.T("Wait for the run to finish")) + trigger.Flags().BoolVar(&triggerJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(trigger) + + var runsLimit int + var runsJSON bool + runs := &cobra.Command{Use: "runs ", Short: i18n.T("List scheduled task runs"), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, runsJSON) + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleRuns(cmd.Context(), args[0], runsLimit, connectionOptions(flags)) + }) + }} + runs.Flags().IntVar(&runsLimit, "limit", 20, i18n.T("Maximum runs to return")) + runs.Flags().BoolVar(&runsJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(runs) + + var cancelJSON bool + cancel := &cobra.Command{Use: "run-cancel ", Short: i18n.T("Cancel a scheduled task run"), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, cancelJSON) + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleRunCancel(cmd.Context(), args[0], args[1], connectionOptions(flags)) + }) + }} + cancel.Flags().BoolVar(&cancelJSON, "json", false, i18n.T("Output JSON")) + root.AddCommand(cancel) + return root +} + +func newScheduleActionCommand(service *app.Service, deps Dependencies, flags *globalFlags, action string) *cobra.Command { + var runAt string + var jsonOutput bool + command := &cobra.Command{Use: action + " ", Short: i18n.T("Change scheduled task state"), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, jsonOutput) + body := map[string]any{} + if action == "resume" && strings.TrimSpace(runAt) != "" { + body["run_at"] = runAt + } + return emitCall(deps, flags, func() (app.Result, error) { + return service.ScheduleAction(cmd.Context(), "schedule."+action, args[0], action, body, connectionOptions(flags)) + }) + }} + if action == "resume" { + command.Flags().StringVar(&runAt, "run-at", "", i18n.T("New RFC3339 time for an expired one-shot schedule")) + } + command.Flags().BoolVar(&jsonOutput, "json", false, i18n.T("Output JSON")) + return command +} + +func newScheduleWriteCommand(service *app.Service, deps Dependencies, flags *globalFlags, name string, update bool) *cobra.Command { + var file, scheduleType, cron, interval, runAt, timezone, scheduleName, description, actionType, actionSpec string + var agentUUID, prompt, botUUID, targetType, targetID, message string + var jsonOutput bool + use := name + if update { + use += " " + } + command := &cobra.Command{Use: use, Short: i18n.T("Write a scheduled task"), Args: func(cmd *cobra.Command, args []string) error { + if update { + return cobra.ExactArgs(1)(cmd, args) + } + return cobra.NoArgs(cmd, args) + }, RunE: func(cmd *cobra.Command, args []string) error { + setJSONOutput(flags, jsonOutput) + body, err := scheduleBody(file, cron, interval, runAt, timezone, scheduleType, scheduleName, description, actionType, actionSpec, agentUUID, prompt, botUUID, targetType, targetID, message) + if err != nil { + return emitCommand(deps, flags, app.Result{}, err) + } + if !update && body["action_spec"] == nil && body["action_spec_json"] == nil { + return emitCommand(deps, flags, app.Result{}, result.New("input", i18n.T("create requires --action-spec or an action convenience option"))) + } + return emitCall(deps, flags, func() (app.Result, error) { + if update { + return service.ScheduleUpdate(cmd.Context(), args[0], body, connectionOptions(flags)) + } + return service.ScheduleCreate(cmd.Context(), body, connectionOptions(flags)) + }) + }} + command.Flags().StringVar(&file, "file", "", i18n.T("JSON/YAML request body file")) + command.Flags().StringVar(&scheduleType, "type", "", i18n.T("Schedule type: cron, interval or once")) + command.Flags().StringVar(&cron, "cron", "", i18n.T("Cron expression")) + command.Flags().StringVar(&interval, "interval", "", i18n.T("Interval in seconds")) + command.Flags().StringVar(&runAt, "run-at", "", i18n.T("One-shot RFC3339 time")) + command.Flags().StringVar(&timezone, "timezone", "", i18n.T("IANA timezone")) + command.Flags().StringVar(&scheduleName, "name", "", i18n.T("Schedule name")) + command.Flags().StringVar(&description, "description", "", i18n.T("Schedule description")) + command.Flags().StringVar(&actionType, "action-type", "", i18n.T("Action type")) + command.Flags().StringVar(&actionSpec, "action-spec", "", i18n.T("Action JSON or @file")) + command.Flags().StringVar(&agentUUID, "agent-uuid", "", i18n.T("Agent UUID convenience option")) + command.Flags().StringVar(&prompt, "prompt", "", i18n.T("Agent prompt convenience option")) + command.Flags().StringVar(&botUUID, "bot-uuid", "", i18n.T("Bot UUID convenience option")) + command.Flags().StringVar(&targetType, "target-type", "", i18n.T("Bot target type")) + command.Flags().StringVar(&targetID, "target-id", "", i18n.T("Bot target ID")) + command.Flags().StringVar(&message, "message", "", i18n.T("Bot message convenience option")) + command.Flags().BoolVar(&jsonOutput, "json", false, i18n.T("Output JSON")) + return command +} + +func scheduleBody(file, cron, interval, runAt, timezone, scheduleType, name, description, actionType, actionSpec, agentUUID, prompt, botUUID, targetType, targetID, message string) (map[string]any, error) { + body := map[string]any{} + if strings.TrimSpace(file) != "" { + loaded, err := loadScheduleFile(file) + if err != nil { + return nil, err + } + body = loaded + } + set := func(key, value string) { + if strings.TrimSpace(value) != "" { + body[key] = value + } + } + set("name", name) + set("description", description) + set("timezone", timezone) + set("schedule_type", scheduleType) + if cron != "" { + body["schedule_type"], body["cron_expression"] = "cron", cron + } + if interval != "" { + seconds, err := strconv.Atoi(interval) + if err != nil || seconds < 1 { + return nil, result.New("input", "interval must be a positive number of seconds") + } + body["schedule_type"], body["interval_seconds"] = "interval", seconds + } + if runAt != "" { + body["schedule_type"], body["run_at"] = "once", runAt + } + if cron != "" && interval != "" || cron != "" && runAt != "" || interval != "" && runAt != "" { + return nil, result.New("input", "cron, interval and run-at are mutually exclusive") + } + set("action_type", actionType) + if strings.TrimSpace(actionSpec) != "" { + parsed, err := parseActionSpec(actionSpec) + if err != nil { + return nil, err + } + body["action_spec"] = parsed + if actionType == "" { + if kind, ok := parsed["type"].(string); ok { + body["action_type"] = kind + } + } + } + if agentUUID != "" || prompt != "" { + body["action_spec"] = map[string]any{"type": "agent", "agent_uuid": agentUUID, "prompt_template": prompt} + body["action_type"] = "agent" + } + if botUUID != "" || targetType != "" || targetID != "" || message != "" { + body["action_spec"] = map[string]any{"type": "bot_message", "bot_uuid": botUUID, "target": map[string]any{"target_type": targetType, "target_id": targetID}, "message_chain": []map[string]any{{"type": "Plain", "text": message}}} + body["action_type"] = "bot_message" + } + if body["action_spec"] == nil && strings.TrimSpace(actionSpec) == "" && (agentUUID == "" && botUUID == "") { + if _, creatingType := body["action_type"]; creatingType { + return nil, result.New("input", "action-spec is required") + } + } + return body, nil +} + +func validateScheduleFilters(status, ownerType, actionType string) error { + if status != "" && !scheduleContainsString([]string{"active", "paused", "completed", "needs_rebind", "archived"}, status) { + return result.New("input", "unsupported schedule status") + } + if ownerType != "" && !scheduleContainsString([]string{"user", "plugin", "workflow"}, ownerType) { + return result.New("input", "owner-type must be user, plugin or workflow") + } + if actionType != "" && !scheduleContainsString([]string{"agent", "workflow", "bot_message", "plugin_handler", "box_script"}, actionType) { + return result.New("input", "unsupported schedule action type") + } + return nil +} + +func scheduleContainsString(values []string, wanted string) bool { + for _, value := range values { + if value == wanted { + return true + } + } + return false +} + +func loadScheduleFile(path string) (map[string]any, error) { + if path == "-" { + return nil, result.New("input", "schedule --file - is not available with this command entrypoint") + } + data, err := os.ReadFile(path) + if err != nil { + return nil, result.New("input", "unable to read schedule file") + } + var body map[string]any + if err := json.Unmarshal(data, &body); err != nil { + if yamlErr := yaml.Unmarshal(data, &body); yamlErr != nil || body == nil { + return nil, result.New("input", "schedule file must contain a YAML or JSON object") + } + } + return body, nil +} + +func parseActionSpec(value string) (map[string]any, error) { + if strings.HasPrefix(value, "@") { + data, err := os.ReadFile(strings.TrimPrefix(value, "@")) + if err != nil { + return nil, result.New("input", "unable to read action-spec file") + } + value = string(data) + } + var spec map[string]any + if err := json.Unmarshal([]byte(value), &spec); err != nil || spec == nil { + return nil, result.New("input", "action-spec must be a JSON object or @file") + } + return spec, nil +} + +func setJSONOutput(flags *globalFlags, enabled bool) { + if enabled { + flags.output, flags.outputSet = "json", true + } +} diff --git a/internal/command/schedule_test.go b/internal/command/schedule_test.go new file mode 100644 index 0000000..4ab7dd7 --- /dev/null +++ b/internal/command/schedule_test.go @@ -0,0 +1,23 @@ +package command + +import "testing" + +func TestScheduleBodyBuildsCronAgentAction(t *testing.T) { + body, err := scheduleBody("", "0 9 * * 1-5", "", "", "Asia/Shanghai", "", "Morning", "", "", "", "agent-1", "hello", "", "", "", "") + if err != nil { + t.Fatalf("scheduleBody() error = %v", err) + } + if body["schedule_type"] != "cron" || body["cron_expression"] != "0 9 * * 1-5" || body["action_type"] != "agent" { + t.Fatalf("scheduleBody() = %#v", body) + } + action, ok := body["action_spec"].(map[string]any) + if !ok || action["agent_uuid"] != "agent-1" || action["prompt_template"] != "hello" { + t.Fatalf("agent action = %#v", body["action_spec"]) + } +} + +func TestScheduleBodyRejectsInvalidInterval(t *testing.T) { + if _, err := scheduleBody("", "", "zero", "", "", "", "", "", "", "", "", "", "", "", "", ""); err == nil { + t.Fatal("scheduleBody() accepted an invalid interval") + } +} diff --git a/internal/command/schema.go b/internal/command/schema.go index 9e1666f..23a23bc 100644 --- a/internal/command/schema.go +++ b/internal/command/schema.go @@ -261,6 +261,18 @@ var schemaMetaByName = map[string]schemaCommandMeta{ meta.SupportsWait = true return meta }(), + "schedule.list": readMeta(operationIDs("schedule.list")...), + "schedule.get": readMeta(operationIDs("schedule.get")...), + "schedule.preview": readMeta(operationIDs("schedule.preview")...), + "schedule.runs": readMeta(operationIDs("schedule.runs")...), + "schedule.create": writeMeta(operationIDs("schedule.create"), schemaWriteOptions{}), + "schedule.update": writeMeta(operationIDs("schedule.update"), schemaWriteOptions{}), + "schedule.pause": writeMeta(operationIDs("schedule.pause"), schemaWriteOptions{}), + "schedule.resume": writeMeta(operationIDs("schedule.resume"), schemaWriteOptions{}), + "schedule.archive": writeMeta(operationIDs("schedule.archive"), schemaWriteOptions{}), + "schedule.delete": writeMeta(operationIDs("schedule.delete"), schemaWriteOptions{Destructive: true, RequiresYes: true}), + "schedule.trigger": writeMeta(operationIDs("schedule.trigger"), schemaWriteOptions{SupportsWait: true}), + "schedule.run-cancel": writeMeta(operationIDs("schedule.run_cancel"), schemaWriteOptions{}), "knowledge-base.list": readMeta(operationIDs("knowledge_base.list")...), "knowledge-base.get": readMeta(operationIDs("knowledge_base.get")...), diff --git a/internal/output/default.go b/internal/output/default.go index 74eded5..3454c13 100644 --- a/internal/output/default.go +++ b/internal/output/default.go @@ -369,6 +369,15 @@ func renderDefaultData(w io.Writer, value any, command string) error { return nil } } + if command == "schedule.get" { + return renderValue(w, data["schedule"], i18n.T("Schedule")) + } + if command == "schedule.preview" { + if err := renderFields(w, data, []string{"warning"}); err != nil { + return err + } + return renderValue(w, data["next_runs"], i18n.T("Next runs")) + } if listKey := commandListKey(command); listKey != "" { if items, ok := data[listKey].([]any); ok { if err := renderFields(w, data, []string{"model_type"}); err != nil { @@ -962,6 +971,10 @@ func commandListKey(command string) string { return "skills" case "task.list": return "tasks" + case "schedule.list": + return "schedules" + case "schedule.runs": + return "schedule_runs" } return "" } @@ -994,6 +1007,10 @@ func resourceFields(key string) []string { return []string{"name", "provider_name", "context_length", "uuid"} case "tasks": return []string{"id", "task_type", "kind", "status", "created_at"} + case "schedules": + return []string{"uuid", "name", "owner_type", "action_type", "status", "schedule", "timezone", "next_run_at", "recent_runs", "circuit_state", "consecutive_failures", "circuit_open_until"} + case "schedule_runs": + return []string{"uuid", "status", "error_bucket", "trigger_source", "scheduled_for", "duration_ms", "target_results", "linked_execution", "summary", "error"} case "bases": return []string{"name", "knowledge_engine_plugin_id", "uuid"} case "files":