Repository navigation
Expand file tree
/
Copy pathbrowser.go
More file actions
2364 lines (2199 loc) · 107 KB
/
Copy pathbrowser.go
File metadata and controls
2364 lines (2199 loc) · 107 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
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package kernel
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"slices"
"time"
"github.com/kernel/kernel-go-sdk/internal/apiform"
"github.com/kernel/kernel-go-sdk/internal/apijson"
"github.com/kernel/kernel-go-sdk/internal/apiquery"
shimjson "github.com/kernel/kernel-go-sdk/internal/encoding/json"
"github.com/kernel/kernel-go-sdk/internal/requestconfig"
"github.com/kernel/kernel-go-sdk/option"
"github.com/kernel/kernel-go-sdk/packages/pagination"
"github.com/kernel/kernel-go-sdk/packages/param"
"github.com/kernel/kernel-go-sdk/packages/respjson"
"github.com/kernel/kernel-go-sdk/shared"
)
// BrowserService contains methods and other services that help with interacting
// with the kernel API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewBrowserService] method instead.
type BrowserService struct {
Options []option.RequestOption
// Stream live telemetry events from a browser session, and manage the destinations
// sessions export them to.
Telemetry BrowserTelemetryService
// Record and manage browser session video replays.
Replays BrowserReplayService
// Read, write, and manage files on the browser instance.
Fs BrowserFService
// Execute and manage processes on the browser instance.
Process BrowserProcessService
// Stream logs from the browser instance.
Logs BrowserLogService
// Control mouse, keyboard, and screen on the browser instance.
Computer BrowserComputerService
// Execute Playwright code against the browser instance and manage the executors it
// runs in.
Playwright BrowserPlaywrightService
// Discover and invoke native page tools across the browser instance.
Webmcp BrowserWebmcpService
}
// NewBrowserService generates a new service that applies the given options to each
// request. These options are applied after the parent client's options (if there
// is one), and before any request-specific options.
func NewBrowserService(opts ...option.RequestOption) (r BrowserService) {
r = BrowserService{}
r.Options = opts
r.Telemetry = NewBrowserTelemetryService(opts...)
r.Replays = NewBrowserReplayService(opts...)
r.Fs = NewBrowserFService(opts...)
r.Process = NewBrowserProcessService(opts...)
r.Logs = NewBrowserLogService(opts...)
r.Computer = NewBrowserComputerService(opts...)
r.Playwright = NewBrowserPlaywrightService(opts...)
r.Webmcp = NewBrowserWebmcpService(opts...)
return
}
// Create a new browser session from within an action.
func (r *BrowserService) New(ctx context.Context, body BrowserNewParams, opts ...option.RequestOption) (res *BrowserNewResponse, err error) {
opts = slices.Concat(r.Options, opts)
path := "browsers"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Get information about a browser session.
func (r *BrowserService) Get(ctx context.Context, idOrName string, query BrowserGetParams, opts ...option.RequestOption) (res *BrowserGetResponse, err error) {
opts = slices.Concat(r.Options, opts)
if idOrName == "" {
err = errors.New("missing required id_or_name parameter")
return nil, err
}
path := fmt.Sprintf("browsers/%s", idOrName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Update a browser session.
func (r *BrowserService) Update(ctx context.Context, idOrName string, body BrowserUpdateParams, opts ...option.RequestOption) (res *BrowserUpdateResponse, err error) {
opts = slices.Concat(r.Options, opts)
if idOrName == "" {
err = errors.New("missing required id_or_name parameter")
return nil, err
}
path := fmt.Sprintf("browsers/%s", idOrName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, body, &res, opts...)
return res, err
}
// List all browser sessions with pagination support. Use status parameter to
// filter by session state.
func (r *BrowserService) List(ctx context.Context, query BrowserListParams, opts ...option.RequestOption) (res *pagination.OffsetPagination[BrowserListResponse], err error) {
var raw *http.Response
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
path := "browsers"
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
if err != nil {
return nil, err
}
err = cfg.Execute()
if err != nil {
return nil, err
}
res.SetPageConfig(cfg, raw)
return res, nil
}
// List all browser sessions with pagination support. Use status parameter to
// filter by session state.
func (r *BrowserService) ListAutoPaging(ctx context.Context, query BrowserListParams, opts ...option.RequestOption) *pagination.OffsetPaginationAutoPager[BrowserListResponse] {
return pagination.NewOffsetPaginationAutoPager(r.List(ctx, query, opts...))
}
// Sends an HTTP request through Chrome's HTTP request stack, inheriting the
// browser's TLS fingerprint, cookies, proxy configuration, and headers. Returns a
// structured JSON response with status, headers, body, and timing.
func (r *BrowserService) Curl(ctx context.Context, idOrName string, body BrowserCurlParams, opts ...option.RequestOption) (res *BrowserCurlResponse, err error) {
opts = slices.Concat(r.Options, opts)
if idOrName == "" {
err = errors.New("missing required id_or_name parameter")
return nil, err
}
path := fmt.Sprintf("browsers/%s/curl", idOrName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Delete a browser session by ID or name
func (r *BrowserService) DeleteByID(ctx context.Context, idOrName string, opts ...option.RequestOption) (err error) {
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if idOrName == "" {
err = errors.New("missing required id_or_name parameter")
return err
}
path := fmt.Sprintf("browsers/%s", idOrName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, nil, opts...)
return err
}
// Loads one or more unpacked extensions using live CDP activation when eligible.
// Chromium restarts when enterprise policy requires it or live activation fails.
func (r *BrowserService) LoadExtensions(ctx context.Context, idOrName string, body BrowserLoadExtensionsParams, opts ...option.RequestOption) (err error) {
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if idOrName == "" {
err = errors.New("missing required id_or_name parameter")
return err
}
path := fmt.Sprintf("browsers/%s/extensions", idOrName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, nil, opts...)
return err
}
// Execute JavaScript in a persistent Node.js runtime inside the browser VM.
// Top-level bindings, closures, mutations, and dynamically imported modules
// persist across calls until the REPL is reset or replaced. Start with
// `repl.help()` to list available methods, or call `repl.help("click")` for
// detailed help.
//
// Expression values are ignored. Emit ordered text or image output with
// `repl.write(...)`, console methods, or `repl.emitImage(...)`. The runtime also
// exposes browser-control helpers, WebMCP, Patchright, Playwright, and raw CDP.
//
// Executions are serialized. A timeout, crash, OOM, or protocol failure terminates
// the REPL and changes its `repl_id`. This is unrestricted code execution inside
// the browser VM and is not sandboxed.
func (r *BrowserService) Repl(ctx context.Context, idOrName string, body BrowserReplParams, opts ...option.RequestOption) (res *BrowserReplResult, err error) {
opts = slices.Concat(r.Options, opts)
if idOrName == "" {
err = errors.New("missing required id_or_name parameter")
return nil, err
}
path := fmt.Sprintf("browsers/%s/repl", idOrName)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
type BrowserAllowlistState struct {
// Opaque revision to pass as network.expected_allowlist_revision on an update.
Revision string `json:"revision" api:"required"`
// Revision against which that mutation was accepted; reuse it when retrying the
// mutation.
BaseRevision string `json:"base_revision"`
// ID of the last conditional allowlist update saved on this browser.
MutationID string `json:"mutation_id"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Revision respjson.Field
BaseRevision respjson.Field
MutationID respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserAllowlistState) RawJSON() string { return r.JSON.raw }
func (r *BrowserAllowlistState) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this BrowserAllowlistState to a BrowserAllowlistStateParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// BrowserAllowlistStateParam.Overrides()
func (r BrowserAllowlistState) ToParam() BrowserAllowlistStateParam {
return param.Override[BrowserAllowlistStateParam](json.RawMessage(r.RawJSON()))
}
// The property Revision is required.
type BrowserAllowlistStateParam struct {
// Opaque revision to pass as network.expected_allowlist_revision on an update.
Revision string `json:"revision" api:"required"`
// Revision against which that mutation was accepted; reuse it when retrying the
// mutation.
BaseRevision param.Opt[string] `json:"base_revision,omitzero"`
// ID of the last conditional allowlist update saved on this browser.
MutationID param.Opt[string] `json:"mutation_id,omitzero"`
paramObj
}
func (r BrowserAllowlistStateParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserAllowlistStateParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserAllowlistStateParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type BrowserLocation struct {
// Effective canonical BCP 47 formatting locale selected for the browser session.
Locale string `json:"locale" api:"required"`
// Where one effective browser location field came from. `override` is set
// explicitly on the session; `default` comes from the browser's region.
//
// Any of "override", "default".
LocaleSource BrowserLocationSource `json:"locale_source" api:"required"`
// Effective IANA timezone selected for the browser session.
Timezone string `json:"timezone" api:"required"`
// Where one effective browser location field came from. `override` is set
// explicitly on the session; `default` comes from the browser's region.
//
// Any of "override", "default".
TimezoneSource BrowserLocationSource `json:"timezone_source" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Locale respjson.Field
LocaleSource respjson.Field
Timezone respjson.Field
TimezoneSource respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserLocation) RawJSON() string { return r.JSON.raw }
func (r *BrowserLocation) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type BrowserLocationRequestParam struct {
// Session-only supported canonical BCP 47 locale override. Omit to use the default
// for the browser's region.
Locale param.Opt[string] `json:"locale,omitzero"`
// Session-only IANA timezone override. Omit to use the default for the browser's
// region.
Timezone param.Opt[string] `json:"timezone,omitzero"`
paramObj
}
func (r BrowserLocationRequestParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserLocationRequestParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserLocationRequestParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Where one effective browser location field came from. `override` is set
// explicitly on the session; `default` comes from the browser's region.
type BrowserLocationSource string
const (
BrowserLocationSourceOverride BrowserLocationSource = "override"
BrowserLocationSourceDefault BrowserLocationSource = "default"
)
// Omit a field to leave it unchanged, set a string override, or set null to clear
// the override and use the default for the browser's region.
type BrowserLocationUpdateRequestParam struct {
// Session-only supported canonical BCP 47 locale override. Null clears the
// override and uses the browser region's default.
Locale param.Opt[string] `json:"locale,omitzero"`
// Session-only IANA timezone override. Null clears the override and uses the
// browser region's default.
Timezone param.Opt[string] `json:"timezone,omitzero"`
paramObj
}
func (r BrowserLocationUpdateRequestParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserLocationUpdateRequestParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserLocationUpdateRequestParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Memory allocated to the browser session.
type BrowserMemory string
const (
BrowserMemory1GiB BrowserMemory = "1GiB"
BrowserMemory2GiB BrowserMemory = "2GiB"
BrowserMemory4GiB BrowserMemory = "4GiB"
BrowserMemory6GiB BrowserMemory = "6GiB"
BrowserMemory8GiB BrowserMemory = "8GiB"
BrowserMemory12GiB BrowserMemory = "12GiB"
BrowserMemory16GiB BrowserMemory = "16GiB"
)
// Memory requested for a non-GPU browser. Headless browsers support 1GiB
// (default), 2GiB, or 4GiB; headful browsers support 8GiB (default) or 16GiB.
type BrowserMemoryRequest string
const (
BrowserMemoryRequest1GiB BrowserMemoryRequest = "1GiB"
BrowserMemoryRequest2GiB BrowserMemoryRequest = "2GiB"
BrowserMemoryRequest4GiB BrowserMemoryRequest = "4GiB"
BrowserMemoryRequest8GiB BrowserMemoryRequest = "8GiB"
BrowserMemoryRequest16GiB BrowserMemoryRequest = "16GiB"
)
// Network configuration for a browser session or browser pool.
type BrowserNetworkConfig struct {
// Egress allowlist for a browser session: the only destinations the browser may
// reach through Kernel-managed egress. Any other destination is refused with a 403
// whose X-Kernel-Proxy-Error header is network_policy_denied, so pages cannot load
// or send data to unlisted hosts, including with fetch() and WebSockets. Omit the
// field for unfiltered egress; an empty list is invalid. The allowlist applies
// from the browser's first request, and start_url must be allowed by it. Entries
// are exact hostnames ("example.com"), one leading "_." wildcard that matches
// subdomains at any depth but not the domain itself ("_.example.com" matches
// api.example.com, not example.com), public IPv4 addresses ("8.8.8.8"), bracketed
// public IPv6 addresses ("[2001:4860:4860::8888]"), or public CIDR ranges in
// canonical form ("8.8.4.0/24", "2001:4860::/32"). IP and CIDR entries only match
// destinations written as an IP address, never hostnames that resolve into the
// range. Entries cannot include ports, paths, or schemes, and match every port on
// their host. Wildcards over a public suffix ("_.com", "_.github.io") and private
// or reserved IP ranges are rejected, as are entries that overlap private_hosts.
// Enforced at Kernel's egress proxy only: destinations in private_hosts, and
// processes in the browser VM that do not use the browser's proxy, are not
// filtered, and Kernel's own control traffic is always allowed. Can be replaced or
// removed while the session runs with PATCH /browsers/{id_or_name}, but not added
// to a browser created without one. Supported on browser pools and their leased
// browsers. Per-lease changes are reset to the pool's allowlist on release. If a
// lessee removes the allowlist and the pool still requires one, the browser is
// replaced on release rather than given an allowlist again. Requires proxy v3.
AllowedHosts []string `json:"allowed_hosts"`
// Concurrency metadata for a browser's saved allowlist configuration. Browser
// pools omit it. This remains present after removal so an uncertain removal can be
// retried. It does not prove proxy or VM application completed. Do not include it
// in creation or pool updates.
AllowlistState BrowserAllowlistState `json:"allowlist_state"`
// Destinations the browser reaches directly through the session's own network
// instead of through Kernel-managed egress — for private hosts reachable over a
// VPN or tunnel the session has joined (e.g. a Tailscale tailnet). By default,
// private IP ranges already route directly: RFC1918 (10.0.0.0/8, 172.16.0.0/12,
// 192.168.0.0/16), CGNAT/Tailscale (100.64.0.0/10), and IPv6 ULA (fc00::/7). An
// explicitly supplied list replaces those defaults with exactly the entries given,
// and an empty list ([]) disables them so all traffic uses Kernel-managed egress;
// omit private_hosts to keep the defaults. Entries are hostname patterns
// ("_.example.ts.net", "preview.internal") or IP/CIDR literals ("100.64.0.0/10",
// "10.1.30.63"). IP and CIDR entries only match URLs written with a literal IP
// address; they never match hostnames that resolve into the range, so private DNS
// names need a hostname entry even when they resolve inside the default ranges.
// CIDRs must be in canonical masked form (host bits zero), and only the private
// ranges listed above are accepted; public, loopback, link-local, and unspecified
// ranges are rejected. Exact IPv6 addresses must be bracketed ("[fd00::1]"); IPv6
// CIDR ranges are unbracketed ("fd00::/8"). Wildcards are limited to one leading
// "_." over a suffix with at least two labels that is not a public suffix (so
// "_.co.uk" or "_.ts.net" are rejected, while "\*.example.ts.net" is accepted).
// Hostname and IP entries may carry a port; CIDR ranges may not. Hostname entries
// are not resolved during validation, so callers must ensure they identify private
// destinations. Not related to a proxy's bypass_hosts, which selects between
// upstream-proxy and Kernel-managed direct egress and cannot reach into a VPN.
PrivateHosts []string `json:"private_hosts"`
// Per-destination proxy routes for a browser session. A destination hostname is
// matched against every route's hosts, regardless of port; route order does not
// matter. An exact hostname beats a wildcard, and a longer wildcard suffix beats a
// shorter one (for a.b.example.com: "a.b.example.com" > "_.b.example.com" >
// "_.example.com"). A host pattern may appear in only one route. "\*.example.com"
// matches subdomains only, not example.com. A matched request selects the route's
// proxy instead of the session's top-level proxy (including mode: direct); the
// route proxy's own bypass_hosts still apply. If the route proxy becomes
// unavailable, matched requests fail closed without falling back. Requests that
// match no route use the session's default egress from the top-level proxy field
// (or the browser default when proxy is omitted: stealth proxy or direct egress).
// Routes apply from the start of the session, including to start_url and other
// traffic during browser setup. Setting routes requires proxy v3. Browser pools
// also support these routes.
ProxyRoutes []BrowserNetworkConfigProxyRoute `json:"proxy_routes"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
AllowedHosts respjson.Field
AllowlistState respjson.Field
PrivateHosts respjson.Field
ProxyRoutes respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserNetworkConfig) RawJSON() string { return r.JSON.raw }
func (r *BrowserNetworkConfig) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this BrowserNetworkConfig to a BrowserNetworkConfigParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// BrowserNetworkConfigParam.Overrides()
func (r BrowserNetworkConfig) ToParam() BrowserNetworkConfigParam {
return param.Override[BrowserNetworkConfigParam](json.RawMessage(r.RawJSON()))
}
type BrowserNetworkConfigProxyRoute struct {
// Exact hostnames or leading \*. wildcard patterns (subdomains only); patterns
// cannot include ports, and matching ignores the destination port. Hosts not
// matched by any route use the session's top-level proxy (or the browser default
// when proxy is omitted).
Hosts []string `json:"hosts" api:"required"`
// Select an active non-direct proxy by ID or name. Responses always use ID.
Proxy BrowserNetworkConfigProxyRouteProxy `json:"proxy" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Hosts respjson.Field
Proxy respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserNetworkConfigProxyRoute) RawJSON() string { return r.JSON.raw }
func (r *BrowserNetworkConfigProxyRoute) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Select an active non-direct proxy by ID or name. Responses always use ID.
type BrowserNetworkConfigProxyRouteProxy struct {
ID string `json:"id"`
Name string `json:"name"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
Name respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserNetworkConfigProxyRouteProxy) RawJSON() string { return r.JSON.raw }
func (r *BrowserNetworkConfigProxyRouteProxy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Network configuration for a browser session or browser pool.
type BrowserNetworkConfigParam struct {
// Egress allowlist for a browser session: the only destinations the browser may
// reach through Kernel-managed egress. Any other destination is refused with a 403
// whose X-Kernel-Proxy-Error header is network_policy_denied, so pages cannot load
// or send data to unlisted hosts, including with fetch() and WebSockets. Omit the
// field for unfiltered egress; an empty list is invalid. The allowlist applies
// from the browser's first request, and start_url must be allowed by it. Entries
// are exact hostnames ("example.com"), one leading "_." wildcard that matches
// subdomains at any depth but not the domain itself ("_.example.com" matches
// api.example.com, not example.com), public IPv4 addresses ("8.8.8.8"), bracketed
// public IPv6 addresses ("[2001:4860:4860::8888]"), or public CIDR ranges in
// canonical form ("8.8.4.0/24", "2001:4860::/32"). IP and CIDR entries only match
// destinations written as an IP address, never hostnames that resolve into the
// range. Entries cannot include ports, paths, or schemes, and match every port on
// their host. Wildcards over a public suffix ("_.com", "_.github.io") and private
// or reserved IP ranges are rejected, as are entries that overlap private_hosts.
// Enforced at Kernel's egress proxy only: destinations in private_hosts, and
// processes in the browser VM that do not use the browser's proxy, are not
// filtered, and Kernel's own control traffic is always allowed. Can be replaced or
// removed while the session runs with PATCH /browsers/{id_or_name}, but not added
// to a browser created without one. Supported on browser pools and their leased
// browsers. Per-lease changes are reset to the pool's allowlist on release. If a
// lessee removes the allowlist and the pool still requires one, the browser is
// replaced on release rather than given an allowlist again. Requires proxy v3.
AllowedHosts []string `json:"allowed_hosts,omitzero"`
// Destinations the browser reaches directly through the session's own network
// instead of through Kernel-managed egress — for private hosts reachable over a
// VPN or tunnel the session has joined (e.g. a Tailscale tailnet). By default,
// private IP ranges already route directly: RFC1918 (10.0.0.0/8, 172.16.0.0/12,
// 192.168.0.0/16), CGNAT/Tailscale (100.64.0.0/10), and IPv6 ULA (fc00::/7). An
// explicitly supplied list replaces those defaults with exactly the entries given,
// and an empty list ([]) disables them so all traffic uses Kernel-managed egress;
// omit private_hosts to keep the defaults. Entries are hostname patterns
// ("_.example.ts.net", "preview.internal") or IP/CIDR literals ("100.64.0.0/10",
// "10.1.30.63"). IP and CIDR entries only match URLs written with a literal IP
// address; they never match hostnames that resolve into the range, so private DNS
// names need a hostname entry even when they resolve inside the default ranges.
// CIDRs must be in canonical masked form (host bits zero), and only the private
// ranges listed above are accepted; public, loopback, link-local, and unspecified
// ranges are rejected. Exact IPv6 addresses must be bracketed ("[fd00::1]"); IPv6
// CIDR ranges are unbracketed ("fd00::/8"). Wildcards are limited to one leading
// "_." over a suffix with at least two labels that is not a public suffix (so
// "_.co.uk" or "_.ts.net" are rejected, while "\*.example.ts.net" is accepted).
// Hostname and IP entries may carry a port; CIDR ranges may not. Hostname entries
// are not resolved during validation, so callers must ensure they identify private
// destinations. Not related to a proxy's bypass_hosts, which selects between
// upstream-proxy and Kernel-managed direct egress and cannot reach into a VPN.
PrivateHosts []string `json:"private_hosts,omitzero"`
// Per-destination proxy routes for a browser session. A destination hostname is
// matched against every route's hosts, regardless of port; route order does not
// matter. An exact hostname beats a wildcard, and a longer wildcard suffix beats a
// shorter one (for a.b.example.com: "a.b.example.com" > "_.b.example.com" >
// "_.example.com"). A host pattern may appear in only one route. "\*.example.com"
// matches subdomains only, not example.com. A matched request selects the route's
// proxy instead of the session's top-level proxy (including mode: direct); the
// route proxy's own bypass_hosts still apply. If the route proxy becomes
// unavailable, matched requests fail closed without falling back. Requests that
// match no route use the session's default egress from the top-level proxy field
// (or the browser default when proxy is omitted: stealth proxy or direct egress).
// Routes apply from the start of the session, including to start_url and other
// traffic during browser setup. Setting routes requires proxy v3. Browser pools
// also support these routes.
ProxyRoutes []BrowserNetworkConfigProxyRouteParam `json:"proxy_routes,omitzero"`
paramObj
}
func (r BrowserNetworkConfigParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserNetworkConfigParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserNetworkConfigParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// The properties Hosts, Proxy are required.
type BrowserNetworkConfigProxyRouteParam struct {
// Exact hostnames or leading \*. wildcard patterns (subdomains only); patterns
// cannot include ports, and matching ignores the destination port. Hosts not
// matched by any route use the session's top-level proxy (or the browser default
// when proxy is omitted).
Hosts []string `json:"hosts,omitzero" api:"required"`
// Select an active non-direct proxy by ID or name. Responses always use ID.
Proxy BrowserNetworkConfigProxyRouteProxyParam `json:"proxy,omitzero" api:"required"`
paramObj
}
func (r BrowserNetworkConfigProxyRouteParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserNetworkConfigProxyRouteParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserNetworkConfigProxyRouteParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Select an active non-direct proxy by ID or name. Responses always use ID.
type BrowserNetworkConfigProxyRouteProxyParam struct {
ID param.Opt[string] `json:"id,omitzero"`
Name param.Opt[string] `json:"name,omitzero"`
paramObj
}
func (r BrowserNetworkConfigProxyRouteProxyParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserNetworkConfigProxyRouteProxyParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserNetworkConfigProxyRouteProxyParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Network configuration changes for a running browser session. Other network
// settings can only be set at creation.
type BrowserNetworkUpdateParam struct {
// The network.allowlist_state.revision from the browser's last saved snapshot.
// Supply together with mutation_id to opt into conditional allowlist updates. The
// revision is checked atomically with the configuration write. A stale request
// returns 409 stale_network without changing the allowlist. A GET alone does not
// fence an earlier unfinished PATCH.
ExpectedAllowlistRevision param.Opt[string] `json:"expected_allowlist_revision,omitzero"`
// A unique ID for this allowlist update, supplied together with
// expected_allowlist_revision. Reuse both values and the identical allowed_hosts
// payload when retrying an uncertain update. If it is still the current mutation,
// the retry finishes proxy and VM application without creating another revision. A
// superseded mutation returns 409 stale_network. These fields guard only
// network.allowed_hosts, not other browser update fields.
MutationID param.Opt[string] `json:"mutation_id,omitzero"`
// Replaces the session's egress allowlist, using the same entry rules as
// network.allowed_hosts on create. Only an allowlist the browser was created with
// can be changed: a browser created without one can't be given one, and an
// allowlist removed with null can't be added back. Omit to leave the allowlist
// unchanged, or set to null to remove it and return to unfiltered egress; an empty
// list is invalid. The new list applies without restarting the browser: new
// requests to destinations it no longer allows are refused within a few seconds,
// and open connections to them are closed within about 30 seconds, or up to 10
// minutes during a Kernel deploy. Connections to destinations it still allows,
// such as WebSockets, stay open. A start_url in the same request must be allowed
// by the updated list, and is loaded only after the list takes effect. Requires a
// browser created with proxy v3. Supported on leased pooled browsers; the pool's
// allowlist is restored before reuse, or the browser is destroyed if it cannot be
// safely restored. If the request fails, retry it: the new list may already apply
// to some requests.
AllowedHosts []string `json:"allowed_hosts,omitzero"`
paramObj
}
func (r BrowserNetworkUpdateParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserNetworkUpdateParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserNetworkUpdateParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Browser pool this session was acquired from, if any.
type BrowserPoolRef struct {
// Browser pool ID
ID string `json:"id" api:"required"`
// Browser pool name, if set
Name string `json:"name"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
Name respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserPoolRef) RawJSON() string { return r.JSON.raw }
func (r *BrowserPoolRef) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Resolved proxy configuration for a browser session. Selected proxies are
// returned by stable ID.
type BrowserProxy struct {
// Selected proxy ID.
ID string `json:"id"`
// Proxy egress mode. direct forces no proxy regardless of stealth. default uses
// the browser's stealth-derived default: Kernel's default stealth proxy when
// stealth=true, or direct egress when stealth=false. default is primarily useful
// on browser update to restore the browser default after selected-proxy egress.
//
// Any of "direct", "default".
Mode BrowserProxyMode `json:"mode"`
// Selected proxy name.
Name string `json:"name"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
Mode respjson.Field
Name respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserProxy) RawJSON() string { return r.JSON.raw }
func (r *BrowserProxy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Browser proxy configuration. Provide exactly one of mode, id, or name; an empty
// object is invalid. Set mode to direct for no proxy regardless of stealth. Set
// mode to default to use the browser's stealth-derived default: Kernel's default
// stealth proxy when stealth=true, or direct egress when stealth=false. Select id
// or name to use that proxy regardless of stealth. The selected proxy must be in
// the same project as the browser. Names must match exactly one active proxy; use
// id for stable references. Proxy configuration changes only egress and does not
// change stealth or CAPTCHA solver behavior. A stealth browser using mode=direct
// still runs in stealth mode with the CAPTCHA solver enabled. When proxy is
// omitted on browser creation, stealth browsers use Kernel's default stealth proxy
// and non-stealth browsers use direct egress. When omitted on update, the current
// configuration is unchanged.
type BrowserProxyConfig struct {
// Proxy ID.
ID string `json:"id"`
// Proxy egress mode. direct forces no proxy regardless of stealth. default uses
// the browser's stealth-derived default: Kernel's default stealth proxy when
// stealth=true, or direct egress when stealth=false. default is primarily useful
// on browser update to restore the browser default after selected-proxy egress.
//
// Any of "direct", "default".
Mode BrowserProxyMode `json:"mode"`
// Proxy name. Must match exactly one active proxy in the project.
Name string `json:"name"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
Mode respjson.Field
Name respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserProxyConfig) RawJSON() string { return r.JSON.raw }
func (r *BrowserProxyConfig) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// ToParam converts this BrowserProxyConfig to a BrowserProxyConfigParam.
//
// Warning: the fields of the param type will not be present. ToParam should only
// be used at the last possible moment before sending a request. Test for this with
// BrowserProxyConfigParam.Overrides()
func (r BrowserProxyConfig) ToParam() BrowserProxyConfigParam {
return param.Override[BrowserProxyConfigParam](json.RawMessage(r.RawJSON()))
}
// Browser proxy configuration. Provide exactly one of mode, id, or name; an empty
// object is invalid. Set mode to direct for no proxy regardless of stealth. Set
// mode to default to use the browser's stealth-derived default: Kernel's default
// stealth proxy when stealth=true, or direct egress when stealth=false. Select id
// or name to use that proxy regardless of stealth. The selected proxy must be in
// the same project as the browser. Names must match exactly one active proxy; use
// id for stable references. Proxy configuration changes only egress and does not
// change stealth or CAPTCHA solver behavior. A stealth browser using mode=direct
// still runs in stealth mode with the CAPTCHA solver enabled. When proxy is
// omitted on browser creation, stealth browsers use Kernel's default stealth proxy
// and non-stealth browsers use direct egress. When omitted on update, the current
// configuration is unchanged.
type BrowserProxyConfigParam struct {
// Proxy ID.
ID param.Opt[string] `json:"id,omitzero"`
// Proxy name. Must match exactly one active proxy in the project.
Name param.Opt[string] `json:"name,omitzero"`
// Proxy egress mode. direct forces no proxy regardless of stealth. default uses
// the browser's stealth-derived default: Kernel's default stealth proxy when
// stealth=true, or direct egress when stealth=false. default is primarily useful
// on browser update to restore the browser default after selected-proxy egress.
//
// Any of "direct", "default".
Mode BrowserProxyMode `json:"mode,omitzero"`
paramObj
}
func (r BrowserProxyConfigParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserProxyConfigParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserProxyConfigParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Proxy egress mode. direct forces no proxy regardless of stealth. default uses
// the browser's stealth-derived default: Kernel's default stealth proxy when
// stealth=true, or direct egress when stealth=false. default is primarily useful
// on browser update to restore the browser default after selected-proxy egress.
type BrowserProxyMode string
const (
BrowserProxyModeDirect BrowserProxyMode = "direct"
BrowserProxyModeDefault BrowserProxyMode = "default"
)
// BrowserReplContentUnion contains all possible properties and values from
// [BrowserReplTextContent], [BrowserReplImageContent].
//
// Use the [BrowserReplContentUnion.AsAny] method to switch on the variant.
//
// Use the methods beginning with 'As' to cast the union to one of its variants.
type BrowserReplContentUnion struct {
// This field is from variant [BrowserReplTextContent].
Channel BrowserReplTextContentChannel `json:"channel"`
// This field is from variant [BrowserReplTextContent].
Text string `json:"text"`
// Any of "text", "image".
Type string `json:"type"`
// This field is from variant [BrowserReplImageContent].
DataB64 string `json:"data_b64"`
// This field is from variant [BrowserReplImageContent].
MimeType string `json:"mime_type"`
JSON struct {
Channel respjson.Field
Text respjson.Field
Type respjson.Field
DataB64 respjson.Field
MimeType respjson.Field
raw string
} `json:"-"`
}
// anyBrowserReplContent is implemented by each variant of
// [BrowserReplContentUnion] to add type safety for the return type of
// [BrowserReplContentUnion.AsAny]
type anyBrowserReplContent interface {
implBrowserReplContentUnion()
}
func (BrowserReplTextContent) implBrowserReplContentUnion() {}
func (BrowserReplImageContent) implBrowserReplContentUnion() {}
// Use the following switch statement to find the correct variant
//
// switch variant := BrowserReplContentUnion.AsAny().(type) {
// case kernel.BrowserReplTextContent:
// case kernel.BrowserReplImageContent:
// default:
// fmt.Errorf("no variant present")
// }
func (u BrowserReplContentUnion) AsAny() anyBrowserReplContent {
switch u.Type {
case "text":
return u.AsText()
case "image":
return u.AsImage()
}
return nil
}
func (u BrowserReplContentUnion) AsText() (v BrowserReplTextContent) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
func (u BrowserReplContentUnion) AsImage() (v BrowserReplImageContent) {
apijson.UnmarshalRoot(json.RawMessage(u.JSON.raw), &v)
return
}
// Returns the unmodified JSON received from the API
func (u BrowserReplContentUnion) RawJSON() string { return u.JSON.raw }
func (r *BrowserReplContentUnion) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type BrowserReplImageContent struct {
DataB64 string `json:"data_b64" api:"required"`
MimeType string `json:"mime_type" api:"required"`
// Any of "image".
Type BrowserReplImageContentType `json:"type" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
DataB64 respjson.Field
MimeType respjson.Field
Type respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserReplImageContent) RawJSON() string { return r.JSON.raw }
func (r *BrowserReplImageContent) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type BrowserReplImageContentType string
const (
BrowserReplImageContentTypeImage BrowserReplImageContentType = "image"
)
// Request to execute code in the persistent Browser REPL.
//
// The property Code is required.
type BrowserReplRequestParam struct {
// JavaScript evaluated in a persistent Node.js runtime. Top-level bindings persist
// until the browser VM's API process exits, the REPL is reset, or the REPL is
// terminated after a crash or timeout. Static top-level imports are unsupported;
// use dynamic `import()`. Expression values are ignored; emit output with
// `repl.write(...)`, console methods, or `repl.emitImage(...)`. May be empty only
// when `reset` is true.
Code string `json:"code" api:"required"`
// Terminate the current REPL, start a fresh one, and then evaluate code.
Reset param.Opt[bool] `json:"reset,omitzero"`
// Maximum execution time in seconds. Default is 60.
TimeoutSec param.Opt[int64] `json:"timeout_sec,omitzero"`
paramObj
}
func (r BrowserReplRequestParam) MarshalJSON() (data []byte, err error) {
type shadow BrowserReplRequestParam
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *BrowserReplRequestParam) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Result of Browser REPL code execution.
type BrowserReplResult struct {
// CUID2 identifying the exact state-holding REPL process used for this execution.
// Stable across calls and Chromium reconnects; changes after an API restart,
// explicit reset, execution timeout, or REPL crash.
ReplID string `json:"repl_id" api:"required"`
// Whether the code executed successfully.
Success bool `json:"success" api:"required"`
// Optional ordered text/image output produced by the execution.
Content []BrowserReplContentUnion `json:"content"`
// True if text or image output was dropped or truncated due to response limits.
ContentTruncated bool `json:"content_truncated"`
// Wall-clock execution time in milliseconds.
DurationMs int64 `json:"duration_ms"`
// Error message if execution failed.
Error string `json:"error"`
// True if the REPL identified by `repl_id` was terminated by this request. The
// next request lazily starts a fresh REPL with a new `repl_id`.
ReplTerminated bool `json:"repl_terminated"`
// Stack trace if execution failed.
Stack string `json:"stack"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ReplID respjson.Field
Success respjson.Field
Content respjson.Field
ContentTruncated respjson.Field
DurationMs respjson.Field
Error respjson.Field
ReplTerminated respjson.Field
Stack respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserReplResult) RawJSON() string { return r.JSON.raw }
func (r *BrowserReplResult) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type BrowserReplTextContent struct {
// `write` is emitted by `repl.write`; `stdout` and `stderr` are emitted by console
// methods.
//
// Any of "write", "stdout", "stderr".
Channel BrowserReplTextContentChannel `json:"channel" api:"required"`
Text string `json:"text" api:"required"`
// Any of "text".
Type BrowserReplTextContentType `json:"type" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Channel respjson.Field
Text respjson.Field
Type respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r BrowserReplTextContent) RawJSON() string { return r.JSON.raw }
func (r *BrowserReplTextContent) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// `write` is emitted by `repl.write`; `stdout` and `stderr` are emitted by console
// methods.
type BrowserReplTextContentChannel string
const (
BrowserReplTextContentChannelWrite BrowserReplTextContentChannel = "write"
BrowserReplTextContentChannelStdout BrowserReplTextContentChannel = "stdout"
BrowserReplTextContentChannelStderr BrowserReplTextContentChannel = "stderr"
)
type BrowserReplTextContentType string
const (
BrowserReplTextContentTypeText BrowserReplTextContentType = "text"
)
// Session usage metrics.
type BrowserUsage struct {
// Time in milliseconds the session was actively running.