-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbrowsers.go
More file actions
3810 lines (3452 loc) · 132 KB
/
Copy pathbrowsers.go
File metadata and controls
3810 lines (3452 loc) · 132 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
package cmd
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/kernel/cli/pkg/table"
"github.com/kernel/cli/pkg/util"
"github.com/kernel/kernel-go-sdk"
"github.com/kernel/kernel-go-sdk/option"
"github.com/kernel/kernel-go-sdk/packages/pagination"
"github.com/kernel/kernel-go-sdk/packages/ssestream"
"github.com/kernel/kernel-go-sdk/shared"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// BrowsersService defines the subset of the Kernel SDK browser client that we use.
// See https://github.com/kernel/kernel-go-sdk/blob/main/browser.go
type BrowsersService interface {
Get(ctx context.Context, idOrName string, query kernel.BrowserGetParams, opts ...option.RequestOption) (res *kernel.BrowserGetResponse, err error)
List(ctx context.Context, query kernel.BrowserListParams, opts ...option.RequestOption) (res *pagination.OffsetPagination[kernel.BrowserListResponse], err error)
New(ctx context.Context, body kernel.BrowserNewParams, opts ...option.RequestOption) (res *kernel.BrowserNewResponse, err error)
Update(ctx context.Context, idOrName string, body kernel.BrowserUpdateParams, opts ...option.RequestOption) (res *kernel.BrowserUpdateResponse, err error)
DeleteByID(ctx context.Context, idOrName string, opts ...option.RequestOption) (err error)
HTTPClient(id string, opts ...option.RequestOption) (*http.Client, error)
LoadExtensions(ctx context.Context, id string, body kernel.BrowserLoadExtensionsParams, opts ...option.RequestOption) (err error)
}
// BrowserReplaysService defines the subset we use for browser replays.
type BrowserReplaysService interface {
List(ctx context.Context, id string, opts ...option.RequestOption) (res *[]kernel.BrowserReplayListResponse, err error)
Download(ctx context.Context, replayID string, query kernel.BrowserReplayDownloadParams, opts ...option.RequestOption) (res *http.Response, err error)
Start(ctx context.Context, id string, body kernel.BrowserReplayStartParams, opts ...option.RequestOption) (res *kernel.BrowserReplayStartResponse, err error)
Stop(ctx context.Context, replayID string, body kernel.BrowserReplayStopParams, opts ...option.RequestOption) (err error)
}
// BrowserFSService defines the subset we use for browser filesystem APIs.
type BrowserFSService interface {
NewDirectory(ctx context.Context, id string, body kernel.BrowserFNewDirectoryParams, opts ...option.RequestOption) (err error)
DeleteDirectory(ctx context.Context, id string, body kernel.BrowserFDeleteDirectoryParams, opts ...option.RequestOption) (err error)
DeleteFile(ctx context.Context, id string, body kernel.BrowserFDeleteFileParams, opts ...option.RequestOption) (err error)
DownloadDirZip(ctx context.Context, id string, query kernel.BrowserFDownloadDirZipParams, opts ...option.RequestOption) (res *http.Response, err error)
FileInfo(ctx context.Context, id string, query kernel.BrowserFFileInfoParams, opts ...option.RequestOption) (res *kernel.BrowserFFileInfoResponse, err error)
ListFiles(ctx context.Context, id string, query kernel.BrowserFListFilesParams, opts ...option.RequestOption) (res *[]kernel.BrowserFListFilesResponse, err error)
Move(ctx context.Context, id string, body kernel.BrowserFMoveParams, opts ...option.RequestOption) (err error)
ReadFile(ctx context.Context, id string, query kernel.BrowserFReadFileParams, opts ...option.RequestOption) (res *http.Response, err error)
SetFilePermissions(ctx context.Context, id string, body kernel.BrowserFSetFilePermissionsParams, opts ...option.RequestOption) (err error)
Upload(ctx context.Context, id string, body kernel.BrowserFUploadParams, opts ...option.RequestOption) (err error)
UploadZip(ctx context.Context, id string, body kernel.BrowserFUploadZipParams, opts ...option.RequestOption) (err error)
WriteFile(ctx context.Context, id string, contents io.Reader, body kernel.BrowserFWriteFileParams, opts ...option.RequestOption) (err error)
}
// BrowserProcessService defines the subset we use for browser process APIs.
type BrowserProcessService interface {
Exec(ctx context.Context, id string, body kernel.BrowserProcessExecParams, opts ...option.RequestOption) (res *kernel.BrowserProcessExecResponse, err error)
Kill(ctx context.Context, processID string, params kernel.BrowserProcessKillParams, opts ...option.RequestOption) (res *kernel.BrowserProcessKillResponse, err error)
Resize(ctx context.Context, processID string, params kernel.BrowserProcessResizeParams, opts ...option.RequestOption) (res *kernel.BrowserProcessResizeResponse, err error)
Spawn(ctx context.Context, id string, body kernel.BrowserProcessSpawnParams, opts ...option.RequestOption) (res *kernel.BrowserProcessSpawnResponse, err error)
Status(ctx context.Context, processID string, query kernel.BrowserProcessStatusParams, opts ...option.RequestOption) (res *kernel.BrowserProcessStatusResponse, err error)
Stdin(ctx context.Context, processID string, params kernel.BrowserProcessStdinParams, opts ...option.RequestOption) (res *kernel.BrowserProcessStdinResponse, err error)
StdoutStreamStreaming(ctx context.Context, processID string, query kernel.BrowserProcessStdoutStreamParams, opts ...option.RequestOption) (stream *ssestream.Stream[kernel.BrowserProcessStdoutStreamResponse])
}
// BrowserFWatchService defines the subset we use for browser filesystem watch APIs.
type BrowserFWatchService interface {
EventsStreaming(ctx context.Context, watchID string, query kernel.BrowserFWatchEventsParams, opts ...option.RequestOption) (stream *ssestream.Stream[kernel.BrowserFWatchEventsResponse])
Start(ctx context.Context, id string, body kernel.BrowserFWatchStartParams, opts ...option.RequestOption) (res *kernel.BrowserFWatchStartResponse, err error)
Stop(ctx context.Context, watchID string, body kernel.BrowserFWatchStopParams, opts ...option.RequestOption) (err error)
}
// BrowserLogService defines the subset we use for browser log APIs.
type BrowserLogService interface {
StreamStreaming(ctx context.Context, id string, query kernel.BrowserLogStreamParams, opts ...option.RequestOption) (stream *ssestream.Stream[shared.LogEvent])
}
// BrowserPlaywrightService defines the subset we use for Playwright execution.
type BrowserPlaywrightService interface {
Execute(ctx context.Context, id string, body kernel.BrowserPlaywrightExecuteParams, opts ...option.RequestOption) (res *kernel.BrowserPlaywrightExecuteResponse, err error)
}
// BrowserComputerService defines the subset we use for OS-level mouse & screen.
type BrowserComputerService interface {
Batch(ctx context.Context, id string, body kernel.BrowserComputerBatchParams, opts ...option.RequestOption) (err error)
CaptureScreenshot(ctx context.Context, id string, body kernel.BrowserComputerCaptureScreenshotParams, opts ...option.RequestOption) (res *http.Response, err error)
ClickMouse(ctx context.Context, id string, body kernel.BrowserComputerClickMouseParams, opts ...option.RequestOption) (err error)
DragMouse(ctx context.Context, id string, body kernel.BrowserComputerDragMouseParams, opts ...option.RequestOption) (err error)
GetMousePosition(ctx context.Context, id string, opts ...option.RequestOption) (res *kernel.BrowserComputerGetMousePositionResponse, err error)
MoveMouse(ctx context.Context, id string, body kernel.BrowserComputerMoveMouseParams, opts ...option.RequestOption) (err error)
PressKey(ctx context.Context, id string, body kernel.BrowserComputerPressKeyParams, opts ...option.RequestOption) (err error)
ReadClipboard(ctx context.Context, id string, opts ...option.RequestOption) (res *kernel.BrowserComputerReadClipboardResponse, err error)
Scroll(ctx context.Context, id string, body kernel.BrowserComputerScrollParams, opts ...option.RequestOption) (err error)
SetCursorVisibility(ctx context.Context, id string, body kernel.BrowserComputerSetCursorVisibilityParams, opts ...option.RequestOption) (res *kernel.BrowserComputerSetCursorVisibilityResponse, err error)
TypeText(ctx context.Context, id string, body kernel.BrowserComputerTypeTextParams, opts ...option.RequestOption) (err error)
WriteClipboard(ctx context.Context, id string, body kernel.BrowserComputerWriteClipboardParams, opts ...option.RequestOption) (err error)
}
// Regular expression to validate CUID2 identifiers (starts with a letter, 24 lowercase alphanumeric characters).
var cuidRegex = regexp.MustCompile(`^[a-z][a-z0-9]{23}$`)
// getAvailableViewports returns the list of supported viewport configurations.
func getAvailableViewports() []string {
return []string{
"2560x1440@10",
"1920x1080@25",
"1920x1200@25",
"1440x900@25",
"1280x800@60",
"1024x768@60",
"1200x800@60",
}
}
// parseViewport parses a viewport string (e.g., "1920x1080@25") and returns width, height, and refresh rate.
// Returns error if the format is invalid.
func parseViewport(viewport string) (width, height, refreshRate int64, err error) {
parts := strings.Split(viewport, "@")
var dimStr string
if len(parts) == 1 {
dimStr = parts[0]
refreshRate = 0
} else if len(parts) == 2 {
dimStr = parts[0]
rr, parseErr := strconv.ParseInt(parts[1], 10, 64)
if parseErr != nil {
return 0, 0, 0, fmt.Errorf("invalid refresh rate: %v", parseErr)
}
refreshRate = rr
} else {
return 0, 0, 0, fmt.Errorf("invalid viewport format")
}
dims := strings.Split(dimStr, "x")
if len(dims) != 2 {
return 0, 0, 0, fmt.Errorf("invalid viewport format, expected WIDTHxHEIGHT[@RATE]")
}
w, err := strconv.ParseInt(dims[0], 10, 64)
if err != nil {
return 0, 0, 0, fmt.Errorf("invalid width: %v", err)
}
h, err := strconv.ParseInt(dims[1], 10, 64)
if err != nil {
return 0, 0, 0, fmt.Errorf("invalid height: %v", err)
}
return w, h, refreshRate, nil
}
// parseChromePolicy resolves the --chrome-policy / --chrome-policy-file inputs into a
// custom Chrome enterprise policy object. The two inputs are mutually exclusive (enforced
// by cobra); a file path of "-" reads stdin. It returns a nil map when neither input is
// set or the content is empty. An explicit empty object ("{}") yields a non-nil empty map,
// so callers must guard the SDK assignment with len>0: chrome_policy uses omitzero, which
// drops only a nil map, not an empty one.
func parseChromePolicy(inline, file string) (map[string]any, error) {
data := strings.TrimSpace(inline)
if file != "" {
var b []byte
var err error
if file == "-" {
b, err = io.ReadAll(os.Stdin)
} else {
b, err = os.ReadFile(file)
}
if err != nil {
return nil, fmt.Errorf("failed to read chrome policy file: %w", err)
}
data = strings.TrimSpace(string(b))
}
if data == "" {
return nil, nil
}
policy := map[string]any{}
if err := json.Unmarshal([]byte(data), &policy); err != nil {
return nil, fmt.Errorf("invalid JSON in chrome policy (must be a JSON object): %w", err)
}
if policy == nil {
// json.Unmarshal of the literal `null` succeeds but nils the map.
return nil, fmt.Errorf("chrome policy must be a JSON object, not null")
}
return policy, nil
}
// parseKeyValueSpecs parses repeated KEY=VALUE flag values into a map. It
// returns the parsed pairs along with any specs that were malformed (missing
// "=" or an empty key), mirroring the kernel hypeman CLI convention.
func parseKeyValueSpecs(specs []string) (map[string]string, []string) {
values := make(map[string]string)
var malformed []string
for _, spec := range specs {
parts := strings.SplitN(spec, "=", 2)
if len(parts) != 2 || parts[0] == "" {
malformed = append(malformed, spec)
continue
}
values[parts[0]] = parts[1]
}
return values, malformed
}
// tagsFromFlag reads a repeated KEY=VALUE flag and parses it into a map,
// warning about any malformed entries. It returns the parsed tags (nil when no
// valid pairs are set) and whether the flag was provided on the command line.
//
// "Provided" keys off Changed, not len(specs): pflag records an empty `--tag=`
// as Changed-but-empty, and that must still count as provided so the update
// path rejects it (or `--tag= --clear-tags`) instead of silently ignoring it.
func tagsFromFlag(cmd *cobra.Command, flagName string) (map[string]string, bool) {
provided := cmd.Flags().Changed(flagName)
specs, _ := cmd.Flags().GetStringArray(flagName)
tags, malformed := parseKeyValueSpecs(specs)
for _, invalid := range malformed {
pterm.Warning.Printf("Ignoring malformed tag: %s\n", invalid)
}
if len(tags) == 0 {
return nil, provided
}
return tags, provided
}
// formatTags renders tags as a deterministic "k=v, k2=v2" string with keys
// sorted, for display in detail tables.
func formatTags(tags kernel.Tags) string {
if len(tags) == 0 {
return ""
}
keys := make([]string, 0, len(tags))
for k := range tags {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(tags))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%s", k, tags[k]))
}
return strings.Join(parts, ", ")
}
// Inputs for each command
type BrowsersCreateInput struct {
TimeoutSeconds int
Stealth BoolFlag
Headless BoolFlag
GPU BoolFlag
InvocationID string
Kiosk BoolFlag
ProfileID string
ProfileName string
ProfileSaveChanges BoolFlag
ProxyID string
StartURL string
Extensions []string
Viewport string
Telemetry string
ChromePolicy string
ChromePolicyFile string
Name string
Tags map[string]string
Output string
}
type BrowsersDeleteInput struct {
Identifier string
}
type BrowsersViewInput struct {
Identifier string
Output string
}
type BrowsersGetInput struct {
Identifier string
IncludeDeleted bool
Output string
}
type BrowsersUpdateInput struct {
Identifier string
ProxyID string
ClearProxy bool
ProfileID string
ProfileName string
ProfileSaveChanges BoolFlag
Viewport string
Force bool
Telemetry string
Name string
SetName bool
ClearName bool
Tags map[string]string
TagsProvided bool
ClearTags bool
Output string
}
// BrowsersCmd is a cobra-independent command handler for browsers operations.
type BrowsersCmd struct {
browsers BrowsersService
replays BrowserReplaysService
fs BrowserFSService
fsWatch BrowserFWatchService
process BrowserProcessService
logs BrowserLogService
computer BrowserComputerService
playwright BrowserPlaywrightService
telemetry BrowserTelemetryService
}
type BrowsersListInput struct {
Output string
IncludeDeleted bool
Status string
Limit int
Offset int
Query string
Tags map[string]string
}
func (b BrowsersCmd) List(ctx context.Context, in BrowsersListInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
params := kernel.BrowserListParams{}
// Use new Status parameter if provided, otherwise fall back to deprecated IncludeDeleted
if in.Status != "" {
switch in.Status {
case "active":
params.Status = kernel.BrowserListParamsStatusActive
case "deleted":
params.Status = kernel.BrowserListParamsStatusDeleted
case "all":
params.Status = kernel.BrowserListParamsStatusAll
default:
return fmt.Errorf("invalid --status value: %s (must be 'active', 'deleted', or 'all')", in.Status)
}
} else if in.IncludeDeleted {
params.IncludeDeleted = kernel.Opt(true)
}
if in.Limit > 0 {
params.Limit = kernel.Opt(int64(in.Limit))
}
if in.Offset > 0 {
params.Offset = kernel.Opt(int64(in.Offset))
}
if in.Query != "" {
params.Query = kernel.Opt(in.Query)
}
if len(in.Tags) > 0 {
params.Tags = in.Tags
}
page, err := b.browsers.List(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
var browsers []kernel.BrowserListResponse
if page != nil {
browsers = page.Items
}
if in.Output == "json" {
return util.PrintPrettyJSONSlice(browsers)
}
if len(browsers) == 0 {
pterm.Info.Println("No running browsers found")
return nil
}
// Prepare table data
headers := []string{"Browser ID", "Name", "Created At", "Profile", "Pool", "CDP WS URL", "Live View URL"}
showDeletedAt := in.IncludeDeleted || in.Status == "deleted" || in.Status == "all"
if showDeletedAt {
headers = append(headers, "Deleted At")
}
tableData := pterm.TableData{headers}
for _, browser := range browsers {
profile := "-"
if browser.Profile.Name != "" {
profile = browser.Profile.Name
} else if browser.Profile.ID != "" {
profile = browser.Profile.ID
}
pool := "-"
if browser.Pool.Name != "" {
pool = browser.Pool.Name
} else if browser.Pool.ID != "" {
pool = browser.Pool.ID
}
row := []string{
browser.SessionID,
util.OrDash(browser.Name),
util.FormatLocal(browser.CreatedAt),
profile,
pool,
truncateURL(browser.CdpWsURL, 50),
truncateURL(browser.BrowserLiveViewURL, 50),
}
if showDeletedAt {
deletedAt := "-"
if !browser.DeletedAt.IsZero() {
deletedAt = util.FormatLocal(browser.DeletedAt)
}
row = append(row, deletedAt)
}
tableData = append(tableData, row)
}
PrintTableNoPad(tableData, true)
return nil
}
func (b BrowsersCmd) Create(ctx context.Context, in BrowsersCreateInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
if err := validateStartURLFlag(in.StartURL); err != nil {
return err
}
params := kernel.BrowserNewParams{}
if in.TimeoutSeconds > 0 {
params.TimeoutSeconds = kernel.Opt(int64(in.TimeoutSeconds))
}
if in.Stealth.Set {
params.Stealth = kernel.Opt(in.Stealth.Value)
}
if in.Headless.Set {
params.Headless = kernel.Opt(in.Headless.Value)
}
if in.GPU.Set {
params.GPU = kernel.Opt(in.GPU.Value)
}
if in.InvocationID != "" {
params.InvocationID = kernel.Opt(in.InvocationID)
}
if in.Kiosk.Set {
params.KioskMode = kernel.Opt(in.Kiosk.Value)
}
// Validate profile selection: at most one of profile-id or profile-name must be provided
if in.ProfileID != "" && in.ProfileName != "" {
pterm.Error.Println("must specify at most one of --profile-id or --profile-name")
return nil
} else if in.ProfileID != "" || in.ProfileName != "" {
params.Profile = kernel.BrowserProfileParam{
SaveChanges: kernel.Opt(in.ProfileSaveChanges.Value),
}
if in.ProfileID != "" {
params.Profile.ID = kernel.Opt(in.ProfileID)
} else if in.ProfileName != "" {
params.Profile.Name = kernel.Opt(in.ProfileName)
}
}
// Add proxy if specified
if in.ProxyID != "" {
params.ProxyID = kernel.Opt(in.ProxyID)
}
if in.StartURL != "" {
params.StartURL = kernel.Opt(in.StartURL)
}
// Map extensions (IDs or names) into params.Extensions
if len(in.Extensions) > 0 {
for _, ext := range in.Extensions {
val := strings.TrimSpace(ext)
if val == "" {
continue
}
item := kernel.BrowserExtensionParam{}
if cuidRegex.MatchString(val) {
item.ID = kernel.Opt(val)
} else {
item.Name = kernel.Opt(val)
}
params.Extensions = append(params.Extensions, item)
}
}
// Add viewport if specified
if in.Viewport != "" {
width, height, refreshRate, err := parseViewport(in.Viewport)
if err != nil {
pterm.Error.Printf("Invalid viewport format: %v\n", err)
return nil
}
params.Viewport = kernel.BrowserViewportParam{
Width: width,
Height: height,
}
if refreshRate > 0 {
params.Viewport.RefreshRate = kernel.Opt(refreshRate)
}
}
if in.Telemetry != "" {
t, err := buildNewTelemetryParam(in.Telemetry)
if err != nil {
return err
}
params.Telemetry = t
}
chromePolicy, err := parseChromePolicy(in.ChromePolicy, in.ChromePolicyFile)
if err != nil {
return err
}
if len(chromePolicy) > 0 {
params.ChromePolicy = chromePolicy
}
if in.Name != "" {
params.Name = kernel.Opt(in.Name)
}
if len(in.Tags) > 0 {
params.Tags = kernel.Tags(in.Tags)
}
if in.Output != "json" {
pterm.Info.Println("Creating browser session...")
}
browser, err := b.browsers.New(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(browser)
}
printBrowserSessionResult(browser.SessionID, browser.CdpWsURL, browser.BrowserLiveViewURL, browser.Profile, browser.StartURL, browser.Name, browser.Tags)
if in.Telemetry != "" {
printTelemetrySummary(browser.Telemetry)
}
return nil
}
func printBrowserSessionResult(sessionID, cdpURL, liveViewURL string, profile kernel.Profile, startURL, name string, tags kernel.Tags) {
tableData := buildBrowserTableData(sessionID, cdpURL, liveViewURL, profile, startURL, name, tags)
PrintTableNoPad(tableData, true)
}
// buildBrowserTableData creates a base table with common browser session fields.
func buildBrowserTableData(sessionID, cdpURL, liveViewURL string, profile kernel.Profile, startURL, name string, tags kernel.Tags) pterm.TableData {
tableData := pterm.TableData{
{"Property", "Value"},
{"Session ID", sessionID},
}
if name != "" {
tableData = append(tableData, []string{"Name", name})
}
tableData = append(tableData, []string{"CDP WebSocket URL", cdpURL})
if liveViewURL != "" {
tableData = append(tableData, []string{"Live View URL", liveViewURL})
}
if profile.ID != "" || profile.Name != "" {
profVal := profile.Name
if profVal == "" {
profVal = profile.ID
}
tableData = append(tableData, []string{"Profile", profVal})
}
if startURL != "" {
tableData = append(tableData, []string{"Start URL", startURL})
}
if len(tags) > 0 {
tableData = append(tableData, []string{"Tags", formatTags(tags)})
}
return tableData
}
func (b BrowsersCmd) Delete(ctx context.Context, in BrowsersDeleteInput) error {
// Treat not found as a success (idempotent delete)
if err := b.browsers.DeleteByID(ctx, in.Identifier); err != nil && !util.IsNotFound(err) {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Successfully deleted (or already absent) browser: %s\n", in.Identifier)
return nil
}
func (b BrowsersCmd) View(ctx context.Context, in BrowsersViewInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
browser, err := b.browsers.Get(ctx, in.Identifier, kernel.BrowserGetParams{})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
// View command returns a custom response, not the full browser object
// Use json.Marshal to ensure proper JSON escaping of the URL
urlBytes, err := json.Marshal(browser.BrowserLiveViewURL)
if err != nil {
return err
}
fmt.Printf("{\n \"liveViewUrl\": %s\n}\n", urlBytes)
return nil
}
if browser.BrowserLiveViewURL == "" {
if browser.Headless {
pterm.Warning.Println("This browser is running in headless mode and does not have a live view URL")
} else {
pterm.Warning.Println("No live view URL available for this browser")
}
return nil
}
fmt.Println(browser.BrowserLiveViewURL)
return nil
}
func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
query := kernel.BrowserGetParams{}
if in.IncludeDeleted {
query.IncludeDeleted = kernel.Opt(true)
}
browser, err := b.browsers.Get(ctx, in.Identifier, query)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(browser)
}
// Build table starting with common browser fields
tableData := buildBrowserTableData(
browser.SessionID,
browser.CdpWsURL,
browser.BrowserLiveViewURL,
browser.Profile,
browser.StartURL,
browser.Name,
browser.Tags,
)
// Append additional detailed fields
tableData = append(tableData, []string{"Created At", util.FormatLocal(browser.CreatedAt)})
tableData = append(tableData, []string{"Timeout (seconds)", fmt.Sprintf("%d", browser.TimeoutSeconds)})
tableData = append(tableData, []string{"Headless", fmt.Sprintf("%t", browser.Headless)})
tableData = append(tableData, []string{"Stealth", fmt.Sprintf("%t", browser.Stealth)})
tableData = append(tableData, []string{"GPU", fmt.Sprintf("%t", browser.GPU)})
tableData = append(tableData, []string{"Kiosk Mode", fmt.Sprintf("%t", browser.KioskMode)})
if browser.Viewport.Width > 0 && browser.Viewport.Height > 0 {
viewportStr := fmt.Sprintf("%dx%d", browser.Viewport.Width, browser.Viewport.Height)
if browser.Viewport.RefreshRate > 0 {
viewportStr = fmt.Sprintf("%s@%d", viewportStr, browser.Viewport.RefreshRate)
}
tableData = append(tableData, []string{"Viewport", viewportStr})
}
if browser.ProxyID != "" {
tableData = append(tableData, []string{"Proxy ID", browser.ProxyID})
}
if !browser.DeletedAt.IsZero() {
tableData = append(tableData, []string{"Deleted At", util.FormatLocal(browser.DeletedAt)})
}
PrintTableNoPad(tableData, true)
return nil
}
func (b BrowsersCmd) Update(ctx context.Context, in BrowsersUpdateInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
// Validate profile selection: at most one of profile-id or profile-name must be provided
if in.ProfileID != "" && in.ProfileName != "" {
return fmt.Errorf("must specify at most one of --profile-id or --profile-name")
}
// Cannot specify both --proxy-id and --clear-proxy
if in.ProxyID != "" && in.ClearProxy {
return fmt.Errorf("cannot specify both --proxy-id and --clear-proxy")
}
// Cannot specify both --name and --clear-name
if in.SetName && in.ClearName {
return fmt.Errorf("cannot specify both --name and --clear-name")
}
// Cannot specify both --tag and --clear-tags. TagsProvided (whether the flag
// was passed) is the authoritative signal so the check still fires when every
// --tag value was malformed and dropped to an empty map.
if (in.TagsProvided || len(in.Tags) > 0) && in.ClearTags {
return fmt.Errorf("cannot specify both --tag and --clear-tags")
}
// --tag was provided but parsed to zero valid pairs (every value malformed).
// Treat as a user error rather than silently leaving tags unchanged.
if in.TagsProvided && len(in.Tags) == 0 {
return fmt.Errorf("no valid --tag KEY=VALUE pairs provided")
}
// --name must carry a value; clearing is done explicitly via --clear-name.
// (A set name combined with --clear-name is already rejected above, so the
// ClearName case cannot reach here.)
if in.SetName && in.Name == "" {
return fmt.Errorf("--name requires a non-empty value; use --clear-name to clear the name")
}
hasProxyChange := in.ProxyID != "" || in.ClearProxy
hasProfileChange := in.ProfileID != "" || in.ProfileName != ""
hasViewportChange := in.Viewport != ""
// By this point a set name is guaranteed non-empty (the guard above rejects --name "").
hasNameChange := in.SetName || in.ClearName
hasTagsChange := len(in.Tags) > 0 || in.ClearTags
// Validate --save-changes is only used with a profile
if in.ProfileSaveChanges.Set && !hasProfileChange {
return fmt.Errorf("--save-changes requires --profile-id or --profile-name")
}
// Validate --force is only used with a viewport change
if in.Force && !hasViewportChange {
return fmt.Errorf("--force requires --viewport")
}
// Validate that at least one update option is provided
if !hasProxyChange && !hasProfileChange && !hasViewportChange && in.Telemetry == "" && !hasNameChange && !hasTagsChange {
return fmt.Errorf("must specify at least one of: --proxy-id, --clear-proxy, --profile-id, --profile-name, --viewport, --telemetry, --name, --clear-name, --tag, or --clear-tags")
}
params := kernel.BrowserUpdateParams{}
// Handle name changes
if in.ClearName {
params.Name = kernel.Opt("")
} else if in.SetName {
params.Name = kernel.Opt(in.Name)
}
// Handle tag changes. Tags are a full replace, not a merge: providing --tag
// replaces the entire set, and --clear-tags removes all tags.
if in.ClearTags {
params.Tags = kernel.Tags{}
} else if len(in.Tags) > 0 {
params.Tags = kernel.Tags(in.Tags)
}
// Handle proxy changes
if in.ClearProxy {
params.ProxyID = kernel.Opt("")
} else if in.ProxyID != "" {
params.ProxyID = kernel.Opt(in.ProxyID)
}
// Handle profile changes
if hasProfileChange {
params.Profile = shared.BrowserProfileParam{}
if in.ProfileID != "" {
params.Profile.ID = kernel.Opt(in.ProfileID)
} else if in.ProfileName != "" {
params.Profile.Name = kernel.Opt(in.ProfileName)
}
if in.ProfileSaveChanges.Set {
params.Profile.SaveChanges = kernel.Opt(in.ProfileSaveChanges.Value)
}
}
// Handle telemetry changes
if in.Telemetry != "" {
t, err := buildUpdateTelemetryParam(in.Telemetry)
if err != nil {
return err
}
params.Telemetry = t
}
// Handle viewport changes
if hasViewportChange {
width, height, refreshRate, err := parseViewport(in.Viewport)
if err != nil {
return fmt.Errorf("invalid viewport format: %v", err)
}
params.Viewport = kernel.BrowserUpdateParamsViewport{
BrowserViewportParam: shared.BrowserViewportParam{
Width: width,
Height: height,
},
}
if refreshRate > 0 {
params.Viewport.RefreshRate = kernel.Opt(refreshRate)
}
if in.Force {
params.Viewport.Force = kernel.Opt(true)
}
}
if in.Output != "json" {
pterm.Info.Printf("Updating browser %s...\n", in.Identifier)
}
browser, err := b.browsers.Update(ctx, in.Identifier, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(browser)
}
pterm.Success.Printf("Updated browser %s\n", browser.SessionID)
if hasNameChange {
pterm.Info.Printf("Name: %s\n", util.OrDash(browser.Name))
}
if hasTagsChange {
pterm.Info.Printf("Tags: %s\n", util.OrDash(formatTags(browser.Tags)))
}
if in.Telemetry != "" {
printTelemetrySummary(browser.Telemetry)
}
return nil
}
// Logs
type BrowsersLogsStreamInput struct {
Identifier string
Source string
Follow BoolFlag
Path string
SupervisorProcess string
}
func (b BrowsersCmd) LogsStream(ctx context.Context, in BrowsersLogsStreamInput) error {
if b.logs == nil {
pterm.Error.Println("logs service not available")
return nil
}
br, err := b.browsers.Get(ctx, in.Identifier, kernel.BrowserGetParams{})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
params := kernel.BrowserLogStreamParams{Source: kernel.BrowserLogStreamParamsSource(in.Source)}
if in.Follow.Set {
params.Follow = kernel.Opt(in.Follow.Value)
}
if in.Path != "" {
params.Path = kernel.Opt(in.Path)
}
if in.SupervisorProcess != "" {
params.SupervisorProcess = kernel.Opt(in.SupervisorProcess)
}
stream := b.logs.StreamStreaming(ctx, br.SessionID, params)
if stream == nil {
pterm.Error.Println("failed to open log stream")
return nil
}
defer stream.Close()
for stream.Next() {
ev := stream.Current()
pterm.Println(fmt.Sprintf("[%s] %s", util.FormatLocal(ev.Timestamp), ev.Message))
}
if err := stream.Err(); err != nil {
return util.CleanedUpSdkError{Err: err}
}
return nil
}
// Computer (mouse/screen)
type BrowsersComputerClickMouseInput struct {
Identifier string
X int64
Y int64
NumClicks int64
Button string
ClickType string
HoldKeys []string
}
type BrowsersComputerMoveMouseInput struct {
Identifier string
X int64
Y int64
HoldKeys []string
Smooth *bool
DurationMs *int64
}
type BrowsersComputerScreenshotInput struct {
Identifier string
X int64
Y int64
Width int64
Height int64
To string
HasRegion bool
}
type BrowsersComputerTypeTextInput struct {
Identifier string
Text string
Delay int64
}
type BrowsersComputerPressKeyInput struct {
Identifier string
Keys []string
Duration int64
HoldKeys []string
}
type BrowsersComputerScrollInput struct {
Identifier string
X int64
Y int64
DeltaX int64
DeltaXSet bool
DeltaY int64
DeltaYSet bool
HoldKeys []string
}
type BrowsersComputerDragMouseInput struct {
Identifier string
Path [][]int64
Delay int64
StepDelayMs int64
StepsPerSegment int64
Button string
HoldKeys []string
Smooth *bool
DurationMs *int64
}
type BrowsersComputerSetCursorInput struct {
Identifier string
Hidden bool
}
type BrowsersComputerGetMousePositionInput struct {
Identifier string
Output string
}
type BrowsersComputerBatchInput struct {
Identifier string
ActionsJSON string
}
type BrowsersComputerReadClipboardInput struct {
Identifier string
Output string
}
type BrowsersComputerWriteClipboardInput struct {
Identifier string
Text string
}
func (b BrowsersCmd) ComputerClickMouse(ctx context.Context, in BrowsersComputerClickMouseInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.browsers.Get(ctx, in.Identifier, kernel.BrowserGetParams{})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
body := kernel.BrowserComputerClickMouseParams{X: in.X, Y: in.Y}
if in.NumClicks > 0 {
body.NumClicks = kernel.Opt(in.NumClicks)
}
if in.Button != "" {
body.Button = kernel.BrowserComputerClickMouseParamsButton(in.Button)
}
if in.ClickType != "" {
body.ClickType = kernel.BrowserComputerClickMouseParamsClickType(in.ClickType)