Skip to content
Closed
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
12 changes: 12 additions & 0 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 支持展示的稳定操作顺序。
Expand Down
57 changes: 57 additions & 0 deletions internal/api/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand All @@ -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)
Expand Down
193 changes: 193 additions & 0 deletions internal/api/schedule.go
Original file line number Diff line number Diff line change
@@ -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)
}
62 changes: 62 additions & 0 deletions internal/api/schedule_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Loading
Loading