-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathagent.go
More file actions
1210 lines (1064 loc) · 31.7 KB
/
agent.go
File metadata and controls
1210 lines (1064 loc) · 31.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"errors"
"fmt"
"os"
"regexp"
"slices"
"strings"
"time"
"github.com/charmbracelet/huh"
"github.com/twitchtv/twirp"
"github.com/urfave/cli/v3"
"github.com/livekit/livekit-cli/v2/pkg/agentfs"
"github.com/livekit/livekit-cli/v2/pkg/config"
"github.com/livekit/livekit-cli/v2/pkg/util"
lkproto "github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
lksdk "github.com/livekit/server-sdk-go/v2"
)
const (
cloudAgentsBetaSignupURL = "https://forms.gle/GkGNNTiMt2qyfnu78"
)
var (
idFlag = func(required bool) *cli.StringFlag {
return &cli.StringFlag{
Name: "id",
Usage: fmt.Sprintf("`ID` of the agent. If unset, and the %s file is present, will use the id found there.", config.LiveKitTOMLFile),
Required: required,
}
}
idSliceFlag = &cli.StringSliceFlag{
Name: "id",
Usage: "`IDs` of agent(s)",
Required: false,
}
secretsFileFlag = &cli.StringFlag{
Name: "secrets-file",
Usage: "`FILE` containing secret KEY=VALUE pairs, one per line. These will be injected as environment variables into the agent.",
TakesFile: true,
Required: false,
}
secretsFlag = &cli.StringSliceFlag{
Name: "secrets",
Usage: "KEY=VALUE comma separated secrets. These will be injected as environment variables into the agent. These take precedence over secrets-file.",
Required: false,
}
logTypeFlag = &cli.StringFlag{
Name: "log-type",
Usage: "Type of logs to retrieve. Valid values are 'deploy' and 'build'",
Value: "deploy",
Required: false,
}
regionFlag = &cli.StringSliceFlag{
Name: "regions",
Usage: "Region(s) to deploy the agent to. If unset, will deploy to the nearest region.",
Required: false,
Hidden: true,
}
skipSDKCheckFlag = &cli.BoolFlag{
Name: "skip-sdk-check",
Required: false,
Hidden: true,
}
dockerFileFlag = &cli.StringFlag{
Name: "dockerfile",
Usage: "Path to the Dockerfile to use for the agent. If unset, will use the Dockerfile in the working directory.",
Required: false,
Aliases: []string{"f"},
}
AgentCommands = []*cli.Command{
{
Name: "agent",
Aliases: []string{"a"},
Usage: "Manage LiveKit Cloud Agents",
Commands: []*cli.Command{
{
Name: "create",
Usage: "Create a new LiveKit Cloud Agent",
Action: createAgent,
Before: createAgentClient,
Flags: []cli.Flag{
secretsFlag,
secretsFileFlag,
silentFlag,
regionFlag,
skipSDKCheckFlag,
dockerFileFlag,
},
// NOTE: since secrets may contain commas, or indeed any special character we might want to treat as a flag separator,
// we disable it entirely here and require multiple --secrets flags to be used.
DisableSliceFlagSeparator: true,
ArgsUsage: "[working-dir]",
},
{
Name: "config",
Usage: fmt.Sprintf("Creates a %s in the working directory for an existing agent.", config.LiveKitTOMLFile),
Before: createAgentClient,
Action: createAgentConfig,
Flags: []cli.Flag{
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "deploy",
Usage: "Deploy a new version of the agent",
Before: createAgentClient,
Action: deployAgent,
Flags: []cli.Flag{
secretsFlag,
secretsFileFlag,
dockerFileFlag,
},
// NOTE: since secrets may contain commas, or indeed any special character we might want to treat as a flag separator,
// we disable it entirely here and require multiple --secrets flags to be used.
DisableSliceFlagSeparator: true,
ArgsUsage: "[working-dir]",
},
{
Name: "status",
Usage: "Get the status of an agent",
Before: createAgentClient,
Action: getAgentStatus,
Flags: []cli.Flag{
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "update",
Usage: "Update an agent metadata and secrets. This will restart the agent.",
Before: createAgentClient,
Action: updateAgent,
Flags: []cli.Flag{
secretsFlag,
secretsFileFlag,
},
// NOTE: since secrets may contain commas, or indeed any special character we might want to treat as a flag separator,
// we disable it entirely here and require multiple --secrets flags to be used.
DisableSliceFlagSeparator: true,
ArgsUsage: "[working-dir]",
},
{
Name: "restart",
Usage: "Restart an agent",
Before: createAgentClient,
Action: restartAgent,
Flags: []cli.Flag{
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "rollback",
Usage: "Rollback an agent to a previous version",
Before: createAgentClient,
Action: rollbackAgent,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "version",
Usage: "Version to rollback to, defaults to most recent previous to current.",
Value: "latest",
Required: true,
},
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "logs",
Aliases: []string{"tail"},
Usage: "Tail logs from agent",
Before: createAgentClient,
Action: getLogs,
Flags: []cli.Flag{
idFlag(false),
logTypeFlag,
},
ArgsUsage: "[working-dir]",
},
{
Name: "delete",
Usage: "Delete an agent",
Before: createAgentClient,
Action: deleteAgent,
Aliases: []string{"destroy"},
Flags: []cli.Flag{
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "versions",
Usage: "List versions of an agent",
Before: createAgentClient,
Action: listAgentVersions,
Flags: []cli.Flag{
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "list",
Usage: "List all LiveKit Cloud Agents",
Action: listAgents,
Before: createAgentClient,
Flags: []cli.Flag{
idSliceFlag,
},
},
{
Name: "secrets",
Usage: "List secrets for an agent",
Before: createAgentClient,
Action: listAgentSecrets,
Flags: []cli.Flag{
idFlag(false),
},
ArgsUsage: "[working-dir]",
},
{
Name: "update-secrets",
Usage: "Update secrets for an agent, will cause a re-start of the agent.",
Before: createAgentClient,
Action: updateAgentSecrets,
Flags: []cli.Flag{
secretsFlag,
secretsFileFlag,
idFlag(false),
&cli.BoolFlag{
Name: "overwrite",
Usage: "If set, will overwrite existing secrets",
Required: false,
Value: false,
},
},
// NOTE: since secrets may contain commas, or indeed any special character we might want to treat as a flag separator,
// we disable it entirely here and require multiple --secrets flags to be used.
DisableSliceFlagSeparator: true,
ArgsUsage: "[working-dir]",
},
},
},
}
subdomainPattern = regexp.MustCompile(`^(?:https?|wss?)://([^.]+)\.`)
agentsClient *lksdk.AgentClient
ignoredSecrets = []string{
"LIVEKIT_API_KEY",
"LIVEKIT_API_SECRET",
"LIVEKIT_URL",
}
)
func createAgentClient(ctx context.Context, cmd *cli.Command) (context.Context, error) {
var err error
if _, err := requireProject(ctx, cmd); err != nil {
return ctx, err
}
if cmd.NArg() > 0 {
workingDir = cmd.Args().First()
}
// If a project has been manually selected that conflicts with the agent's config,
// or if the config file is malformed, this is an error. If the config does not exist,
// we assume it gets created later.
configExists, err := requireConfig(workingDir, tomlFilename)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return ctx, err
}
if configExists {
projectSubdomainMatch := subdomainPattern.FindStringSubmatch(project.URL)
if len(projectSubdomainMatch) < 2 {
return ctx, fmt.Errorf("invalid project URL [%s]", project.URL)
}
if projectSubdomainMatch[1] != lkConfig.Project.Subdomain {
return ctx, fmt.Errorf("project does not match agent subdomain [%s]", lkConfig.Project.Subdomain)
}
}
agentsClient, err = lksdk.NewAgentClient(project.URL, project.APIKey, project.APISecret)
if err != nil {
return ctx, err
}
return ctx, nil
}
func createAgent(ctx context.Context, cmd *cli.Command) error {
subdomainMatches := subdomainPattern.FindStringSubmatch(project.URL)
if len(subdomainMatches) < 2 {
return fmt.Errorf("invalid project URL [%s]", project.URL)
}
// We have a configured project, but don't need to double-confirm if it was
// set via a command line flag, because intent is clear.
if !cmd.IsSet("project") {
useProject := true
if err := huh.NewForm(huh.NewGroup(huh.NewConfirm().
Title(fmt.Sprintf("Use project [%s] with subdomain [%s] to create agent?", project.Name, subdomainMatches[1])).
Value(&useProject).
Inline(false).
WithTheme(util.Theme))).
Run(); err != nil {
return err
}
if !useProject {
if _, err := selectProject(ctx, cmd); err != nil {
return err
}
var err error
// Recreate the client with the new project
agentsClient, err = lksdk.NewAgentClient(project.URL, project.APIKey, project.APISecret)
if err != nil {
return err
}
// Re-parse the project URL to get the subdomain
subdomainMatches = subdomainPattern.FindStringSubmatch(project.URL)
if len(subdomainMatches) < 2 {
return fmt.Errorf("invalid project URL [%s]", project.URL)
}
}
}
logger.Debugw("Creating agent", "working-dir", workingDir)
configExists, err := requireConfig(workingDir, tomlFilename)
if err != nil && configExists {
return err
}
silent := cmd.Bool("silent")
if configExists && lkConfig.Agent != nil {
if !silent {
fmt.Printf("Using agent configuration [%s]\n", util.Accented(tomlFilename))
}
} else {
lkConfig = config.NewLiveKitTOML(subdomainMatches[1]).WithDefaultAgent()
}
if !silent {
fmt.Printf("Creating new agent\n")
}
regions := cmd.StringSlice("regions")
if len(regions) != 0 {
lkConfig.Agent.Regions = regions
}
secrets, err := requireSecrets(ctx, cmd, false, false)
if err != nil {
return err
}
settingsMap, err := getClientSettings(ctx, cmd.Bool("silent"))
if err != nil {
return err
}
projectType, err := agentfs.DetectProjectType(workingDir)
if err != nil {
return fmt.Errorf("unable to determine project type: %w, please use a supported project type, or create your own Dockerfile in the current directory", err)
}
dockerfile := cmd.String("dockerfile")
if dockerfile == "" {
if err := requireDockerfile(ctx, cmd, workingDir, projectType, settingsMap); err != nil {
return err
}
}
if err := agentfs.CheckSDKVersion(workingDir, projectType, settingsMap); err != nil {
if cmd.Bool("skip-sdk-check") {
fmt.Printf("Error checking SDK version: %v, skipping...\n", err)
} else {
return err
}
}
req := &lkproto.CreateAgentRequest{
Secrets: secrets,
Regions: lkConfig.Agent.Regions,
}
resp, err := agentsClient.CreateAgent(ctx, req)
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
lkConfig.Agent.ID = resp.AgentId
lkConfig.Agent.Dockerfile = dockerfile
if err := lkConfig.SaveTOMLFile(workingDir, tomlFilename); err != nil {
return err
}
err = agentfs.UploadTarball(workingDir, resp.PresignedUrl, []string{config.LiveKitTOMLFile})
if err != nil {
return err
}
fmt.Printf("Created agent with ID [%s]\n", util.Accented(resp.AgentId))
err = agentfs.Build(ctx, resp.AgentId, project, dockerfile)
if err != nil {
return err
}
fmt.Println("Build completed - You can view build logs later with `lk agent logs --log-type=build`")
if !silent {
var viewLogs bool = true
if err := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title("Agent deploying. Would you like to view logs?").
Description("You can view logs later with `lk agent logs`").
Value(&viewLogs).
WithTheme(util.Theme),
),
).Run(); err != nil {
return err
} else if viewLogs {
fmt.Println("Tailing logs...safe to exit at any time")
return agentfs.LogHelper(ctx, lkConfig.Agent.ID, "deploy", project)
}
}
return nil
}
func createAgentConfig(ctx context.Context, cmd *cli.Command) error {
if _, err := os.Stat(tomlFilename); err == nil {
var overwrite bool
if err := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title(
fmt.Sprintf("Config file [%s] file already exists. Overwrite?", tomlFilename),
).
Value(&overwrite).
WithTheme(util.Theme),
),
).
Run(); err != nil {
return err
}
if !overwrite {
return fmt.Errorf("config file [%s] already exists", tomlFilename)
}
}
agentID := cmd.String("id")
if agentID == "" {
if err := huh.NewInput().
Title("Agent ID").
Value(&agentID).
WithTheme(util.Theme).
Run(); err != nil {
return err
} else if agentID == "" {
return fmt.Errorf("agent ID is required")
}
}
response, err := agentsClient.ListAgents(ctx, &lkproto.ListAgentsRequest{
AgentId: agentID,
})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if len(response.Agents) == 0 {
return fmt.Errorf("agent not found")
}
subdomainPattern := regexp.MustCompile(`^(?:https?|wss?)://([^.]+)\.`)
matches := subdomainPattern.FindStringSubmatch(project.URL)
if len(matches) < 1 {
return fmt.Errorf("invalid project URL: %s", project.URL)
}
var regions []string
for _, regionalAgent := range response.Agents[0].AgentDeployments {
regions = append(regions, regionalAgent.Region)
}
agent := response.Agents[0]
lkConfig := config.NewLiveKitTOML(matches[1])
lkConfig.Agent = &config.LiveKitTOMLAgentConfig{
ID: agent.AgentId,
Regions: regions,
}
if err := lkConfig.SaveTOMLFile("", tomlFilename); err != nil {
return err
}
return nil
}
func deployAgent(ctx context.Context, cmd *cli.Command) error {
var req *lkproto.DeployAgentRequest
agentId, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
dockerfile := cmd.String("dockerfile")
req = &lkproto.DeployAgentRequest{
AgentId: agentId,
}
secrets, err := requireSecrets(ctx, cmd, false, true)
if err != nil {
return err
}
if len(secrets) > 0 {
req.Secrets = secrets
}
projectType, err := agentfs.DetectProjectType(workingDir)
if err != nil {
return fmt.Errorf("unable to determine project type: %w, please use a supported project type, or create your own Dockerfile in the current directory", err)
}
settingsMap, err := getClientSettings(ctx, cmd.Bool("silent"))
if err != nil {
return err
}
if err := agentfs.CheckSDKVersion(workingDir, projectType, settingsMap); err != nil {
if cmd.Bool("skip-sdk-check") {
fmt.Printf("Error checking SDK version: %v, skipping...\n", err)
} else {
return err
}
}
resp, err := agentsClient.DeployAgent(ctx, req)
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if !resp.Success {
return fmt.Errorf("failed to deploy agent: %s", resp.Message)
}
presignedUrl := resp.PresignedUrl
err = agentfs.UploadTarball(workingDir, presignedUrl, []string{config.LiveKitTOMLFile})
if err != nil {
return err
}
fmt.Printf("Updated agent [%s]\n", util.Accented(resp.AgentId))
err = agentfs.Build(ctx, resp.AgentId, project, dockerfile)
if err != nil {
return err
}
fmt.Println("Deployed agent")
return nil
}
func getAgentStatus(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
res, err := agentsClient.ListAgents(ctx, &lkproto.ListAgentsRequest{
AgentId: agentID,
})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if len(res.Agents) == 0 {
return fmt.Errorf("no agents found")
}
var rows [][]string
for _, agent := range res.Agents {
for _, regionalAgent := range agent.AgentDeployments {
curCPU, err := agentfs.ParseCpu(regionalAgent.CurCpu)
if err != nil {
logger.Errorw("error parsing cpu", err)
}
curMem, err := agentfs.ParseMem(regionalAgent.CurMem, false)
if err != nil {
logger.Errorw("error parsing mem", err)
}
memLimit, err := agentfs.ParseMem(regionalAgent.MemLimit, true)
if err != nil {
logger.Errorw("error parsing mem req", err)
}
rows = append(rows, []string{
agent.AgentId,
agent.Version,
regionalAgent.Region,
regionalAgent.Status,
fmt.Sprintf("%s / %s", curCPU, regionalAgent.CpuLimit),
fmt.Sprintf("%s / %s", curMem, memLimit),
fmt.Sprintf("%d / %d / %d", regionalAgent.Replicas, regionalAgent.MinReplicas, regionalAgent.MaxReplicas),
agent.DeployedAt.AsTime().Format(time.RFC3339),
})
}
}
t := util.CreateTable().
Headers("ID", "Version", "Region", "Status", "CPU", "Mem", "Replicas", "Deployed At").
Rows(rows...)
fmt.Println(t)
return nil
}
func restartAgent(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
resp, err := agentsClient.RestartAgent(ctx, &lkproto.RestartAgentRequest{
AgentId: agentID,
})
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("failed to restart agent: %s", resp.Message)
}
fmt.Printf("Restarted agent [%s]\n", util.Accented(agentID))
return nil
}
func updateAgent(ctx context.Context, cmd *cli.Command) error {
configExists, err := requireConfig(workingDir, tomlFilename)
if err != nil && configExists {
return err
}
if !configExists {
return fmt.Errorf("config file [%s] required to update agent", tomlFilename)
}
if !lkConfig.HasAgent() {
return fmt.Errorf("no agent config found in [%s]", tomlFilename)
}
regions := cmd.StringSlice("regions")
if len(regions) != 0 {
lkConfig.Agent.Regions = regions
}
req := &lkproto.UpdateAgentRequest{
AgentId: lkConfig.Agent.ID,
Regions: lkConfig.Agent.Regions,
}
secrets, err := requireSecrets(ctx, cmd, false, true)
if err != nil {
return err
}
if len(secrets) > 0 {
req.Secrets = secrets
}
var resp *lkproto.UpdateAgentResponse
util.Await("Updating agent ["+util.Accented(lkConfig.Agent.ID)+"]", func() {
resp, err = agentsClient.UpdateAgent(ctx, req)
})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if resp.Success {
fmt.Printf("Updated agent [%s]\n", util.Accented(lkConfig.Agent.ID))
err = lkConfig.SaveTOMLFile("", tomlFilename)
return err
}
return fmt.Errorf("failed to update agent: %s", resp.Message)
}
func rollbackAgent(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
var resp *lkproto.RollbackAgentResponse
util.Await("Rolling back agent ["+util.Accented(agentID)+"]", func() {
resp, err = agentsClient.RollbackAgent(ctx, &lkproto.RollbackAgentRequest{
AgentId: agentID,
Version: cmd.String("version"),
})
})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if !resp.Success {
return fmt.Errorf("failed to rollback agent %s", resp.Message)
}
fmt.Printf("Rolled back agent [%s] to version [%s]\n", util.Accented(agentID), util.Accented(cmd.String("version")))
return nil
}
func getLogs(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
err = agentfs.LogHelper(ctx, agentID, cmd.String("log-type"), project)
return err
}
func deleteAgent(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
var confirmDelete bool
if err := huh.NewForm(
huh.NewGroup(
huh.NewConfirm().
Title(fmt.Sprintf("Are you sure you want to delete agent [%s]?", agentID)).
Value(&confirmDelete).
Inline(false).
WithTheme(util.Theme),
),
).Run(); err != nil {
return err
}
if !confirmDelete {
return nil
}
var res *lkproto.DeleteAgentResponse
var innerErr error
if err := util.Await(
"Deleting agent ["+util.Accented(agentID)+"]",
func() {
if res, innerErr = agentsClient.DeleteAgent(ctx, &lkproto.DeleteAgentRequest{
AgentId: agentID,
}); err != nil {
}
},
); err != nil {
return err
}
if innerErr != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if !res.Success {
return fmt.Errorf("failed to delete agent %s", res.Message)
}
fmt.Printf("Deleted agent [%s]\n", util.Accented(agentID))
return nil
}
func listAgentVersions(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
req := &lkproto.ListAgentVersionsRequest{
AgentId: agentID,
}
versions, err := agentsClient.ListAgentVersions(ctx, req)
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
table := util.CreateTable().
Headers("Version", "Current", "Deployed At")
// Sort versions by created date descending
slices.SortFunc(versions.Versions, func(a, b *lkproto.AgentVersion) int {
return b.CreatedAt.AsTime().Compare(a.CreatedAt.AsTime())
})
for _, version := range versions.Versions {
table.Row(version.Version, fmt.Sprintf("%t", version.Current), version.CreatedAt.AsTime().Format(time.RFC3339))
}
fmt.Println(table)
return nil
}
func listAgents(ctx context.Context, cmd *cli.Command) error {
var items []*lkproto.AgentInfo
if cmd.IsSet("id") {
for _, agentID := range cmd.StringSlice("id") {
if agentID == "" {
continue
}
res, err := agentsClient.ListAgents(ctx, &lkproto.ListAgentsRequest{
AgentId: agentID,
})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
items = append(items, res.Agents...)
}
} else {
agents, err := agentsClient.ListAgents(ctx, &lkproto.ListAgentsRequest{})
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
items = agents.Agents
}
if len(items) == 0 {
fmt.Println("No agents found")
return nil
}
slices.SortFunc(items, func(a, b *lkproto.AgentInfo) int {
return b.DeployedAt.AsTime().Compare(a.DeployedAt.AsTime())
})
var rows [][]string
for _, agent := range items {
var regions []string
for _, regionalAgent := range agent.AgentDeployments {
regions = append(regions, regionalAgent.Region)
}
rows = append(rows, []string{
agent.AgentId,
strings.Join(regions, ","),
agent.Version,
agent.DeployedAt.AsTime().Format(time.RFC3339),
})
}
t := util.CreateTable().
Headers("ID", "Regions", "Version", "Deployed At").
Rows(rows...)
fmt.Println(t)
return nil
}
func listAgentSecrets(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
req := &lkproto.ListAgentSecretsRequest{
AgentId: agentID,
}
secrets, err := agentsClient.ListAgentSecrets(ctx, req)
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
table := util.CreateTable().
Headers("Name", "Created At", "Updated At")
for _, secret := range secrets.Secrets {
// NOTE: Maybe these should be omitted on the server side?
if slices.Contains(ignoredSecrets, secret.Name) {
continue
}
table.Row(secret.Name, secret.CreatedAt.AsTime().Format(time.RFC3339), secret.UpdatedAt.AsTime().Format(time.RFC3339))
}
fmt.Println(table)
return nil
}
func updateAgentSecrets(ctx context.Context, cmd *cli.Command) error {
agentID, err := getAgentID(ctx, cmd, workingDir, tomlFilename)
if err != nil {
return err
}
secrets, err := requireSecrets(ctx, cmd, true, true)
if err != nil {
return err
}
req := &lkproto.UpdateAgentSecretsRequest{
AgentId: agentID,
Secrets: secrets,
Overwrite: cmd.Bool("overwrite"),
}
resp, err := agentsClient.UpdateAgentSecrets(ctx, req)
if err != nil {
if twerr, ok := err.(twirp.Error); ok {
if twerr.Code() == twirp.PermissionDenied {
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
}
}
return err
}
if resp.Success {
fmt.Println("Updated agent secrets")
return nil
}
return fmt.Errorf("failed to update agent secrets: %s", resp.Message)