Skip to content
Merged
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
7 changes: 5 additions & 2 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,10 @@ steel browser start

### Parameters

- `--stealth` (boolean, optional): Enable stealth mode (humanize interactions + auto CAPTCHA)
- `-p, --proxy` (string, optional): Use a residential proxy
- `--stealth` (boolean, optional): Enable stealth mode: humanized interactions, plus automatic CAPTCHA solving when your plan includes it
- `-p, --proxy` (string, optional): Route the session through your own proxy (http://user:pass@host:port)
- `--use-proxy` (boolean, optional): Use a Steel-managed residential proxy
- `--project` (string, optional): Project to create the session in, needed with an organization-wide API key. Defaults to STEEL_PROJECT_ID
- `--timeout` (string, optional): Session timeout in milliseconds. Defaults to 900000 (15 minutes), which every plan allows (create-time only)
- `--inactivity-timeout` (string, optional): Inactivity timeout in milliseconds: release the session when no command, CDP message, or remote input arrives for this long. Defaults to 600000 (10 minutes); pass 0 to disable (create-time only)
- `--solve-captcha` (boolean, optional): Enable manual CAPTCHA solving on new sessions (create-time only)
Expand Down Expand Up @@ -1283,6 +1285,7 @@ steel init
### Parameters

- `--agent` (boolean, optional): Run in agent mode: auto-accept interactive prompts and print agent-friendly output. Designed for AI coding agents
- `--from` (string, optional): Coding client for targeted agent setup (opencode, claude-code, codex, pi)
- `--skills` (string[], optional): Open the Steel skills installer flow. With no value, lets you choose skills interactively
- `--no-skills` (boolean, optional): Skip Steel skill installation

Expand Down
7 changes: 5 additions & 2 deletions docs/references/agent-troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,11 @@ steel browser start --local --session "$SESSION_NAME"

## Common Failures and Actions

- `Missing browser auth...`:
authenticate (`steel login`) or export `STEEL_API_KEY`.
- `auth_required` with `data.login`: you are not signed in. Show the user
`data.login.verificationUrl` and the code `data.login.userCode`. After they
approve, run the same command again.
- `auth_required` without `data.login`: export `STEEL_API_KEY` (CI, or another
API URL).
- `Failed to reach Steel session API ...`:
check endpoint flags/env and runtime availability.
- `Session "<name>" is not running...`:
Expand Down
22 changes: 18 additions & 4 deletions docs/references/steel-browser.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Main flags:
- `--session <name>`
- `--stealth`
- `--proxy <url>`
- `--use-proxy`
- `--project <id>`
- `--timeout <ms>`
- `--inactivity-timeout <ms>` (default 600000; `0` turns it off)
- `--solve-captcha`
Expand All @@ -52,11 +54,20 @@ Flag semantics:
- `stealthConfig.humanizeInteractions = true`
- `stealthConfig.autoCaptchaSolving = true`
- `solveCaptcha = true`
- If the plan refuses CAPTCHA solving (`plan_feature_unavailable` or
`deposit_required`), the session starts again without it and the output
carries a note in `data.notes`. Interactions are still humanized.
- `--solve-captcha` enables manual CAPTCHA solving for new sessions:
- `solveCaptcha = true`
- `stealthConfig.autoCaptchaSolving` is not forced on
- `--proxy <url>` sets `proxyUrl` on session creation. The Sessions API may return
`proxySource: "external"` rather than echoing the proxy URL in responses.
- If the plan refuses it, the command fails. It is never dropped.
- `--proxy <url>` sets `proxyUrl` on session creation (your own proxy). It must be
a URL. The Sessions API may return `proxySource: "external"` rather than
echoing the proxy URL in responses.
- `--use-proxy` sets `useProxy = true` (a Steel residential proxy).
`--proxy residential` is read the same way, with a note.
- `--project <id>` sets `projectId`. An organization-wide API key needs it.
`STEEL_PROJECT_ID` sets it when the flag is absent.
- `--namespace <name>` sets the credential namespace for the session. Credentials
stored under this namespace will be available for injection.
- `--credentials` enables credential injection for the session. Sends
Expand Down Expand Up @@ -201,8 +212,11 @@ serve the execution routes or the `find` target form.

## Troubleshooting (Agent-Focused)

- `Missing browser auth. Run steel login or set STEEL_API_KEY.`:
run `steel login` locally, or set `STEEL_API_KEY` in CI/job env.
- `auth_required` with `data.login`: you are not signed in, and a sign-in has
started. Show the user `data.login.verificationUrl` and the code
`data.login.userCode`. After they approve, run the same command again.
- `auth_required` without `data.login` (CI, or another API URL): set
`STEEL_API_KEY` in the job env.
- `Failed to reach Steel session API ...` in local mode:
verify `steel dev start` is running and endpoint resolution matches expected
host/port.
Expand Down
42 changes: 41 additions & 1 deletion src/api/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::config::settings::ApiMode;

pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
pub const USER_AGENT: &str = concat!("steel-cli/", env!("CARGO_PKG_VERSION"));

#[derive(Debug, Error)]
#[non_exhaustive]
Expand Down Expand Up @@ -48,6 +49,15 @@ pub enum ApiError {
}

impl ApiError {
pub fn body_str(&self, key: &str) -> Option<&str> {
match self {
Self::RequestFailed {
body: Some(body), ..
} => body.get(key).and_then(Value::as_str),
_ => None,
}
}

/// Check if this is a 404/410 (not found). Matches TS `isNotFoundApiError()`.
pub const fn is_not_found(&self) -> bool {
matches!(self, Self::RequestFailed { status, .. } if *status == 404 || *status == 410)
Expand Down Expand Up @@ -177,7 +187,7 @@ impl SteelClient {

pub fn with(base_url: String, mode: ApiMode, auth: Auth) -> Result<Self, reqwest::Error> {
let http = Client::builder()
.user_agent("steel-cli")
.user_agent(USER_AGENT)
.connect_timeout(CONNECT_TIMEOUT)
.timeout(REQUEST_TIMEOUT)
.redirect(refuse_redirects())
Expand Down Expand Up @@ -502,4 +512,34 @@ mod tests {

assert!(matches!(result, Err(ApiError::Unreachable { .. })));
}

#[tokio::test]
async fn requests_carry_the_cli_version_in_the_user_agent() {
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

assert_eq!(
USER_AGENT,
format!("steel-cli/{}", env!("CARGO_PKG_VERSION"))
);
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/test"))
.and(header("user-agent", USER_AGENT))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.expect(1)
.mount(&server)
.await;
let auth = Auth {
api_key: None,
access_token: None,
source: crate::config::auth::AuthSource::None,
};
let client = SteelClient::with(server.uri(), ApiMode::Local, auth).unwrap();

client
.request(reqwest::Method::GET, "/test", None)
.await
.unwrap();
}
}
57 changes: 53 additions & 4 deletions src/api/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ use crate::config::settings::ApiMode;
const CLOUD_CONNECT_URL: &str = "wss://connect.steel.dev";
const CLOUD_VIEWER_URL: &str = "https://app.steel.dev/sessions";

#[derive(Debug, Default)]
#[derive(Debug, Default, Clone)]
pub struct CreateSessionOptions {
pub stealth: bool,
pub stealth_without_captcha: bool,
pub proxy_url: Option<String>,
pub use_proxy: bool,
pub project_id: Option<String>,
pub timeout_ms: Option<u64>,
pub inactivity_timeout_ms: Option<u64>,
pub headless: Option<bool>,
Expand Down Expand Up @@ -46,7 +49,9 @@ fn non_empty(value: Option<&str>) -> Option<&str> {

impl Session {
pub fn parse(value: Value) -> anyhow::Result<Self> {
serde_json::from_value(value).context("The Steel API returned an unexpected session.")
serde_json::from_value(value).context(crate::util::error::ApiBadResponse(
"The Steel API returned an unexpected session.",
))
}

pub fn is_live(&self) -> bool {
Expand Down Expand Up @@ -129,14 +134,30 @@ fn build_create_body(options: &CreateSessionOptions) -> Value {
}
}

if options.stealth {
if options.stealth && options.stealth_without_captcha {
obj.insert(
"stealthConfig".into(),
json!({"humanizeInteractions": true}),
);
} else if options.stealth {
obj.insert(
"stealthConfig".into(),
json!({"humanizeInteractions": true, "autoCaptchaSolving": true}),
);
obj.insert("solveCaptcha".into(), json!(true));
}

if options.use_proxy {
obj.insert("useProxy".into(), json!(true));
}

if let Some(ref project_id) = options.project_id {
let trimmed = project_id.trim();
if !trimmed.is_empty() {
obj.insert("projectId".into(), json!(trimmed));
}
}

if options.solve_captcha {
obj.insert("solveCaptcha".into(), json!(true));
}
Expand Down Expand Up @@ -256,7 +277,12 @@ mod tests {

#[test]
fn parse_needs_an_id() {
assert!(Session::parse(json!({"status": "live"})).is_err());
let err = Session::parse(json!({"status": "live"})).unwrap_err();
assert_eq!(crate::util::output::classify(&err).code, "api_bad_response");
assert_eq!(
err.to_string(),
"The Steel API returned an unexpected session."
);
assert_eq!(session(json!({"id": "s1"})).id, "s1");
}

Expand Down Expand Up @@ -379,6 +405,29 @@ mod tests {
assert!(body["stealthConfig"].is_object());
}

#[test]
fn create_body_stealth_without_captcha_keeps_humanizing_only() {
let body = build_create_body(&CreateSessionOptions {
stealth: true,
stealth_without_captcha: true,
..Default::default()
});
assert_eq!(
body,
json!({"stealthConfig": {"humanizeInteractions": true}})
);
}

#[test]
fn create_body_steel_proxy_and_project() {
let body = build_create_body(&CreateSessionOptions {
use_proxy: true,
project_id: Some(" p-1 ".into()),
..Default::default()
});
assert_eq!(body, json!({"useProxy": true, "projectId": "p-1"}));
}

#[test]
fn create_body_all_fields() {
let body = build_create_body(&CreateSessionOptions {
Expand Down
5 changes: 3 additions & 2 deletions src/browser/profile_store.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};

use anyhow::Result;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -69,7 +69,8 @@ fn read_profile_in(name: &str, dir: &Path) -> Result<Option<ProfileData>> {
return Ok(None);
}
let contents = std::fs::read_to_string(&path)?;
let data: ProfileData = serde_json::from_str(&contents)?;
let data: ProfileData = serde_json::from_str(&contents)
.with_context(|| crate::util::error::LocalStateInvalid(path.display().to_string()))?;
Ok(Some(data))
}

Expand Down
18 changes: 16 additions & 2 deletions src/browser/state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};

use anyhow::Result;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::config::settings::ApiMode;
Expand Down Expand Up @@ -117,7 +117,9 @@ fn load_in(name: &str, dir: &Path) -> Result<Option<BrowserSession>> {
return Ok(None);
}
let contents = std::fs::read_to_string(&path)?;
Ok(Some(serde_json::from_str(&contents)?))
Ok(Some(serde_json::from_str(&contents).with_context(
|| crate::util::error::LocalStateInvalid(path.display().to_string()),
)?))
}

fn save_in(session: &BrowserSession, dir: &Path) -> Result<()> {
Expand Down Expand Up @@ -183,6 +185,18 @@ mod tests {
assert_eq!(load_in("work", dir.path()).unwrap(), Some(s));
}

#[test]
fn corrupt_session_file_is_local_state_error() {
let dir = tempfile::TempDir::new().unwrap();
std::fs::write(dir.path().join("broken.json"), "{").unwrap();
let err = load_in("broken", dir.path()).unwrap_err();
assert_eq!(
crate::util::output::classify(&err).code,
"local_state_invalid"
);
assert!(err.to_string().contains("broken.json"));
}

#[test]
fn load_missing_is_none() {
let dir = tempfile::tempdir().unwrap();
Expand Down
19 changes: 15 additions & 4 deletions src/commands/browser/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1231,17 +1231,28 @@ async fn attach(client: &SteelClient, id: &str) -> Result<BrowserSession> {

impl Browser {
pub async fn open(name: Option<&str>, start_default: bool) -> Result<Self> {
let target = super::target(name)?;
let signs_in = match &target {
Some(Target::Saved(found)) => found.mode == ApiMode::Cloud,
Some(Target::Id(_)) => true,
None if name.is_none() && start_default => {
eprintln!("warning: session \"default\" is not running; starting a new one");
true
}
None => return Err(super::not_running(name)),
};
if signs_in {
crate::commands::login::ensure_signed_in().await?;
}
let client = SteelClient::new()?;
let state = match super::target(name)? {
let state = match target {
Some(Target::Saved(found)) => *found,
Some(Target::Id(id)) => attach(&client, &id).await?,
None if name.is_none() && start_default => {
eprintln!("warning: session \"default\" is not running; starting a new one");
None => {
start::create(&client, DEFAULT_SESSION, &start::default_options())
.await?
.0
}
None => return Err(super::not_running(name)),
};
let client = client.at(&state.api_url, state.mode);
Ok(Self { client, state })
Expand Down
4 changes: 2 additions & 2 deletions src/commands/browser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub enum Target {
pub fn target(name: Option<&str>) -> anyhow::Result<Option<Target>> {
let wanted = name.unwrap_or(DEFAULT_SESSION);
if let Some(err) = state::validate_session_name(wanted) {
anyhow::bail!("{err}");
return Err(crate::util::error::invalid_input(err));
}
if let Some(found) = state::load(wanted)? {
return Ok(Some(Target::Saved(Box::new(found))));
Expand Down Expand Up @@ -112,7 +112,7 @@ pub async fn run(args: BrowserArgs) -> anyhow::Result<()> {
if let Some(ref name) = session
&& let Some(err) = state::validate_session_name(name)
{
anyhow::bail!("{err}");
return Err(crate::util::error::invalid_input(err));
}
match args.command {
Command::Start(start_args) => start::run(start_args, session.as_deref()).await,
Expand Down
Loading
Loading