Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 74 additions & 5 deletions cmd/browsers.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,21 @@ func parseFingerprintOS(os string) (kernel.BrowserFingerprintOs, error) {
}
}

// parseBrowserPlatformOS validates the operating system of the browser host.
// This is distinct from --fingerprint-os, which only changes what a Linux
// browser reports to websites.
func parseBrowserPlatformOS(os string) (kernel.BrowserOs, error) {
if os == "" {
return "", nil
}
switch kernel.BrowserOs(os) {
case kernel.BrowserOsLinux, kernel.BrowserOsMacos:
return kernel.BrowserOs(os), nil
default:
return "", fmt.Errorf("invalid --platform-os value: %s (must be linux or macos)", os)
}
}

// maxPrivateHosts mirrors the API's cap on network.private_hosts entries.
const maxPrivateHosts = 32

Expand Down Expand Up @@ -404,6 +419,13 @@ func formatBrowserLocationField(value string, source kernel.BrowserLocationSourc
return fmt.Sprintf("%s (%s)", value, source)
}

func formatBrowserPlatform(platform kernel.BrowserPlatform) string {
if platform.Os == "" {
return string(kernel.BrowserOsLinux)
}
return string(platform.Os)
}

// formatVaultReferences renders the vaults linked to a session for table output,
// preferring each vault's name and falling back to its ID. It returns an empty
// string when no vaults are linked, so the row can be omitted entirely.
Expand Down Expand Up @@ -544,6 +566,7 @@ type BrowsersCreateInput struct {
Memory string
VideoMemory string
FingerprintOS string
PlatformOS string
InvocationID string
Kiosk BoolFlag
ProfileID string
Expand Down Expand Up @@ -594,6 +617,7 @@ type BrowsersLiveViewCreateInput struct {

type BrowsersGetInput struct {
Identifier string
IncludeCost bool
IncludeDeleted bool
Output string
}
Expand Down Expand Up @@ -743,7 +767,7 @@ func (b BrowsersCmd) List(ctx context.Context, in BrowsersListInput) error {
if showLeasedAt {
headers = append(headers, "Leased At")
}
headers = append(headers, "Region", "Profile", "Pool")
headers = append(headers, "Region", "Host OS", "Profile", "Pool")
if showReplay {
headers = append(headers, "Replay ID")
}
Expand Down Expand Up @@ -783,6 +807,7 @@ func (b BrowsersCmd) List(ctx context.Context, in BrowsersListInput) error {
}
row = append(row,
util.OrDash(string(browser.Region)),
formatBrowserPlatform(browser.Platform),
profile,
pool,
)
Expand Down Expand Up @@ -860,6 +885,13 @@ func (b BrowsersCmd) Create(ctx context.Context, in BrowsersCreateInput) error {
if fingerprintOS != "" {
params.Fingerprint = kernel.BrowserFingerprintParam{Os: fingerprintOS}
}
platformOS, err := parseBrowserPlatformOS(in.PlatformOS)
if err != nil {
return err
}
if platformOS != "" {
params.Platform = kernel.BrowserPlatformParam{Os: platformOS}
}
if in.InvocationID != "" {
params.InvocationID = kernel.Opt(in.InvocationID)
}
Expand Down Expand Up @@ -1013,6 +1045,7 @@ func (b BrowsersCmd) Create(ctx context.Context, in BrowsersCreateInput) error {
tableData := buildBrowserTableData(browser.SessionID, browser.CdpWsURL, browser.BrowserLiveViewURL, browser.Profile, browser.ProfileSaveChanges, browser.StartURL, browser.Name, browser.Tags)
tableData = appendBrowserLeasedAtRow(tableData, browser.LeasedAt)
tableData = appendReplayRows(tableData, browser.Replay.ReplayID, browser.Replay.ReplayViewURL, browser.Replay.StartedAt, browser.Replay.FinishedAt)
tableData = append(tableData, []string{"Host OS", formatBrowserPlatform(browser.Platform)})
tableData = append(tableData, []string{"CAPTCHA Solver", fmt.Sprintf("%t", browser.CaptchaSolver.Enabled)})
if browser.Fingerprint.Os != "" {
tableData = append(tableData, []string{"Fingerprint OS", string(browser.Fingerprint.Os)})
Expand Down Expand Up @@ -1040,6 +1073,7 @@ func printBrowserPoolAcquireResult(resp *kernel.BrowserPoolAcquireResponse) {
tableData := buildBrowserTableData(resp.SessionID, resp.CdpWsURL, resp.BrowserLiveViewURL, resp.Profile, resp.ProfileSaveChanges, resp.StartURL, resp.Name, resp.Tags)
tableData = appendBrowserLeasedAtRow(tableData, resp.LeasedAt)
tableData = appendReplayRows(tableData, resp.Replay.ReplayID, resp.Replay.ReplayViewURL, resp.Replay.StartedAt, resp.Replay.FinishedAt)
tableData = append(tableData, []string{"Host OS", formatBrowserPlatform(resp.Platform)})
tableData = append(tableData, []string{"CAPTCHA Solver", fmt.Sprintf("%t", resp.CaptchaSolver.Enabled)})
if resp.Fingerprint.Os != "" {
tableData = append(tableData, []string{"Fingerprint OS", string(resp.Fingerprint.Os)})
Expand Down Expand Up @@ -1197,6 +1231,9 @@ func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error {
}

query := kernel.BrowserGetParams{}
if in.IncludeCost {
query.IncludeCost = kernel.Opt(true)
}
if in.IncludeDeleted {
query.IncludeDeleted = kernel.Opt(true)
}
Expand Down Expand Up @@ -1226,6 +1263,7 @@ func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error {
tableData = appendBrowserLeasedAtRow(tableData, browser.LeasedAt)
tableData = appendReplayRows(tableData, browser.Replay.ReplayID, browser.Replay.ReplayViewURL, browser.Replay.StartedAt, browser.Replay.FinishedAt)
tableData = append(tableData, []string{"Region", util.OrDash(string(browser.Region))})
tableData = append(tableData, []string{"Host OS", formatBrowserPlatform(browser.Platform)})
tableData = append(tableData, browserLocationRows(browser.Location)...)
tableData = append(tableData, []string{"Timeout (seconds)", fmt.Sprintf("%d", browser.TimeoutSeconds)})
tableData = append(tableData, []string{"Headless", fmt.Sprintf("%t", browser.Headless)})
Expand Down Expand Up @@ -1270,6 +1308,15 @@ func (b BrowsersCmd) Get(ctx context.Context, in BrowsersGetInput) error {
if browser.UsageStatus != "" {
tableData = append(tableData, []string{"Usage Status", string(browser.UsageStatus)})
}
if browser.Cost.JSON.Status.Valid() {
tableData = append(tableData, []string{"Cost Status", string(browser.Cost.Status)})
if browser.Cost.JSON.EstimatedUsageSpendUsd.Valid() {
tableData = append(tableData, []string{"Estimated Usage Spend (USD)", browser.Cost.EstimatedUsageSpendUsd})
}
if browser.Cost.JSON.AsOf.Valid() && !browser.Cost.AsOf.IsZero() {
tableData = append(tableData, []string{"Cost As Of", util.FormatLocal(browser.Cost.AsOf)})
}
}

PrintTableNoPad(tableData, true)
return nil
Expand Down Expand Up @@ -1576,6 +1623,7 @@ func (b BrowsersCmd) Update(ctx context.Context, in BrowsersUpdateInput) error {
}

pterm.Success.Printf("Updated browser %s\n", browser.SessionID)
pterm.Info.Printf("Host OS: %s\n", formatBrowserPlatform(browser.Platform))
if !browser.LeasedAt.IsZero() {
pterm.Info.Printf("Leased At: %s\n", util.FormatLocal(browser.LeasedAt))
}
Expand Down Expand Up @@ -3242,7 +3290,16 @@ var browsersListCmd = &cobra.Command{
var browsersCreateCmd = &cobra.Command{
Use: "create",
Short: "Create a new browser session",
RunE: runBrowsersCreate,
Long: `Create a new browser session.

The host platform defaults to Linux. --platform-os controls the operating system
that runs the browser, while --fingerprint-os only changes what a Linux browser
reports to websites. macOS browsers are not available yet; requests currently
return platform_unavailable. When available, macOS browsers are headful, run only
in us-east, and cannot use memory, GPU, video memory, profiles, location overrides,
or fingerprint overrides. Incompatible requests return unsupported_configuration
and identify the offending fields.`,
RunE: runBrowsersCreate,
}

var browsersDeleteCmd = &cobra.Command{
Expand Down Expand Up @@ -3281,9 +3338,15 @@ URL is not stored and cannot be revoked early, so treat it as a credential.`,
var browsersGetCmd = &cobra.Command{
Use: "get <id-or-name>",
Short: "Get detailed information about a browser session by ID or name",
Long: "Retrieve and display detailed information about a specific browser session (by ID or name) including configuration, URLs, and status.",
Args: cobra.ExactArgs(1),
RunE: runBrowsersGet,
Long: `Retrieve and display a browser session's configuration, URLs, and status.

Use --include-cost to request the session's provisional usage cost. Cost is
omitted by default and is not returned by browser list or other browser commands.
A provisional amount is gross browser-meter spend before credits, subscriptions,
tax, and adjustments, not an invoice total. The API may instead report pending or
unavailable, and a running or recently deleted session may accrue after cost.as_of.`,
Args: cobra.ExactArgs(1),
RunE: runBrowsersGet,
}

var browsersSaveProfileCmd = &cobra.Command{
Expand Down Expand Up @@ -3389,6 +3452,7 @@ func init() {

// get flags
addJSONOutputFlag(browsersGetCmd)
browsersGetCmd.Flags().Bool("include-cost", false, "Include the session's provisional usage cost")
browsersGetCmd.Flags().Bool("include-deleted", false, "Include soft-deleted browser sessions in the lookup")

// view flags
Expand Down Expand Up @@ -3719,6 +3783,7 @@ unrestricted code execution inside the browser VM and is not sandboxed.`,
browsersCreateCmd.Flags().String("memory", "", "Memory for a non-GPU browser session. Headless: '1GiB' (default), '2GiB' or '4GiB'. Headful: '8GiB' (default) or '16GiB'")
browsersCreateCmd.Flags().String("video-memory", "", "Video memory (VRAM) for a GPU browser session (requires --gpu): '3GiB' (default, 4 vCPU/6GiB memory) or '6GiB' (8 vCPU/12GiB memory)")
browsersCreateCmd.Flags().String("fingerprint-os", "", "Closed beta browser fingerprint OS override: linux or macos. Contact Kernel to enable; requires --captcha-solver=true, --headless=false, --gpu=false, and default memory")
browsersCreateCmd.Flags().String("platform-os", "", "Browser host operating system: linux (default) or macos; see command help for macOS availability and restrictions")
browsersCreateCmd.Flags().String("invocation-id", "", "Associate the browser session with an invocation")
browsersCreateCmd.Flags().Bool("kiosk", false, "Launch browser in kiosk mode")
browsersCreateCmd.Flags().IntP("timeout", "t", 60, "Timeout in seconds for the browser session")
Expand Down Expand Up @@ -3866,6 +3931,7 @@ func runBrowsersCreate(cmd *cobra.Command, args []string) error {
memory, _ := cmd.Flags().GetString("memory")
videoMemory, _ := cmd.Flags().GetString("video-memory")
fingerprintOS, _ := cmd.Flags().GetString("fingerprint-os")
platformOS, _ := cmd.Flags().GetString("platform-os")
invocationID, _ := cmd.Flags().GetString("invocation-id")
kioskVal, _ := cmd.Flags().GetBool("kiosk")
timeout, _ := cmd.Flags().GetInt("timeout")
Expand Down Expand Up @@ -4029,6 +4095,7 @@ func runBrowsersCreate(cmd *cobra.Command, args []string) error {
Memory: memory,
VideoMemory: videoMemory,
FingerprintOS: fingerprintOS,
PlatformOS: platformOS,
InvocationID: invocationID,
Kiosk: BoolFlag{Set: cmd.Flags().Changed("kiosk"), Value: kioskVal},
ProfileID: profileID,
Expand Down Expand Up @@ -4111,12 +4178,14 @@ func runBrowsersLiveViewCreate(cmd *cobra.Command, args []string) error {
func runBrowsersGet(cmd *cobra.Command, args []string) error {
client := getKernelClient(cmd)
out, _ := cmd.Flags().GetString("output")
includeCost, _ := cmd.Flags().GetBool("include-cost")
includeDeleted, _ := cmd.Flags().GetBool("include-deleted")

svc := client.Browsers
b := BrowsersCmd{browsers: &svc}
return b.Get(cmd.Context(), BrowsersGetInput{
Identifier: args[0],
IncludeCost: includeCost,
IncludeDeleted: includeDeleted,
Output: out,
})
Expand Down
77 changes: 77 additions & 0 deletions cmd/browsers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1215,6 +1215,52 @@ func TestBrowsersCreate_WithFingerprintOS(t *testing.T) {
assert.Equal(t, 2, calls)
}

func TestBrowsersCreate_WithPlatformOS(t *testing.T) {
setupStdoutCapture(t)

var captured kernel.BrowserNewParams
calls := 0
fake := &FakeBrowsersService{
NewFunc: func(ctx context.Context, body kernel.BrowserNewParams, opts ...option.RequestOption) (*kernel.BrowserNewResponse, error) {
calls++
captured = body
return &kernel.BrowserNewResponse{SessionID: "sess-platform", Platform: kernel.BrowserPlatform{Os: body.Platform.Os}}, nil
},
}
b := BrowsersCmd{browsers: fake}

err := b.Create(context.Background(), BrowsersCreateInput{PlatformOS: "macos"})
require.NoError(t, err)
assert.Equal(t, kernel.BrowserOsMacos, captured.Platform.Os)
raw, err := captured.MarshalJSON()
require.NoError(t, err)
assert.Contains(t, string(raw), `"platform":{"os":"macos"}`)
assert.Contains(t, outBuf.String(), "Host OS")
assert.Contains(t, outBuf.String(), "macos")

err = b.Create(context.Background(), BrowsersCreateInput{PlatformOS: "linux"})
require.NoError(t, err)
assert.Equal(t, kernel.BrowserOsLinux, captured.Platform.Os)

err = b.Create(context.Background(), BrowsersCreateInput{PlatformOS: "windows"})
require.ErrorContains(t, err, "--platform-os")
assert.Equal(t, 2, calls)
}

func TestBrowsersPlatformAndCostHelp(t *testing.T) {
require.NotNil(t, browsersCreateCmd.Flags().Lookup("platform-os"))
assert.Contains(t, browsersCreateCmd.Long, "--fingerprint-os")
assert.Contains(t, browsersCreateCmd.Long, "not available yet")
assert.Contains(t, browsersCreateCmd.Long, "us-east")
assert.Contains(t, browsersCreateCmd.Long, "unsupported_configuration")

require.NotNil(t, browsersGetCmd.Flags().Lookup("include-cost"))
assert.Contains(t, browsersGetCmd.Long, "provisional usage cost")
assert.Contains(t, browsersGetCmd.Long, "omitted by default")
assert.Contains(t, browsersGetCmd.Long, "not an invoice total")
assert.Contains(t, browsersGetCmd.Long, "pending or")
}

func TestBrowsersCreate_WithCaptchaSolver(t *testing.T) {
setupStdoutCapture(t)

Expand Down Expand Up @@ -1812,6 +1858,34 @@ func TestBrowsersGet_Error(t *testing.T) {
assert.Contains(t, err.Error(), "get failed")
}

func TestBrowsersGet_WithIncludeCost(t *testing.T) {
setupStdoutCapture(t)
var captured kernel.BrowserGetParams
fake := &FakeBrowsersService{
GetFunc: func(ctx context.Context, id string, query kernel.BrowserGetParams, opts ...option.RequestOption) (*kernel.BrowserGetResponse, error) {
captured = query
var response kernel.BrowserGetResponse
require.NoError(t, json.Unmarshal([]byte(`{
"session_id":"sess-cost",
"platform":{"os":"macos"},
"cost":{"status":"provisional","estimated_usage_spend_usd":"1.25","as_of":"2026-01-02T03:04:05Z"}
}`), &response))
return &response, nil
},
}

err := (BrowsersCmd{browsers: fake}).Get(context.Background(), BrowsersGetInput{
Identifier: "sess-cost",
IncludeCost: true,
})
require.NoError(t, err)
assert.True(t, captured.IncludeCost.Valid())
assert.True(t, captured.IncludeCost.Value)
for _, want := range []string{"Host OS", "macos", "Cost Status", "provisional", "Estimated Usage Spend (USD)", "1.25", "Cost As Of"} {
assert.Contains(t, outBuf.String(), want)
}
}

func TestBrowsersGet_WithIncludeDeleted(t *testing.T) {
setupStdoutCapture(t)
var captured kernel.BrowserGetParams
Expand Down Expand Up @@ -3198,6 +3272,7 @@ func captureUpdateParams(t *testing.T) (*FakeBrowsersService, *kernel.BrowserUpd
SessionID: "session123",
Name: body.Name.Value,
Tags: body.Tags,
Platform: kernel.BrowserPlatform{Os: kernel.BrowserOsMacos},
LeasedAt: time.Date(2033, 6, 7, 8, 9, 10, 0, time.UTC),
}, nil
}}
Expand All @@ -3218,6 +3293,8 @@ func TestBrowsersUpdate_WithName_ForwardsParam(t *testing.T) {
assert.NoError(t, err)
assert.True(t, captured.Name.Valid())
assert.Equal(t, "new-name", captured.Name.Value)
assert.Contains(t, outBuf.String(), "Host OS")
assert.Contains(t, outBuf.String(), "macos")
assert.Contains(t, outBuf.String(), "Leased At")
assert.Contains(t, outBuf.String(), "2033")
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/invoke.go
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ func runInvocationBrowsers(cmd *cobra.Command, args []string) error {
if showLeasedAt {
headers = append(headers, "Leased At")
}
headers = append(headers, "Region", "Headless", "Stealth", "Timeout")
headers = append(headers, "Region", "Host OS", "Headless", "Stealth", "Timeout")
if showReplay {
headers = append(headers, "Replay ID")
}
Expand All @@ -624,6 +624,7 @@ func runInvocationBrowsers(cmd *cobra.Command, args []string) error {
}
row = append(row,
util.OrDash(browser.Region),
formatBrowserPlatform(browser.Platform),
fmt.Sprintf("%v", browser.Headless),
fmt.Sprintf("%v", browser.Stealth),
fmt.Sprintf("%d", browser.TimeoutSeconds),
Expand Down
16 changes: 16 additions & 0 deletions cmd/vaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,9 @@ func (c VaultsCmd) Invoke(ctx context.Context, vault, key, operation string, par
if (operation == "add_payment_method" || operation == "remove_payment_method") && (params == nil || params.PaymentMethod == nil) {
return fmt.Errorf("%s requires its documented parameters", operation)
}
if operation == "link_balance_setup" && (params == nil || params.LinkBalanceSetup == nil) {
return fmt.Errorf("link_balance_setup parameters were not initialized")
}
if operation == "update_access_token" && (params == nil || params.UpdateAccessToken == nil) {
return fmt.Errorf("update_access_token requires --spec-file with access_token")
}
Expand Down Expand Up @@ -410,6 +413,9 @@ func (c VaultsCmd) Invoke(ctx context.Context, vault, key, operation string, par
} else if params != nil && params.PaymentMethod != nil {
request = *params.PaymentMethod
request.IDOrName = vault
} else if params != nil && params.LinkBalanceSetup != nil {
request = *params.LinkBalanceSetup
request.IDOrName = vault
} else if params != nil && params.UpdateAccessToken != nil {
request = *params.UpdateAccessToken
request.IDOrName = vault
Expand Down Expand Up @@ -454,6 +460,16 @@ func (c VaultsCmd) Invoke(ctx context.Context, vault, key, operation string, par
if operation == "add_payment_method" || operation == "remove_payment_method" {
return printVaultPaymentMethodOperationResult(response, operation, output)
}
if operation == "link_balance_setup" {
setupURL, err := printVaultLinkBalanceSetupResult(response, output)
if err != nil || !open {
return err
}
if err := c.openURL(setupURL); err != nil {
return fmt.Errorf("could not open the browser; open the returned Link balance setup URL manually")
}
return nil
}
if response == nil || (response.Type != "card" && response.Type != "payment_request" && response.Type != "wallet" && response.Type != "credential" && response.Type != "credential_account") {
if item.Spec.Provider == "kernel" {
return fmt.Errorf("unexpected vault operation response; %s", kernelVaultRetryGuidance(operation))
Expand Down
Loading
Loading