-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbrowsers.go
More file actions
2546 lines (2334 loc) · 88.1 KB
/
browsers.go
File metadata and controls
2546 lines (2334 loc) · 88.1 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"
"strconv"
"strings"
"github.com/onkernel/cli/pkg/util"
"github.com/onkernel/kernel-go-sdk"
"github.com/onkernel/kernel-go-sdk/option"
"github.com/onkernel/kernel-go-sdk/packages/ssestream"
"github.com/onkernel/kernel-go-sdk/shared"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
)
// BrowsersService defines the subset of the Kernel SDK browser client that we use.
// See https://github.com/onkernel/kernel-go-sdk/blob/main/browser.go
type BrowsersService interface {
List(ctx context.Context, opts ...option.RequestOption) (res *[]kernel.BrowserListResponse, err error)
New(ctx context.Context, body kernel.BrowserNewParams, opts ...option.RequestOption) (res *kernel.BrowserNewResponse, err error)
Delete(ctx context.Context, body kernel.BrowserDeleteParams, opts ...option.RequestOption) (err error)
DeleteByID(ctx context.Context, id string, opts ...option.RequestOption) (err 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)
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])
}
// 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 {
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)
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)
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)
}
// BoolFlag captures whether a boolean flag was set explicitly and its value.
type BoolFlag struct {
Set bool
Value bool
}
// Regular expression to validate CUID2 identifiers (24 lowercase alphanumeric characters).
var cuidRegex = regexp.MustCompile(`^[a-z0-9]{24}$`)
// getAvailableViewports returns the list of supported viewport configurations.
func getAvailableViewports() []string {
return []string{
"2560x1440@10",
"1920x1080@25",
"1920x1200@25",
"1440x900@25",
"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
}
// Inputs for each command
type BrowsersCreateInput struct {
PersistenceID string
TimeoutSeconds int
Stealth BoolFlag
Headless BoolFlag
Kiosk BoolFlag
ProfileID string
ProfileName string
ProfileSaveChanges BoolFlag
ProxyID string
Extensions []string
Viewport string
}
type BrowsersDeleteInput struct {
Identifier string
SkipConfirm bool
}
type BrowsersViewInput struct {
Identifier string
}
// BrowsersCmd is a cobra-independent command handler for browsers operations.
type BrowsersCmd struct {
browsers BrowsersService
replays BrowserReplaysService
fs BrowserFSService
process BrowserProcessService
logs BrowserLogService
computer BrowserComputerService
playwright BrowserPlaywrightService
}
type BrowsersListInput struct {
Output string
}
func (b BrowsersCmd) List(ctx context.Context, in BrowsersListInput) error {
if in.Output != "" && in.Output != "json" {
pterm.Error.Println("unsupported --output value: use 'json'")
return nil
}
browsers, err := b.browsers.List(ctx)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
if browsers == nil {
fmt.Println("[]")
return nil
}
bs, err := json.MarshalIndent(*browsers, "", " ")
if err != nil {
return err
}
fmt.Println(string(bs))
return nil
}
if browsers == nil || len(*browsers) == 0 {
pterm.Info.Println("No running or persistent browsers found")
return nil
}
// Prepare table data
tableData := pterm.TableData{
{"Browser ID", "Created At", "Persistent ID", "Profile", "CDP WS URL", "Live View URL"},
}
for _, browser := range *browsers {
persistentID := "-"
if browser.Persistence.ID != "" {
persistentID = browser.Persistence.ID
}
profile := "-"
if browser.Profile.Name != "" {
profile = browser.Profile.Name
} else if browser.Profile.ID != "" {
profile = browser.Profile.ID
}
tableData = append(tableData, []string{
browser.SessionID,
util.FormatLocal(browser.CreatedAt),
persistentID,
profile,
truncateURL(browser.CdpWsURL, 50),
truncateURL(browser.BrowserLiveViewURL, 50),
})
}
PrintTableNoPad(tableData, true)
return nil
}
func (b BrowsersCmd) Create(ctx context.Context, in BrowsersCreateInput) error {
pterm.Info.Println("Creating browser session...")
params := kernel.BrowserNewParams{}
if in.PersistenceID != "" {
params.Persistence = kernel.BrowserPersistenceParam{ID: in.PersistenceID}
}
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.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.BrowserNewParamsProfile{
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)
}
// 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.BrowserNewParamsExtension{}
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.BrowserNewParamsViewport{
Width: width,
Height: height,
}
if refreshRate > 0 {
params.Viewport.RefreshRate = kernel.Opt(refreshRate)
}
}
browser, err := b.browsers.New(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
tableData := pterm.TableData{
{"Property", "Value"},
{"Session ID", browser.SessionID},
{"CDP WebSocket URL", browser.CdpWsURL},
}
if browser.BrowserLiveViewURL != "" {
tableData = append(tableData, []string{"Live View URL", browser.BrowserLiveViewURL})
}
if browser.Persistence.ID != "" {
tableData = append(tableData, []string{"Persistent ID", browser.Persistence.ID})
}
if browser.Profile.ID != "" || browser.Profile.Name != "" {
profVal := browser.Profile.Name
if profVal == "" {
profVal = browser.Profile.ID
}
tableData = append(tableData, []string{"Profile", profVal})
}
PrintTableNoPad(tableData, true)
return nil
}
func (b BrowsersCmd) Delete(ctx context.Context, in BrowsersDeleteInput) error {
if !in.SkipConfirm {
browsers, err := b.browsers.List(ctx)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if browsers == nil || len(*browsers) == 0 {
pterm.Error.Println("No browsers found")
return nil
}
var found *kernel.BrowserListResponse
for _, br := range *browsers {
if br.SessionID == in.Identifier || br.Persistence.ID == in.Identifier {
bCopy := br
found = &bCopy
break
}
}
if found == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
var confirmMsg string
if found.Persistence.ID == in.Identifier {
confirmMsg = fmt.Sprintf("Are you sure you want to delete browser with persistent ID \"%s\"?", in.Identifier)
} else {
confirmMsg = fmt.Sprintf("Are you sure you want to delete browser with ID \"%s\"?", in.Identifier)
}
pterm.DefaultInteractiveConfirm.DefaultText = confirmMsg
result, _ := pterm.DefaultInteractiveConfirm.Show()
if !result {
pterm.Info.Println("Deletion cancelled")
return nil
}
if found.Persistence.ID == in.Identifier {
pterm.Info.Printf("Deleting browser with persistent ID: %s\n", in.Identifier)
err = b.browsers.Delete(ctx, kernel.BrowserDeleteParams{PersistentID: in.Identifier})
if err != nil && !util.IsNotFound(err) {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Successfully deleted browser with persistent ID: %s\n", in.Identifier)
return nil
}
pterm.Info.Printf("Deleting browser with ID: %s\n", in.Identifier)
err = b.browsers.DeleteByID(ctx, in.Identifier)
if err != nil && !util.IsNotFound(err) {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Successfully deleted browser with ID: %s\n", in.Identifier)
return nil
}
// Skip confirmation: try both deletion modes without listing first
// Treat not found as a success (idempotent delete)
var nonNotFoundErrors []error
// Attempt by session ID
if err := b.browsers.DeleteByID(ctx, in.Identifier); err != nil {
if !util.IsNotFound(err) {
nonNotFoundErrors = append(nonNotFoundErrors, err)
}
}
// Attempt by persistent ID
if err := b.browsers.Delete(ctx, kernel.BrowserDeleteParams{PersistentID: in.Identifier}); err != nil {
if !util.IsNotFound(err) {
nonNotFoundErrors = append(nonNotFoundErrors, err)
}
}
if len(nonNotFoundErrors) >= 2 {
// Both failed with meaningful errors; report one
return util.CleanedUpSdkError{Err: nonNotFoundErrors[0]}
}
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 {
browsers, err := b.browsers.List(ctx)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if browsers == nil || len(*browsers) == 0 {
pterm.Error.Println("No browsers found")
return nil
}
var foundBrowser *kernel.BrowserListResponse
for _, browser := range *browsers {
if browser.Persistence.ID == in.Identifier || browser.SessionID == in.Identifier {
foundBrowser = &browser
break
}
}
if foundBrowser == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
// Output just the URL
pterm.Info.Println(foundBrowser.BrowserLiveViewURL)
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.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
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
}
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
}
type BrowsersComputerSetCursorInput struct {
Identifier string
Hidden bool
}
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.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
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)
}
if len(in.HoldKeys) > 0 {
body.HoldKeys = in.HoldKeys
}
if err := b.computer.ClickMouse(ctx, br.SessionID, body); err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Clicked mouse at (%d,%d)\n", in.X, in.Y)
return nil
}
func (b BrowsersCmd) ComputerMoveMouse(ctx context.Context, in BrowsersComputerMoveMouseInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
body := kernel.BrowserComputerMoveMouseParams{X: in.X, Y: in.Y}
if len(in.HoldKeys) > 0 {
body.HoldKeys = in.HoldKeys
}
if err := b.computer.MoveMouse(ctx, br.SessionID, body); err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Moved mouse to (%d,%d)\n", in.X, in.Y)
return nil
}
func (b BrowsersCmd) ComputerScreenshot(ctx context.Context, in BrowsersComputerScreenshotInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
var body kernel.BrowserComputerCaptureScreenshotParams
if in.HasRegion {
body.Region = kernel.BrowserComputerCaptureScreenshotParamsRegion{X: in.X, Y: in.Y, Width: in.Width, Height: in.Height}
}
res, err := b.computer.CaptureScreenshot(ctx, br.SessionID, body)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
defer res.Body.Close()
if in.To == "" {
pterm.Error.Println("--to is required to save the screenshot")
return nil
}
f, err := os.Create(in.To)
if err != nil {
pterm.Error.Printf("Failed to create file: %v\n", err)
return nil
}
defer f.Close()
if _, err := io.Copy(f, res.Body); err != nil {
pterm.Error.Printf("Failed to write file: %v\n", err)
return nil
}
pterm.Success.Printf("Saved screenshot to %s\n", in.To)
return nil
}
func (b BrowsersCmd) ComputerTypeText(ctx context.Context, in BrowsersComputerTypeTextInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
body := kernel.BrowserComputerTypeTextParams{Text: in.Text}
if in.Delay > 0 {
body.Delay = kernel.Opt(in.Delay)
}
if err := b.computer.TypeText(ctx, br.SessionID, body); err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Typed text: %s\n", in.Text)
return nil
}
func (b BrowsersCmd) ComputerPressKey(ctx context.Context, in BrowsersComputerPressKeyInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
if len(in.Keys) == 0 {
pterm.Error.Println("no keys specified")
return nil
}
body := kernel.BrowserComputerPressKeyParams{Keys: in.Keys}
if in.Duration > 0 {
body.Duration = kernel.Opt(in.Duration)
}
if len(in.HoldKeys) > 0 {
body.HoldKeys = in.HoldKeys
}
if err := b.computer.PressKey(ctx, br.SessionID, body); err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Pressed keys: %s\n", strings.Join(in.Keys, ","))
return nil
}
func (b BrowsersCmd) ComputerScroll(ctx context.Context, in BrowsersComputerScrollInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
body := kernel.BrowserComputerScrollParams{X: in.X, Y: in.Y}
if in.DeltaXSet {
body.DeltaX = kernel.Opt(in.DeltaX)
}
if in.DeltaYSet {
body.DeltaY = kernel.Opt(in.DeltaY)
}
if len(in.HoldKeys) > 0 {
body.HoldKeys = in.HoldKeys
}
if err := b.computer.Scroll(ctx, br.SessionID, body); err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Scrolled at (%d,%d)\n", in.X, in.Y)
return nil
}
func (b BrowsersCmd) ComputerDragMouse(ctx context.Context, in BrowsersComputerDragMouseInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
if len(in.Path) < 2 {
pterm.Error.Println("path must include at least two points")
return nil
}
body := kernel.BrowserComputerDragMouseParams{Path: in.Path}
if in.Delay > 0 {
body.Delay = kernel.Opt(in.Delay)
}
if in.StepDelayMs > 0 {
body.StepDelayMs = kernel.Opt(in.StepDelayMs)
}
if in.StepsPerSegment > 0 {
body.StepsPerSegment = kernel.Opt(in.StepsPerSegment)
}
if in.Button != "" {
body.Button = kernel.BrowserComputerDragMouseParamsButton(in.Button)
}
if len(in.HoldKeys) > 0 {
body.HoldKeys = in.HoldKeys
}
if err := b.computer.DragMouse(ctx, br.SessionID, body); err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Dragged mouse over %d points\n", len(in.Path))
return nil
}
func (b BrowsersCmd) ComputerSetCursor(ctx context.Context, in BrowsersComputerSetCursorInput) error {
if b.computer == nil {
pterm.Error.Println("computer service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
body := kernel.BrowserComputerSetCursorVisibilityParams{Hidden: in.Hidden}
_, err = b.computer.SetCursorVisibility(ctx, br.SessionID, body)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Hidden {
pterm.Success.Println("Cursor hidden")
} else {
pterm.Success.Println("Cursor shown")
}
return nil
}
// Replays
type BrowsersReplaysListInput struct {
Identifier string
}
type BrowsersReplaysStartInput struct {
Identifier string
Framerate int
MaxDurationSeconds int
}
type BrowsersReplaysStopInput struct {
Identifier string
ReplayID string
}
type BrowsersReplaysDownloadInput struct {
Identifier string
ReplayID string
Output string
}
func (b BrowsersCmd) ReplaysList(ctx context.Context, in BrowsersReplaysListInput) error {
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
items, err := b.replays.List(ctx, br.SessionID)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if items == nil || len(*items) == 0 {
pterm.Info.Println("No replays found")
return nil
}
rows := pterm.TableData{{"Replay ID", "Started At", "Finished At", "View URL"}}
for _, r := range *items {
rows = append(rows, []string{r.ReplayID, util.FormatLocal(r.StartedAt), util.FormatLocal(r.FinishedAt), truncateURL(r.ReplayViewURL, 60)})
}
PrintTableNoPad(rows, true)
return nil
}
func (b BrowsersCmd) ReplaysStart(ctx context.Context, in BrowsersReplaysStartInput) error {
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
body := kernel.BrowserReplayStartParams{}
if in.Framerate > 0 {
body.Framerate = kernel.Opt(int64(in.Framerate))
}
if in.MaxDurationSeconds > 0 {
body.MaxDurationInSeconds = kernel.Opt(int64(in.MaxDurationSeconds))
}
res, err := b.replays.Start(ctx, br.SessionID, body)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
rows := pterm.TableData{{"Property", "Value"}, {"Replay ID", res.ReplayID}, {"View URL", res.ReplayViewURL}, {"Started At", util.FormatLocal(res.StartedAt)}}
PrintTableNoPad(rows, true)
return nil
}
func (b BrowsersCmd) ReplaysStop(ctx context.Context, in BrowsersReplaysStopInput) error {
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
err = b.replays.Stop(ctx, in.ReplayID, kernel.BrowserReplayStopParams{ID: br.SessionID})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Stopped replay %s for browser %s\n", in.ReplayID, br.SessionID)
return nil
}
func (b BrowsersCmd) ReplaysDownload(ctx context.Context, in BrowsersReplaysDownloadInput) error {
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil
}
res, err := b.replays.Download(ctx, in.ReplayID, kernel.BrowserReplayDownloadParams{ID: br.SessionID})
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
defer res.Body.Close()
if in.Output == "" {
pterm.Info.Printf("Downloaded replay %s (%s)\n", in.ReplayID, res.Header.Get("content-type"))
_, _ = io.Copy(io.Discard, res.Body)
return nil
}
f, err := os.Create(in.Output)
if err != nil {
pterm.Error.Printf("Failed to create file: %v\n", err)
return nil
}
defer f.Close()
if _, err := io.Copy(f, res.Body); err != nil {
pterm.Error.Printf("Failed to write file: %v\n", err)
return nil
}
pterm.Success.Printf("Saved replay to %s\n", in.Output)
return nil
}
// Process
type BrowsersProcessExecInput struct {
Identifier string
Command string
Args []string
Cwd string
Timeout int
AsUser string
AsRoot BoolFlag
}
type BrowsersProcessSpawnInput = BrowsersProcessExecInput
type BrowsersProcessKillInput struct {
Identifier string
ProcessID string
Signal string
}
type BrowsersProcessStatusInput struct {
Identifier string
ProcessID string
}
type BrowsersProcessStdinInput struct {
Identifier string
ProcessID string
DataB64 string
}
type BrowsersProcessStdoutStreamInput struct {
Identifier string
ProcessID string
}
// Playwright
type BrowsersPlaywrightExecuteInput struct {
Identifier string
Code string
Timeout int64
}
func (b BrowsersCmd) PlaywrightExecute(ctx context.Context, in BrowsersPlaywrightExecuteInput) error {
if b.playwright == nil {
pterm.Error.Println("playwright service not available")
return nil
}
br, err := b.resolveBrowserByIdentifier(ctx, in.Identifier)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if br == nil {
pterm.Error.Printf("Browser '%s' not found\n", in.Identifier)
return nil