Skip to content

Automate browser based workflows with AI

feat: agent-aware CLI with --json envelope, TTY detection, and capabilities (#5271)

Marc Kelechava951f75677479
diff --git a/skyvern/cli/block.py b/skyvern/cli/block.py
index 37e7384c3..ec46f696d 100644
--- a/skyvern/cli/block.py
+++ b/skyvern/cli/block.py
@@ -2,11 +2,7 @@
from __future__ import annotations
-import asyncio
-import json
-import sys
-from pathlib import Path
-from typing import Any, Callable, Coroutine
+from typing import Any
import typer
from dotenv import load_dotenv
@@ -14,59 +10,13 @@ from dotenv import load_dotenv
from skyvern.config import settings
from skyvern.utils.env_paths import resolve_backend_env_path
-from .commands._output import output, output_error
+from .commands._output import resolve_inline_or_file, run_tool
from .mcp_tools.blocks import skyvern_block_schema as tool_block_schema
from .mcp_tools.blocks import skyvern_block_validate as tool_block_validate
block_app = typer.Typer(help="Workflow block schema and validation commands.", no_args_is_help=True)
-def _emit_tool_result(result: dict[str, Any], *, json_output: bool) -> None:
- if json_output:
- json.dump(result, sys.stdout, indent=2, default=str)
- sys.stdout.write("\n")
- if not result.get("ok", False):
- raise SystemExit(1)
- return
-
- if result.get("ok", False):
- output(result.get("data"), action=str(result.get("action", "")), json_mode=False)
- return
-
- err = result.get("error") or {}
- output_error(str(err.get("message") or "Unknown error"), hint=str(err.get("hint") or ""), json_mode=False)
-
-
-def _run_tool(
- runner: Callable[[], Coroutine[Any, Any, dict[str, Any]]],
- *,
- json_output: bool,
- hint_on_exception: str,
-) -> None:
- try:
- result: dict[str, Any] = asyncio.run(runner())
- _emit_tool_result(result, json_output=json_output)
- except typer.BadParameter:
- raise
- except Exception as e:
- output_error(str(e), hint=hint_on_exception, json_mode=json_output)
-
-
-def _resolve_inline_or_file(value: str, *, param_name: str) -> str:
- if not value.startswith("@"):
- return value
-
- file_path = value[1:]
- if not file_path:
- raise typer.BadParameter(f"{param_name} file path cannot be empty after '@'.")
-
- path = Path(file_path).expanduser()
- try:
- return path.read_text(encoding="utf-8")
- except OSError as e:
- raise typer.BadParameter(f"Unable to read {param_name} file '{path}': {e}") from e
-
-
@block_app.callback()
def block_callback(
api_key: str | None = typer.Option(
@@ -97,7 +47,12 @@ def block_schema(
async def _run() -> dict[str, Any]:
return await tool_block_schema(block_type=block_type)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check block type input.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check block type input.",
+ action="skyvern_block_schema",
+ )
@block_app.command("validate")
@@ -108,7 +63,12 @@ def block_validate(
"""Validate a single workflow block definition."""
async def _run() -> dict[str, Any]:
- resolved_json = _resolve_inline_or_file(block_json, param_name="block_json")
- return await tool_block_validate(block_json=resolved_json)
-
- _run_tool(_run, json_output=json_output, hint_on_exception="Check block JSON syntax and required fields.")
+ resolved_block_json = resolve_inline_or_file(block_json, param_name="block_json")
+ return await tool_block_validate(block_json=block_json if resolved_block_json is None else resolved_block_json)
+
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check block JSON syntax and required fields.",
+ action="skyvern_block_validate",
+ )
diff --git a/skyvern/cli/commands/__init__.py b/skyvern/cli/commands/__init__.py
index 221bf587a..d09efc759 100644
--- a/skyvern/cli/commands/__init__.py
+++ b/skyvern/cli/commands/__init__.py
@@ -1,3 +1,6 @@
+from typing import Any
+
+import click
import typer
from dotenv import load_dotenv
@@ -20,6 +23,7 @@ from ..status import status_app
from ..stop_commands import stop_app
from ..tasks import tasks_app
from ..workflow import workflow_app
+from ._output import output, output_error
from .browser import browser_app
_cli_logging_configured = False
@@ -112,6 +116,108 @@ def init_browser_command() -> None:
init_browser()
+@cli_app.command("capabilities")
+def capabilities(
+ subcommand: str = typer.Argument(None, help="Show capabilities for a specific subcommand (e.g., 'workflow')."),
+ depth: int = typer.Option(
+ 1, "--depth", min=0, max=5, help="Recursion depth (0=top-level names only, 1=subcommands, 2+=full tree)."
+ ),
+ # Intentionally defaults True (agent-first) — unlike other commands which default False.
+ json_output: bool = typer.Option(True, "--json/--no-json", help="Output as JSON.", show_default=True),
+) -> None:
+ """Return the CLI command tree for agent discovery.
+
+ Uses progressive disclosure: default depth=1 returns top-level commands
+ with their immediate subcommands (~2K tokens). Drill deeper with --depth
+ or filter to a specific subcommand.
+
+ Examples:
+ skyvern capabilities # top-level + subcommands (~2K tokens)
+ skyvern capabilities workflow # just workflow commands
+ skyvern capabilities --depth 0 # command names only (~500 tokens)
+ skyvern capabilities --depth 3 # full tree (~20K tokens)
+ skyvern capabilities --no-json # human-readable
+ """
+ click_app = typer.main.get_command(cli_app)
+
+ if subcommand:
+ if not isinstance(click_app, click.Group):
+ output_error(f"Unknown subcommand: {subcommand}", json_mode=json_output)
+ ctx = click.Context(click_app, info_name="skyvern")
+ child_cmd = click_app.get_command(ctx, subcommand)
+ if child_cmd is None or child_cmd.hidden:
+ output_error(
+ f"Unknown subcommand: {subcommand}",
+ hint="Run 'skyvern capabilities --depth 0' to see available commands.",
+ json_mode=json_output,
+ )
+ tree = _walk_command_tree(child_cmd, prefix=subcommand, max_depth=depth)
+ else:
+ tree = _walk_command_tree(click_app, max_depth=depth)
+
+ output(tree, action="capabilities", json_mode=json_output)
+
+
+def _walk_command_tree(cmd: Any, prefix: str = "", max_depth: int = 1, _current_depth: int = 0) -> dict:
+ """Recursively walk the Click/Typer command tree and return structured metadata.
+
+ Uses progressive disclosure: max_depth controls how deep to recurse.
+ depth=0 returns names only, depth=1 includes immediate subcommands, etc.
+ """
+ name = prefix or cmd.name or "skyvern"
+ info: dict = {"name": name, "help": (cmd.help or "").strip()}
+
+ options = []
+ arguments = []
+ for param in getattr(cmd, "params", []):
+ if isinstance(param, click.Argument):
+ arg_info: dict = {"name": param.name, "required": param.required}
+ if param.type and param.type.name != "TEXT":
+ arg_info["type"] = param.type.name
+ arguments.append(arg_info)
+ elif isinstance(param, click.Option) and param.name not in ("help",):
+ opt_info: dict = {
+ "name": param.name,
+ "flags": list(param.opts),
+ "required": param.required,
+ }
+ if param.help:
+ opt_info["help"] = param.help
+ options.append(opt_info)
+ if arguments:
+ info["arguments"] = arguments
+ if options:
+ info["options"] = options
+
+ if isinstance(cmd, click.Group):
+ if _current_depth < max_depth:
+ children = []
+ ctx = click.Context(cmd, info_name=name)
+ for child_name in cmd.list_commands(ctx):
+ child_cmd = cmd.get_command(ctx, child_name)
+ if child_cmd is None or child_cmd.hidden:
+ continue
+ child_prefix = f"{name} {child_name}" if prefix else child_name
+ children.append(
+ _walk_command_tree(
+ child_cmd, prefix=child_prefix, max_depth=max_depth, _current_depth=_current_depth + 1
+ )
+ )
+ if children:
+ info["subcommands"] = children
+ else:
+ ctx = click.Context(cmd, info_name=name)
+ child_names = []
+ for n in cmd.list_commands(ctx):
+ c = cmd.get_command(ctx, n)
+ if c is not None and not c.hidden:
+ child_names.append(n)
+ if child_names:
+ info["subcommand_names"] = child_names
+
+ return info
+
+
if __name__ == "__main__": # pragma: no cover - manual CLI invocation
load_dotenv(resolve_backend_env_path())
cli_app()
diff --git a/skyvern/cli/commands/_output.py b/skyvern/cli/commands/_output.py
index e99ccec94..37e68d9ee 100644
--- a/skyvern/cli/commands/_output.py
+++ b/skyvern/cli/commands/_output.py
@@ -1,14 +1,19 @@
from __future__ import annotations
+import asyncio
import json
import sys
-from typing import Any
+from pathlib import Path
+from typing import Any, Callable, Coroutine, NoReturn
+import typer
from rich.console import Console
from rich.table import Table
console = Console()
+ENVELOPE_SCHEMA_VERSION = "1.0"
+
def output(
data: Any,
@@ -17,7 +22,17 @@ def output(
json_mode: bool = False,
) -> None:
if json_mode:
- envelope: dict[str, Any] = {"ok": True, "action": action, "data": data, "error": None}
+ envelope: dict[str, Any] = {
+ "schema_version": ENVELOPE_SCHEMA_VERSION,
+ "ok": True,
+ "action": action,
+ "data": data,
+ "error": None,
+ "warnings": [],
+ "browser_context": None,
+ "artifacts": None,
+ "timing_ms": None,
+ }
json.dump(envelope, sys.stdout, indent=2, default=str)
sys.stdout.write("\n")
return
@@ -35,13 +50,25 @@ def output(
console.print(str(data))
-def output_error(message: str, *, hint: str = "", json_mode: bool = False, exit_code: int = 1) -> None:
+def output_error(
+ message: str,
+ *,
+ hint: str = "",
+ action: str = "",
+ json_mode: bool = False,
+ exit_code: int = 1,
+) -> NoReturn:
if json_mode:
envelope: dict[str, Any] = {
+ "schema_version": ENVELOPE_SCHEMA_VERSION,
"ok": False,
- "action": "",
+ "action": action,
"data": None,
"error": {"message": message, "hint": hint},
+ "warnings": [],
+ "browser_context": None,
+ "artifacts": None,
+ "timing_ms": None,
}
json.dump(envelope, sys.stdout, indent=2, default=str)
sys.stdout.write("\n")
@@ -50,3 +77,64 @@ def output_error(message: str, *, hint: str = "", json_mode: bool = False, exit_
if hint:
console.print(f"[yellow]Hint: {hint}[/yellow]")
raise SystemExit(exit_code)
+
+
+def emit_tool_result(result: dict[str, Any], *, json_output: bool) -> None:
+ """Emit an MCP tool result, preserving the full MCP envelope shape in JSON mode."""
+ if json_output:
+ envelope = {**result}
+ envelope.setdefault("schema_version", ENVELOPE_SCHEMA_VERSION)
+ envelope.setdefault("warnings", [])
+ envelope.setdefault("browser_context", None)
+ envelope.setdefault("artifacts", None)
+ envelope.setdefault("timing_ms", None)
+ json.dump(envelope, sys.stdout, indent=2, default=str)
+ sys.stdout.write("\n")
+ if not result.get("ok", False):
+ raise SystemExit(1)
+ return
+
+ if result.get("ok", False):
+ output(result.get("data"), action=str(result.get("action", "")), json_mode=False)
+ return
+
+ err = result.get("error") or {}
+ output_error(
+ str(err.get("message") or "Unknown error"),
+ hint=str(err.get("hint") or ""),
+ action=str(result.get("action") or ""),
+ json_mode=False,
+ )
+
+
+def run_tool(
+ runner: Callable[[], Coroutine[Any, Any, dict[str, Any]]],
+ *,
+ json_output: bool,
+ hint_on_exception: str,
+ action: str = "",
+) -> None:
+ """Run an async MCP tool and emit the result."""
+ try:
+ result: dict[str, Any] = asyncio.run(runner())
+ emit_tool_result(result, json_output=json_output)
+ except typer.BadParameter:
+ raise
+ except Exception as e:
+ output_error(str(e), hint=hint_on_exception, action=action, json_mode=json_output)
+
+
+def resolve_inline_or_file(value: str | None, *, param_name: str) -> str | None:
+ """Resolve a value that may be a literal string or an @file reference."""
+ if value is None or not value.startswith("@"):
+ return value
+
+ file_path = value[1:]
+ if not file_path:
+ raise typer.BadParameter(f"{param_name} file path cannot be empty after '@'.")
+
+ path = Path(file_path).expanduser()
+ try:
+ return path.read_text(encoding="utf-8")
+ except OSError as e:
+ raise typer.BadParameter(f"Unable to read {param_name} file '{path}': {e}") from e
diff --git a/skyvern/cli/commands/_tty.py b/skyvern/cli/commands/_tty.py
new file mode 100644
index 000000000..97c432ece
--- /dev/null
+++ b/skyvern/cli/commands/_tty.py
@@ -0,0 +1,55 @@
+"""TTY detection utilities for agent-aware non-interactive mode."""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import Any
+
+from ._output import output_error
+
+_TRUTHY_VALUES = {"1", "true", "yes"}
+
+
+def is_interactive() -> bool:
+ """Return False if running in a CI or non-interactive context.
+
+ Checks CI and SKYVERN_NON_INTERACTIVE against explicit truthy values
+ (1, true, yes) so that setting them to "0" or "false" does not
+ accidentally trigger non-interactive mode.
+ """
+ if os.environ.get("CI", "").lower() in _TRUTHY_VALUES:
+ return False
+ if os.environ.get("SKYVERN_NON_INTERACTIVE", "").lower() in _TRUTHY_VALUES:
+ return False
+ return sys.stdin.isatty()
+
+
+def require_interactive_or_flag(
+ flag_value: Any,
+ *,
+ flag_name: str,
+ message: str,
+ env_var_prefix: str = "SKYVERN_CRED_",
+ action: str = "",
+ json_mode: bool = False,
+) -> Any:
+ """Return flag_value if provided, else check if interactive.
+
+ If interactive (TTY), returns None so the caller can proceed with
+ an interactive prompt. If non-interactive and no flag provided,
+ exits with an actionable error message in the appropriate format.
+ """
+ if flag_value is not None:
+ return flag_value
+ if is_interactive():
+ return None
+ env_var = f"{env_var_prefix}{flag_name.upper().replace('-', '_')}"
+ output_error(
+ f"{message} Running in non-interactive mode.",
+ hint=f"Set {env_var} or pass --{flag_name} <value>, or run in an interactive terminal. "
+ f"Unset SKYVERN_NON_INTERACTIVE to re-enable prompts.",
+ action=action,
+ json_mode=json_mode,
+ )
+ raise SystemExit(1) # unreachable — output_error is NoReturn
diff --git a/skyvern/cli/credential.py b/skyvern/cli/credential.py
index 7b67aafc8..aa4c93a2a 100644
--- a/skyvern/cli/credential.py
+++ b/skyvern/cli/credential.py
@@ -2,10 +2,7 @@
from __future__ import annotations
-import asyncio
-import json
-import sys
-from typing import Any, Callable, Coroutine
+from typing import Any
import typer
from dotenv import load_dotenv
@@ -13,7 +10,7 @@ from dotenv import load_dotenv
from skyvern.config import settings
from skyvern.utils.env_paths import resolve_backend_env_path
-from .commands._output import output, output_error
+from .commands._output import run_tool
from .mcp_tools.credential import skyvern_credential_delete as tool_credential_delete
from .mcp_tools.credential import skyvern_credential_get as tool_credential_get
from .mcp_tools.credential import skyvern_credential_list as tool_credential_list
@@ -24,37 +21,6 @@ credential_app = typer.Typer(
)
-def _emit_tool_result(result: dict[str, Any], *, json_output: bool) -> None:
- if json_output:
- json.dump(result, sys.stdout, indent=2, default=str)
- sys.stdout.write("\n")
- if not result.get("ok", False):
- raise SystemExit(1)
- return
-
- if result.get("ok", False):
- output(result.get("data"), action=str(result.get("action", "")), json_mode=False)
- return
-
- err = result.get("error") or {}
- output_error(str(err.get("message") or "Unknown error"), hint=str(err.get("hint") or ""), json_mode=False)
-
-
-def _run_tool(
- runner: Callable[[], Coroutine[Any, Any, dict[str, Any]]],
- *,
- json_output: bool,
- hint_on_exception: str,
-) -> None:
- try:
- result: dict[str, Any] = asyncio.run(runner())
- _emit_tool_result(result, json_output=json_output)
- except typer.BadParameter:
- raise
- except Exception as e:
- output_error(str(e), hint=hint_on_exception, json_mode=json_output)
-
-
@credential_app.callback()
def credential_callback(
api_key: str | None = typer.Option(
@@ -81,7 +47,12 @@ def credential_list(
async def _run() -> dict[str, Any]:
return await tool_credential_list(page=page, page_size=page_size)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check your API key and Skyvern connection.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check your API key and Skyvern connection.",
+ action="skyvern_credential_list",
+ )
@credential_app.command("get")
@@ -94,7 +65,12 @@ def credential_get(
async def _run() -> dict[str, Any]:
return await tool_credential_get(credential_id=credential_id)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check your API key and credential ID.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check your API key and credential ID.",
+ action="skyvern_credential_get",
+ )
@credential_app.command("delete")
@@ -107,4 +83,9 @@ def credential_delete(
async def _run() -> dict[str, Any]:
return await tool_credential_delete(credential_id=credential_id)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check your API key and credential ID.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check your API key and credential ID.",
+ action="skyvern_credential_delete",
+ )
diff --git a/skyvern/cli/credentials.py b/skyvern/cli/credentials.py
index 71a99c1b9..546d415f2 100644
--- a/skyvern/cli/credentials.py
+++ b/skyvern/cli/credentials.py
@@ -3,6 +3,9 @@
Provides `skyvern credentials add/list/get/delete` for managing stored
credentials. Passwords and secrets are collected via getpass (stdin) so they
never appear in shell history or LLM conversation logs.
+
+Non-interactive mode: set SKYVERN_NON_INTERACTIVE=1 or CI=true and pass
+all secret values via flags (--password, --totp, etc.) to avoid prompts.
"""
from __future__ import annotations
@@ -20,6 +23,8 @@ from skyvern.client.types.secret_credential import SecretCredential
from skyvern.config import settings
from skyvern.utils.env_paths import resolve_backend_env_path
+from .commands._output import output, output_error
+from .commands._tty import is_interactive, require_interactive_or_flag
from .console import console
credentials_app = typer.Typer(
@@ -38,7 +43,8 @@ def credentials_callback(
),
) -> None:
"""Store API key in Typer context."""
- ctx.obj = {"api_key": api_key}
+ ctx.ensure_object(dict)
+ ctx.obj["api_key"] = api_key
def _get_client(api_key: str | None = None) -> Skyvern:
@@ -58,24 +64,94 @@ def add_credential(
"-t",
help="Credential type: password, credit_card, or secret",
),
- username: str | None = typer.Option(None, "--username", "-u", help="Username (for password type)"),
+ username: str | None = typer.Option(
+ None, "--username", "-u", envvar="SKYVERN_CRED_USERNAME", help="Username (for password type)"
+ ),
+ password: str | None = typer.Option(
+ None,
+ "--password",
+ envvar="SKYVERN_CRED_PASSWORD",
+ help="Password (prefer env var SKYVERN_CRED_PASSWORD over flag — flags are visible in ps)",
+ ),
+ totp: str | None = typer.Option(
+ None, "--totp", envvar="SKYVERN_CRED_TOTP", help="TOTP secret (prefer env var SKYVERN_CRED_TOTP)"
+ ),
+ card_number: str | None = typer.Option(
+ None,
+ "--card-number",
+ envvar="SKYVERN_CRED_CARD_NUMBER",
+ help="Card number (prefer env var SKYVERN_CRED_CARD_NUMBER)",
+ ),
+ cvv: str | None = typer.Option(
+ None, "--cvv", envvar="SKYVERN_CRED_CVV", help="Card CVV (prefer env var SKYVERN_CRED_CVV)"
+ ),
+ exp_month: str | None = typer.Option(
+ None, "--exp-month", envvar="SKYVERN_CRED_EXP_MONTH", help="Card expiration month MM"
+ ),
+ exp_year: str | None = typer.Option(
+ None, "--exp-year", envvar="SKYVERN_CRED_EXP_YEAR", help="Card expiration year YYYY"
+ ),
+ card_brand: str | None = typer.Option(
+ None, "--card-brand", envvar="SKYVERN_CRED_CARD_BRAND", help="Card brand (visa, mastercard, etc.)"
+ ),
+ holder_name: str | None = typer.Option(
+ None, "--holder-name", envvar="SKYVERN_CRED_HOLDER_NAME", help="Cardholder name"
+ ),
+ secret_value: str | None = typer.Option(
+ None,
+ "--secret-value",
+ envvar="SKYVERN_CRED_SECRET_VALUE",
+ help="Secret value (prefer env var SKYVERN_CRED_SECRET_VALUE)",
+ ),
+ secret_label: str | None = typer.Option(
+ None, "--secret-label", envvar="SKYVERN_CRED_SECRET_LABEL", help="Secret label"
+ ),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
- """Create a credential with secrets entered securely via stdin."""
+ """Create a credential securely.
+
+ Secrets can be provided via env vars (preferred) or interactive prompts.
+ CLI flags for secrets (--password, --cvv, etc.) are visible in ps/proc —
+ use env vars instead: export SKYVERN_CRED_PASSWORD=... before running.
+
+ Examples:
+ export SKYVERN_CRED_PASSWORD=s3cret
+ skyvern credentials add --name MyLogin --type password --username [email protected] --json
+ skyvern credentials add --name MyLogin --type password --username [email protected]
+ """
valid_types = ("password", "credit_card", "secret")
if credential_type not in valid_types:
- console.print(f"[red]Invalid credential type: {credential_type}. Use one of: {', '.join(valid_types)}[/red]")
- raise typer.Exit(code=1)
+ output_error(
+ f"Invalid credential type: {credential_type}. Use one of: {', '.join(valid_types)}",
+ action="credentials.add",
+ json_mode=json_output,
+ )
client = _get_client(ctx.obj.get("api_key") if ctx.obj else None)
if credential_type == "password":
- if not username:
+ username = require_interactive_or_flag(
+ username,
+ flag_name="username",
+ message="Username required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if username is None:
username = typer.prompt("Username")
- password = typer.prompt("Password", hide_input=True)
+ password = require_interactive_or_flag(
+ password,
+ flag_name="password",
+ message="Password required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if password is None:
+ password = typer.prompt("Password", hide_input=True)
if not password:
- console.print("[red]Password cannot be empty.[/red]")
- raise typer.Exit(code=1)
- totp = typer.prompt("TOTP secret (leave blank to skip)", default="", hide_input=True)
+ output_error("Password cannot be empty.", action="credentials.add", json_mode=json_output)
+ if totp is None and is_interactive():
+ totp = typer.prompt("TOTP secret (leave blank to skip)", default="", hide_input=True)
credential = NonEmptyPasswordCredential(
username=username,
password=password,
@@ -83,33 +159,87 @@ def add_credential(
)
elif credential_type == "credit_card":
- card_number = typer.prompt("Card number", hide_input=True)
+ card_number = require_interactive_or_flag(
+ card_number,
+ flag_name="card-number",
+ message="Card number required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if card_number is None:
+ card_number = typer.prompt("Card number", hide_input=True)
if not card_number:
- console.print("[red]Card number cannot be empty.[/red]")
- raise typer.Exit(code=1)
- cvv = typer.prompt("CVV", hide_input=True)
+ output_error("Card number cannot be empty.", action="credentials.add", json_mode=json_output)
+ cvv = require_interactive_or_flag(
+ cvv,
+ flag_name="cvv",
+ message="CVV required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if cvv is None:
+ cvv = typer.prompt("CVV", hide_input=True)
if not cvv:
- console.print("[red]CVV cannot be empty.[/red]")
- raise typer.Exit(code=1)
- exp_month = typer.prompt("Expiration month (MM)")
- exp_year = typer.prompt("Expiration year (YYYY)")
- brand = typer.prompt("Card brand (e.g. visa, mastercard)")
- holder_name = typer.prompt("Cardholder name")
+ output_error("CVV cannot be empty.", action="credentials.add", json_mode=json_output)
+ exp_month = require_interactive_or_flag(
+ exp_month,
+ flag_name="exp-month",
+ message="Expiration month required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if exp_month is None:
+ exp_month = typer.prompt("Expiration month (MM)")
+ exp_year = require_interactive_or_flag(
+ exp_year,
+ flag_name="exp-year",
+ message="Expiration year required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if exp_year is None:
+ exp_year = typer.prompt("Expiration year (YYYY)")
+ card_brand = require_interactive_or_flag(
+ card_brand,
+ flag_name="card-brand",
+ message="Card brand required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if card_brand is None:
+ card_brand = typer.prompt("Card brand (e.g. visa, mastercard)")
+ holder_name = require_interactive_or_flag(
+ holder_name,
+ flag_name="holder-name",
+ message="Cardholder name required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if holder_name is None:
+ holder_name = typer.prompt("Cardholder name")
credential = NonEmptyCreditCardCredential(
card_number=card_number,
card_cvv=cvv,
card_exp_month=exp_month,
card_exp_year=exp_year,
- card_brand=brand,
+ card_brand=card_brand,
card_holder_name=holder_name,
)
else:
- secret_value = typer.prompt("Secret value", hide_input=True)
+ secret_value = require_interactive_or_flag(
+ secret_value,
+ flag_name="secret-value",
+ message="Secret value required.",
+ action="credentials.add",
+ json_mode=json_output,
+ )
+ if secret_value is None:
+ secret_value = typer.prompt("Secret value", hide_input=True)
if not secret_value:
- console.print("[red]Secret value cannot be empty.[/red]")
- raise typer.Exit(code=1)
- secret_label = typer.prompt("Secret label (leave blank to skip)", default="")
+ output_error("Secret value cannot be empty.", action="credentials.add", json_mode=json_output)
+ if secret_label is None and is_interactive():
+ secret_label = typer.prompt("Secret label (leave blank to skip)", default="")
credential = SecretCredential(
secret_value=secret_value,
secret_label=secret_label if secret_label else None,
@@ -122,10 +252,12 @@ def add_credential(
credential=credential,
)
except Exception as e:
- console.print(f"[red]Failed to create credential: {e}[/red]")
- raise typer.Exit(code=1)
+ output_error(f"Failed to create credential: {e}", action="credentials.add", json_mode=json_output)
- console.print(f"[green]Created credential:[/green] {result.credential_id}")
+ if json_output:
+ output({"credential_id": result.credential_id, "name": name}, action="credentials.add", json_mode=True)
+ else:
+ console.print(f"[green]Created credential:[/green] {result.credential_id}")
@credentials_app.command("list")
@@ -133,6 +265,7 @@ def list_credentials(
ctx: typer.Context,
page: int = typer.Option(1, "--page", help="Page number"),
page_size: int = typer.Option(10, "--page-size", help="Results per page"),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""List stored credentials (metadata only, never passwords)."""
client = _get_client(ctx.obj.get("api_key") if ctx.obj else None)
@@ -140,8 +273,19 @@ def list_credentials(
try:
credentials = client.get_credentials(page=page, page_size=page_size)
except Exception as e:
- console.print(f"[red]Failed to list credentials: {e}[/red]")
- raise typer.Exit(code=1)
+ output_error(f"Failed to list credentials: {e}", action="credentials.list", json_mode=json_output)
+
+ if json_output:
+ data = [
+ {
+ "credential_id": c.credential_id,
+ "name": c.name,
+ "credential_type": str(c.credential_type),
+ }
+ for c in (credentials or [])
+ ]
+ output(data, action="credentials.list", json_mode=True)
+ return
if not credentials:
console.print("No credentials found.")
@@ -171,6 +315,7 @@ def list_credentials(
def get_credential(
ctx: typer.Context,
credential_id: str = typer.Argument(..., help="Credential ID (starts with cred_)"),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
"""Show metadata for a single credential."""
client = _get_client(ctx.obj.get("api_key") if ctx.obj else None)
@@ -178,8 +323,16 @@ def get_credential(
try:
cred = client.get_credential(credential_id)
except Exception as e:
- console.print(f"[red]Failed to get credential: {e}[/red]")
- raise typer.Exit(code=1)
+ output_error(f"Failed to get credential: {e}", action="credentials.get", json_mode=json_output)
+
+ if json_output:
+ data = {
+ "credential_id": cred.credential_id,
+ "name": cred.name,
+ "credential_type": str(cred.credential_type),
+ }
+ output(data, action="credentials.get", json_mode=True)
+ return
table = Table(title=f"Credential: {cred.name}")
table.add_column("Field", style="cyan")
@@ -208,9 +361,22 @@ def delete_credential(
ctx: typer.Context,
credential_id: str = typer.Argument(..., help="Credential ID to delete (starts with cred_)"),
yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation prompt"),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
- """Permanently delete a stored credential."""
+ """Permanently delete a stored credential.
+
+ Examples:
+ skyvern credentials delete cred_abc123 --yes
+ skyvern credentials delete cred_abc123 --yes --json
+ """
if not yes:
+ if not is_interactive():
+ output_error(
+ "Confirmation required for delete. Running in non-interactive mode.",
+ hint="skyvern credentials delete <id> --yes",
+ action="credentials.delete",
+ json_mode=json_output,
+ )
confirm = typer.confirm(f"Delete credential {credential_id}?")
if not confirm:
console.print("Aborted.")
@@ -221,7 +387,9 @@ def delete_credential(
try:
client.delete_credential(credential_id)
except Exception as e:
- console.print(f"[red]Failed to delete credential: {e}[/red]")
- raise typer.Exit(code=1)
+ output_error(f"Failed to delete credential: {e}", action="credentials.delete", json_mode=json_output)
- console.print(f"[green]Deleted credential:[/green] {credential_id}")
+ if json_output:
+ output({"credential_id": credential_id, "deleted": True}, action="credentials.delete", json_mode=True)
+ else:
+ console.print(f"[green]Deleted credential:[/green] {credential_id}")
diff --git a/skyvern/cli/run_commands.py b/skyvern/cli/run_commands.py
index d3747da94..6020aaf25 100644
--- a/skyvern/cli/run_commands.py
+++ b/skyvern/cli/run_commands.py
@@ -15,6 +15,8 @@ from rich.panel import Panel
from rich.prompt import Confirm
from starlette.middleware import Middleware
+from skyvern.cli.commands._output import output_error
+from skyvern.cli.commands._tty import is_interactive
from skyvern.cli.console import console
from skyvern.cli.core.client import close_skyvern
from skyvern.cli.core.mcp_http_auth import MCPAPIKeyMiddleware, close_auth_db
@@ -115,25 +117,52 @@ def run_server() -> None:
)
-@run_app.command(name="ui")
-def run_ui() -> None:
- """Run the Skyvern UI server."""
- console.print(Panel("[bold blue]Starting Skyvern UI Server...[/bold blue]", border_style="blue"))
+def _handle_port_conflict(port: int, *, force: bool, command_hint: str) -> bool:
+ """Check for existing process on port and handle it.
+
+ Returns True if the caller should proceed (port is free or was freed).
+ Returns False if the user declined to kill the existing process.
+ Exits with error if non-interactive and --force was not passed.
+ """
try:
- with console.status("[bold green]Checking for existing process on port 8080...") as status:
- pids = get_pids_on_port(8080)
- if pids:
- status.stop()
- response = Confirm.ask("Process already running on port 8080. [yellow]Kill it?[/yellow]")
- if response:
- kill_pids(pids)
- console.print("✅ [green]Process killed.[/green]")
- else:
- console.print("[yellow]UI server not started. Process already running on port 8080.[/yellow]")
- return
- status.stop()
+ pids = get_pids_on_port(port)
+ if not pids:
+ return True
+ if force:
+ kill_pids(pids)
+ console.print("[green]Process killed (--force).[/green]")
+ return True
+ if not is_interactive():
+ output_error(
+ f"Process already running on port {port}.",
+ hint=command_hint,
+ )
+ response = Confirm.ask(f"Process already running on port {port}. [yellow]Kill it?[/yellow]")
+ if response:
+ kill_pids(pids)
+ console.print("[green]Process killed.[/green]")
+ else:
+ console.print(f"[yellow]Server not started. Process already running on port {port}.[/yellow]")
+ return False
except Exception as e: # pragma: no cover - CLI safeguards
- console.print(f"[red]Error checking for process: {e}[/red]")
+ console.print(f"[red]Error checking for process on port {port}: {e}[/red]")
+ return False
+ return True
+
+
+@run_app.command(name="ui")
+def run_ui(
+ force: bool = typer.Option(False, "--force", help="Kill existing process on port 8080 without prompting."),
+) -> None:
+ """Run the Skyvern UI server.
+
+ Examples:
+ skyvern run ui
+ skyvern run ui --force
+ """
+ console.print(Panel("[bold blue]Starting Skyvern UI Server...[/bold blue]", border_style="blue"))
+ if not _handle_port_conflict(8080, force=force, command_hint="skyvern run ui --force"):
+ return
frontend_env_path = resolve_frontend_env_path()
if frontend_env_path is None:
@@ -171,24 +200,18 @@ def run_ui() -> None:
@run_app.command(name="ui-dev")
-def run_ui_dev() -> None:
- """Run the Skyvern UI server in development mode (npm run start-local)."""
+def run_ui_dev(
+ force: bool = typer.Option(False, "--force", help="Kill existing process on port 8080 without prompting."),
+) -> None:
+ """Run the Skyvern UI server in development mode (npm run start-local).
+
+ Examples:
+ skyvern run ui-dev
+ skyvern run ui-dev --force
+ """
console.print(Panel("[bold blue]Starting Skyvern UI Server (dev mode)...[/bold blue]", border_style="blue"))
- try:
- with console.status("[bold green]Checking for existing process on port 8080...") as status:
- pids = get_pids_on_port(8080)
- if pids:
- status.stop()
- response = Confirm.ask("Process already running on port 8080. [yellow]Kill it?[/yellow]")
- if response:
- kill_pids(pids)
- console.print("✅ [green]Process killed.[/green]")
- else:
- console.print("[yellow]UI server not started. Process already running on port 8080.[/yellow]")
- return
- status.stop()
- except Exception as e: # pragma: no cover - CLI safeguards
- console.print(f"[red]Error checking for process: {e}[/red]")
+ if not _handle_port_conflict(8080, force=force, command_hint="skyvern run ui-dev --force"):
+ return
frontend_env_path = resolve_frontend_env_path()
if frontend_env_path is None:
diff --git a/skyvern/cli/skills/skyvern/SKILL.md b/skyvern/cli/skills/skyvern/SKILL.md
index ef52e9712..ae0c1b56e 100644
--- a/skyvern/cli/skills/skyvern/SKILL.md
+++ b/skyvern/cli/skills/skyvern/SKILL.md
@@ -6,8 +6,7 @@ allowed-tools: Bash(skyvern:*)
# Skyvern Browser Automation -- CLI Reference
-Skyvern uses AI to navigate and interact with websites. This skill teaches the
-CLI commands. Every example is a runnable `skyvern <command>` invocation.
+Skyvern uses AI to navigate and interact with websites. Every example is a runnable `skyvern <command>` invocation.
## Setup
@@ -60,11 +59,14 @@ only.
| `skyvern credential list` | List credentials (metadata) |
| `skyvern credential get` | Get credential metadata |
| `skyvern credential delete` | Delete a credential |
-| `skyvern credentials add` | Create a credential (interactive) |
+| `skyvern credentials add` | Create a credential (env vars or interactive) |
| `skyvern block schema` | Get block type schema |
| `skyvern block validate` | Validate a block definition |
+| `skyvern capabilities` | Discover all commands (agent-first) |
-All commands accept `--json` for machine-readable output (e.g. `skyvern browser session create --json`).
+All commands accept `--json` for structured output with a consistent envelope.
+**Agent mode:** `skyvern capabilities --json` for discovery, `SKYVERN_NON_INTERACTIVE=1`
+to prevent prompts, `--yes`/`--force` to skip confirmations. See `references/agent-mode.md`.
---
@@ -495,4 +497,4 @@ See `references/prompt-writing.md` for templates and anti-patterns.
| `references/rerun-playbook.md` | Rerun procedures and comparison |
| `references/complex-inputs.md` | Date pickers, uploads, dropdowns |
| `references/tool-map.md` | Complete tool inventory by outcome |
-| `references/cli-parity.md` | CLI command to MCP tool mapping |
+| `references/cli-parity.md` | CLI/MCP mapping and agent-aware features |
diff --git a/skyvern/cli/skills/skyvern/references/agent-mode.md b/skyvern/cli/skills/skyvern/references/agent-mode.md
new file mode 100644
index 000000000..70281a944
--- /dev/null
+++ b/skyvern/cli/skills/skyvern/references/agent-mode.md
@@ -0,0 +1,64 @@
+# Agent Mode
+
+Patterns for using the Skyvern CLI from AI agents and CI/CD pipelines.
+
+## Discovery
+
+```bash
+# Top-level commands (~1.4K tokens, default)
+skyvern capabilities --json
+
+# Drill into a specific command group
+skyvern capabilities workflow --json
+
+# Full tree (~20K tokens, opt-in)
+skyvern capabilities --depth 3 --json
+```
+
+## Non-interactive mode
+
+Set `SKYVERN_NON_INTERACTIVE=1` or `CI=true` to prevent interactive prompts.
+All required values must be passed via env vars or flags. Errors return JSON when `--json` is set.
+
+## Credentials (secrets)
+
+Use env vars for secrets — CLI flags are visible in `ps` and `/proc/*/cmdline`.
+
+```bash
+# Set secrets as env vars BEFORE the command (not inline — avoids shell history leak)
+export SKYVERN_CRED_PASSWORD="s3cret"
+export SKYVERN_CRED_TOTP="JBSWY3DP"
+skyvern credentials add --name "prod-login" --type password \
+ --username "[email protected]" --json
+
+# Credit card
+export SKYVERN_CRED_CARD_NUMBER="4111111111111111"
+export SKYVERN_CRED_CVV="123"
+skyvern credentials add --name "test-card" --type credit_card \
+ --exp-month 12 --exp-year 2027 --card-brand visa --holder-name "John Doe" --json
+
+# Secret
+export SKYVERN_CRED_SECRET_VALUE="sk_live_abc123"
+skyvern credentials add --name "api-token" --type secret --json
+
+# Delete without confirmation
+skyvern credentials delete cred_abc123 --yes --json
+```
+
+Available env vars: `SKYVERN_CRED_PASSWORD`, `SKYVERN_CRED_TOTP`,
+`SKYVERN_CRED_CARD_NUMBER`, `SKYVERN_CRED_CVV`, `SKYVERN_CRED_SECRET_VALUE`,
+`SKYVERN_CRED_USERNAME`, `SKYVERN_CRED_EXP_MONTH`, `SKYVERN_CRED_EXP_YEAR`,
+`SKYVERN_CRED_CARD_BRAND`, `SKYVERN_CRED_HOLDER_NAME`, `SKYVERN_CRED_SECRET_LABEL`.
+
+## Other commands
+
+```bash
+skyvern run ui --force
+skyvern workflow list --json | jq '.ok'
+skyvern status --json | jq '.data'
+```
+
+## Structured output
+
+Every `--json` response uses the same envelope:
+`{schema_version, ok, action, data, error, warnings, browser_context, artifacts, timing_ms}`
diff --git a/skyvern/cli/skills/skyvern/references/cli-parity.md b/skyvern/cli/skills/skyvern/references/cli-parity.md
index 80d19c6b6..64eac5202 100644
--- a/skyvern/cli/skills/skyvern/references/cli-parity.md
+++ b/skyvern/cli/skills/skyvern/references/cli-parity.md
@@ -9,3 +9,17 @@ Common mappings:
- `skyvern credential list` -> `skyvern_credential_list`
Use CLI for local operator workflows and MCP tools for agent-driven integrations.
+
+## Agent-Aware CLI
+
+The CLI supports structured JSON output and non-interactive mode for AI agents:
+
+| Feature | CLI flag | Env var |
+|---------|----------|---------|
+| Structured JSON output | `--json` on any command | - |
+| Non-interactive mode | - | `SKYVERN_NON_INTERACTIVE=1` or `CI=true` |
+| Skip confirmations | `--yes` or `--force` | - |
+| Discover commands | `skyvern capabilities --json` | - |
+
+All `--json` responses use the same envelope:
+`{schema_version, ok, action, data, error, warnings, browser_context, artifacts, timing_ms}`
diff --git a/skyvern/cli/skills/skyvern/references/credentials.md b/skyvern/cli/skills/skyvern/references/credentials.md
index 1464ae629..d675f1a05 100644
--- a/skyvern/cli/skills/skyvern/references/credentials.md
+++ b/skyvern/cli/skills/skyvern/references/credentials.md
@@ -1,20 +1,56 @@
# Credential Management
-## Naming convention
+## Create credentials (non-interactive)
+
+Use env vars for secrets — CLI flags are visible in `ps` and `/proc/*/cmdline`.
+
+```bash
+# Set secrets as env vars BEFORE the command (not inline — avoids shell history leak)
+export SKYVERN_CRED_PASSWORD="s3cret"
+skyvern credentials add --name "prod-login" --type password \
+ --username "[email protected]" --json
+
+# With TOTP
+export SKYVERN_CRED_PASSWORD="s3cret"
+export SKYVERN_CRED_TOTP="JBSWY3DPEHPK3PXP"
+skyvern credentials add --name "prod-mfa" --type password \
+ --username "[email protected]" --json
+
+# Credit card (sensitive fields via env vars)
+export SKYVERN_CRED_CARD_NUMBER="4111111111111111"
+export SKYVERN_CRED_CVV="123"
+skyvern credentials add --name "test-card" --type credit_card \
+ --exp-month "12" --exp-year "2027" --card-brand "visa" \
+ --holder-name "John Doe" --json
-Use environment and target domain in credential names.
+# Secret (API key, token, etc.)
+export SKYVERN_CRED_SECRET_VALUE="sk_live_abc123"
+skyvern credentials add --name "api-token" --type secret \
+ --secret-label "Stripe key" --json
+```
-Example: `prod-salesforce-primary` or `staging-hubspot-sandbox`.
+Set `SKYVERN_NON_INTERACTIVE=1` to ensure prompts never fire.
-## Lifecycle
+## List and lookup
+
+```bash
+skyvern credential list --json
+skyvern credential get --id cred_abc123 --json
+```
+
+## Delete
+
+```bash
+skyvern credentials delete cred_abc123 --yes --json
+```
+
+## Naming convention
-1. Create/store credential in vault.
-2. Validate login once.
-3. Reuse by ID in automation.
-4. Rotate and retire on schedule.
+Use environment and target domain: `prod-salesforce-primary`, `staging-hubspot-sandbox`.
-## Safety checks
+## Safety
+- Use env vars for secrets, not CLI flags.
- Never print secrets in logs.
- Confirm credential IDs map to the expected system.
- Delete stale credentials proactively.
diff --git a/skyvern/cli/status.py b/skyvern/cli/status.py
index 2262dde02..a7308fefb 100644
--- a/skyvern/cli/status.py
+++ b/skyvern/cli/status.py
@@ -4,6 +4,7 @@ import socket
import typer
from rich.table import Table
+from .commands._output import output
from .console import console
status_app = typer.Typer(help="Check status of Skyvern components.", invoke_without_command=True)
@@ -18,31 +19,49 @@ def _check_port(port: int) -> bool:
return False
-def _status_table() -> Table:
+def _status_data() -> list[dict]:
api_port = int(os.getenv("PORT", 8000))
ui_port = 8080
db_port = 5432
- components = [
- ("API server", _check_port(api_port), "skyvern run server"),
- ("UI server", _check_port(ui_port), "skyvern run ui"),
- ("PostgreSQL", _check_port(db_port), "skyvern init --no-postgres false"),
+ return [
+ {"component": "API server", "running": _check_port(api_port), "start_command": "skyvern run server"},
+ {"component": "UI server", "running": _check_port(ui_port), "start_command": "skyvern run ui"},
+ {
+ "component": "PostgreSQL",
+ "running": _check_port(db_port),
+ "start_command": "skyvern init --no-postgres false",
+ },
]
+
+def _status_table(data: list[dict]) -> Table:
table = Table(title="Skyvern Component Status")
table.add_column("Component", style="bold")
table.add_column("Running")
table.add_column("Start Command")
- for name, running, cmd in components:
- status = "[green]Yes[/green]" if running else "[red]No[/red]"
- table.add_row(name, status, cmd)
+ for item in data:
+ status = "[green]Yes[/green]" if item["running"] else "[red]No[/red]"
+ table.add_row(item["component"], status, item["start_command"])
return table
@status_app.callback(invoke_without_command=True)
-def status_callback(ctx: typer.Context) -> None:
- """Show status for API server, UI, and database."""
+def status_callback(
+ ctx: typer.Context,
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
+) -> None:
+ """Show status for API server, UI, and database.
+
+ Examples:
+ skyvern status
+ skyvern status --json
+ """
if ctx.invoked_subcommand is None:
- console.print(_status_table())
+ data = _status_data()
+ if json_output:
+ output(data, action="status", json_mode=True)
+ else:
+ console.print(_status_table(data))
diff --git a/skyvern/cli/stop_commands.py b/skyvern/cli/stop_commands.py
index 87df0c41f..c656337ff 100644
--- a/skyvern/cli/stop_commands.py
+++ b/skyvern/cli/stop_commands.py
@@ -4,11 +4,30 @@ import psutil
import typer
from rich.panel import Panel
+from .commands._output import emit_tool_result
from .console import console
stop_app = typer.Typer(help="Commands to stop Skyvern services.")
+def _emit_stop_result(
+ *,
+ action: str,
+ payload: dict,
+ stopped: bool,
+ not_found_message: str,
+) -> None:
+ emit_tool_result(
+ {
+ "ok": stopped,
+ "action": action,
+ "data": payload,
+ "error": None if stopped else {"message": not_found_message, "hint": ""},
+ },
+ json_output=True,
+ )
+
+
def get_pids_on_port(port: int) -> List[int]:
"""Return a list of PIDs listening on the given port."""
pids = []
@@ -21,97 +40,140 @@ def get_pids_on_port(port: int) -> List[int]:
return list(set(pids))
-def kill_pids(pids: List[int], service_name: str) -> bool:
+def kill_pids(pids: List[int], service_name: str, *, quiet: bool = False) -> bool:
"""Kill the given list of PIDs in a cross-platform way."""
if not pids:
- console.print(f"[yellow]No {service_name} processes found.[/yellow]")
+ if not quiet:
+ console.print(f"[yellow]No {service_name} processes found.[/yellow]")
return False
killed_any = False
for pid in pids:
try:
- # Use psutil for cross-platform process killing
process = psutil.Process(pid)
process.terminate()
- # Wait for the process to exit, use kill() as fallback
process_stopped = False
try:
process.wait(timeout=3)
process_stopped = True
except psutil.TimeoutExpired:
- console.print(f"[yellow]Process {pid} didn't terminate gracefully, forcing kill...[/yellow]")
+ if not quiet:
+ console.print(f"[yellow]Process {pid} didn't terminate gracefully, forcing kill...[/yellow]")
process.kill()
try:
process.wait(timeout=3)
process_stopped = True
except psutil.TimeoutExpired:
- console.print(f"[red]Process {pid} remains unresponsive even after force kill[/red]")
+ if not quiet:
+ console.print(f"[red]Process {pid} remains unresponsive even after force kill[/red]")
if process_stopped:
killed_any = True
- console.print(f"[green]✅ Stopped {service_name} process (PID: {pid})[/green]")
+ if not quiet:
+ console.print(f"[green]Stopped {service_name} process (PID: {pid})[/green]")
else:
- console.print(f"[red]❌ Failed to stop {service_name} process (PID: {pid})[/red]")
+ if not quiet:
+ console.print(f"[red]Failed to stop {service_name} process (PID: {pid})[/red]")
except psutil.NoSuchProcess:
- console.print(f"[yellow]Process {pid} was already stopped[/yellow]")
+ if not quiet:
+ console.print(f"[yellow]Process {pid} was already stopped[/yellow]")
except psutil.AccessDenied:
- console.print(f"[red]Access denied when trying to stop process {pid}[/red]")
+ if not quiet:
+ console.print(f"[red]Access denied when trying to stop process {pid}[/red]")
except Exception as e:
- console.print(f"[red]Failed to stop process {pid}: {e}[/red]")
+ if not quiet:
+ console.print(f"[red]Failed to stop process {pid}: {e}[/red]")
return killed_any
@stop_app.command(name="all")
-def stop_all() -> None:
- """Stop all Skyvern services running on ports 8000, 8080, and 9090."""
- console.print(Panel("[bold red]Stopping All Skyvern Services...[/bold red]", border_style="red"))
+def stop_all(
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
+) -> None:
+ """Stop all Skyvern services running on ports 8000, 8080, and 9090.
+
+ Examples:
+ skyvern stop all
+ skyvern stop all --json
+ """
+ if not json_output:
+ console.print(Panel("[bold red]Stopping All Skyvern Services...[/bold red]", border_style="red"))
- # Stop processes on port 8000 (API server)
pids_8000 = get_pids_on_port(8000)
- killed_8000 = kill_pids(pids_8000, "Skyvern API server (port 8000)")
+ killed_8000 = kill_pids(pids_8000, "Skyvern API server (port 8000)", quiet=json_output)
- # Stop processes on port 8080 (UI server)
pids_8080 = get_pids_on_port(8080)
- killed_8080 = kill_pids(pids_8080, "Skyvern UI server (port 8080)")
+ killed_8080 = kill_pids(pids_8080, "Skyvern UI server (port 8080)", quiet=json_output)
- # Stop processes on port 9090 (UI server)
pids_9090 = get_pids_on_port(9090)
- killed_9090 = kill_pids(pids_9090, "Skyvern UI server (port 9090)")
-
- if killed_8000 or killed_8080 or killed_9090:
- console.print("[green]🛑 All Skyvern services stopped successfully.[/green]")
+ killed_9090 = kill_pids(pids_9090, "Skyvern UI server (port 9090)", quiet=json_output)
+
+ stopped = killed_8000 or killed_8080 or killed_9090
+ not_found_message = "No Skyvern services found running on ports 8000, 8080, or 9090."
+ if json_output:
+ _emit_stop_result(
+ action="stop.all",
+ payload={"stopped": stopped, "services": ["api", "ui", "ui-dev"]},
+ stopped=stopped,
+ not_found_message=not_found_message,
+ )
+ elif stopped:
+ console.print("[green]All Skyvern services stopped successfully.[/green]")
else:
- console.print("[yellow]No Skyvern services found running on ports 8000, 8080, or 9090.[/yellow]")
+ console.print(f"[yellow]{not_found_message}[/yellow]")
@stop_app.command(name="ui")
-def stop_ui() -> None:
+def stop_ui(
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
+) -> None:
"""Stop the Skyvern UI servers running on ports 8080 and 9090."""
- console.print(Panel("[bold red]Stopping Skyvern UI Servers...[/bold red]", border_style="red"))
+ if not json_output:
+ console.print(Panel("[bold red]Stopping Skyvern UI Servers...[/bold red]", border_style="red"))
- # Stop processes on port 8080
pids_8080 = get_pids_on_port(8080)
- killed_8080 = kill_pids(pids_8080, "Skyvern UI server (port 8080)")
+ killed_8080 = kill_pids(pids_8080, "Skyvern UI server (port 8080)", quiet=json_output)
- # Stop processes on port 9090
pids_9090 = get_pids_on_port(9090)
- killed_9090 = kill_pids(pids_9090, "Skyvern UI server (port 9090)")
-
- if killed_8080 or killed_9090:
- console.print("[green]🛑 Skyvern UI servers stopped successfully.[/green]")
+ killed_9090 = kill_pids(pids_9090, "Skyvern UI server (port 9090)", quiet=json_output)
+
+ stopped = killed_8080 or killed_9090
+ not_found_message = "No Skyvern UI servers found running on ports 8080 or 9090."
+ if json_output:
+ _emit_stop_result(
+ action="stop.ui",
+ payload={"stopped": stopped, "services": ["ui", "ui-dev"]},
+ stopped=stopped,
+ not_found_message=not_found_message,
+ )
+ elif stopped:
+ console.print("[green]Skyvern UI servers stopped successfully.[/green]")
else:
- console.print("[yellow]No Skyvern UI servers found running on ports 8080 or 9090.[/yellow]")
+ console.print(f"[yellow]{not_found_message}[/yellow]")
@stop_app.command(name="server")
-def stop_server(port: int = typer.Option(8000, "--port", "-p", help="Port number for the Skyvern API server")) -> None:
+def stop_server(
+ port: int = typer.Option(8000, "--port", "-p", help="Port number for the Skyvern API server"),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
+) -> None:
"""Stop the Skyvern API server running on the specified port (default: 8000)."""
- console.print(Panel(f"[bold red]Stopping Skyvern API Server (port {port})...[/bold red]", border_style="red"))
+ if not json_output:
+ console.print(Panel(f"[bold red]Stopping Skyvern API Server (port {port})...[/bold red]", border_style="red"))
pids = get_pids_on_port(port)
- if kill_pids(pids, f"Skyvern API server (port {port})"):
- console.print(f"[green]🛑 Skyvern API server on port {port} stopped successfully.[/green]")
+ stopped = kill_pids(pids, f"Skyvern API server (port {port})", quiet=json_output)
+ not_found_message = f"No Skyvern API server found running on port {port}."
+ if json_output:
+ _emit_stop_result(
+ action="stop.server",
+ payload={"stopped": stopped, "port": port},
+ stopped=stopped,
+ not_found_message=not_found_message,
+ )
+ elif stopped:
+ console.print(f"[green]Skyvern API server on port {port} stopped successfully.[/green]")
else:
- console.print(f"[yellow]No Skyvern API server found running on port {port}.[/yellow]")
+ console.print(f"[yellow]{not_found_message}[/yellow]")
diff --git a/skyvern/cli/tasks.py b/skyvern/cli/tasks.py
index 473bb150f..e9849d2d7 100644
--- a/skyvern/cli/tasks.py
+++ b/skyvern/cli/tasks.py
@@ -13,6 +13,7 @@ from skyvern.client import Skyvern
from skyvern.config import settings
from skyvern.utils.env_paths import resolve_backend_env_path
+from .commands._output import output, output_error
from .console import console
tasks_app = typer.Typer(help="Manage Skyvern tasks and operations.")
@@ -29,7 +30,8 @@ def tasks_callback(
),
) -> None:
"""Store API key in Typer context."""
- ctx.obj = {"api_key": api_key}
+ ctx.ensure_object(dict)
+ ctx.obj["api_key"] = api_key
def _get_client(api_key: str | None = None) -> Skyvern:
@@ -54,8 +56,21 @@ def _list_workflow_tasks(client: Skyvern, run_id: str) -> list[dict]:
def list_tasks(
ctx: typer.Context,
workflow_run_id: str = typer.Option(..., "--workflow-run-id", "-r", help="Workflow run ID"),
+ json_output: bool = typer.Option(False, "--json", help="Output as JSON."),
) -> None:
- """List tasks for a workflow run."""
+ """List tasks for a workflow run.
+
+ Examples:
+ skyvern tasks list --workflow-run-id wr_abc123
+ skyvern tasks list --workflow-run-id wr_abc123 --json
+ """
client = _get_client(ctx.obj.get("api_key") if ctx.obj else None)
- tasks = _list_workflow_tasks(client, workflow_run_id)
- console.print(Panel(json.dumps(tasks, indent=2), border_style="cyan"))
+ try:
+ tasks = _list_workflow_tasks(client, workflow_run_id)
+ except Exception as e:
+ output_error(f"Failed to list tasks: {e}", action="tasks.list", json_mode=json_output)
+
+ if json_output:
+ output(tasks, action="tasks.list", json_mode=True)
+ else:
+ console.print(Panel(json.dumps(tasks, indent=2), border_style="cyan"))
diff --git a/skyvern/cli/workflow.py b/skyvern/cli/workflow.py
index faf0c4c1b..af545f699 100644
--- a/skyvern/cli/workflow.py
+++ b/skyvern/cli/workflow.py
@@ -2,11 +2,7 @@
from __future__ import annotations
-import asyncio
-import json
-import sys
-from pathlib import Path
-from typing import Any, Callable, Coroutine
+from typing import Any
import typer
from dotenv import load_dotenv
@@ -14,7 +10,7 @@ from dotenv import load_dotenv
from skyvern.config import settings
from skyvern.utils.env_paths import resolve_backend_env_path
-from .commands._output import output, output_error
+from .commands._output import resolve_inline_or_file, run_tool
from .mcp_tools.workflow import skyvern_workflow_cancel as tool_workflow_cancel
from .mcp_tools.workflow import skyvern_workflow_create as tool_workflow_create
from .mcp_tools.workflow import skyvern_workflow_delete as tool_workflow_delete
@@ -27,52 +23,6 @@ from .mcp_tools.workflow import skyvern_workflow_update as tool_workflow_update
workflow_app = typer.Typer(help="Manage Skyvern workflows.", no_args_is_help=True)
-def _emit_tool_result(result: dict[str, Any], *, json_output: bool) -> None:
- if json_output:
- json.dump(result, sys.stdout, indent=2, default=str)
- sys.stdout.write("\n")
- if not result.get("ok", False):
- raise SystemExit(1)
- return
-
- if result.get("ok", False):
- output(result.get("data"), action=str(result.get("action", "")), json_mode=False)
- return
-
- err = result.get("error") or {}
- output_error(str(err.get("message", "Unknown error")), hint=str(err.get("hint", "")), json_mode=False)
-
-
-def _run_tool(
- runner: Callable[[], Coroutine[Any, Any, dict[str, Any]]],
- *,
- json_output: bool,
- hint_on_exception: str,
-) -> None:
- try:
- result: dict[str, Any] = asyncio.run(runner())
- _emit_tool_result(result, json_output=json_output)
- except typer.BadParameter:
- raise
- except Exception as e:
- output_error(str(e), hint=hint_on_exception, json_mode=json_output)
-
-
-def _resolve_inline_or_file(value: str | None, *, param_name: str) -> str | None:
- if value is None or not value.startswith("@"):
- return value
-
- file_path = value[1:]
- if not file_path:
- raise typer.BadParameter(f"{param_name} file path cannot be empty after '@'.")
-
- path = Path(file_path).expanduser()
- try:
- return path.read_text(encoding="utf-8")
- except OSError as e:
- raise typer.BadParameter(f"Unable to read {param_name} file '{path}': {e}") from e
-
-
@workflow_app.callback()
def workflow_callback(
api_key: str | None = typer.Option(
@@ -114,7 +64,12 @@ def workflow_list(
only_workflows=only_workflows,
)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check your API key and workflow list filters.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check your API key and workflow list filters.",
+ action="skyvern_workflow_list",
+ )
@workflow_app.command("get")
@@ -128,7 +83,12 @@ def workflow_get(
async def _run() -> dict[str, Any]:
return await tool_workflow_get(workflow_id=workflow_id, version=version)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check your API key and workflow ID.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check your API key and workflow ID.",
+ action="skyvern_workflow_get",
+ )
@workflow_app.command("create")
@@ -149,15 +109,19 @@ def workflow_create(
"""Create a workflow."""
async def _run() -> dict[str, Any]:
- resolved_definition = _resolve_inline_or_file(definition, param_name="definition")
- assert resolved_definition is not None
+ resolved_definition = resolve_inline_or_file(definition, param_name="definition")
return await tool_workflow_create(
- definition=resolved_definition,
+ definition=definition if resolved_definition is None else resolved_definition,
format=definition_format,
folder_id=folder_id,
)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check the workflow definition syntax.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check the workflow definition syntax.",
+ action="skyvern_workflow_create",
+ )
@workflow_app.command("update")
@@ -178,15 +142,19 @@ def workflow_update(
"""Update a workflow definition."""
async def _run() -> dict[str, Any]:
- resolved_definition = _resolve_inline_or_file(definition, param_name="definition")
- assert resolved_definition is not None
+ resolved_definition = resolve_inline_or_file(definition, param_name="definition")
return await tool_workflow_update(
workflow_id=workflow_id,
- definition=resolved_definition,
+ definition=definition if resolved_definition is None else resolved_definition,
format=definition_format,
)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check the workflow ID and definition syntax.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check the workflow ID and definition syntax.",
+ action="skyvern_workflow_update",
+ )
@workflow_app.command("delete")
@@ -200,7 +168,12 @@ def workflow_delete(
async def _run() -> dict[str, Any]:
return await tool_workflow_delete(workflow_id=workflow_id, force=force)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check the workflow ID and your permissions.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check the workflow ID and your permissions.",
+ action="skyvern_workflow_delete",
+ )
@workflow_app.command("run")
@@ -230,7 +203,7 @@ def workflow_run(
"""Run a workflow."""
async def _run() -> dict[str, Any]:
- resolved_params = _resolve_inline_or_file(params, param_name="params")
+ resolved_params = resolve_inline_or_file(params, param_name="params")
return await tool_workflow_run(
workflow_id=workflow_id,
parameters=resolved_params,
@@ -242,7 +215,12 @@ def workflow_run(
run_with=run_with,
)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check the workflow ID and run parameters.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check the workflow ID and run parameters.",
+ action="skyvern_workflow_run",
+ )
@workflow_app.command("status")
@@ -255,7 +233,12 @@ def workflow_status(
async def _run() -> dict[str, Any]:
return await tool_workflow_status(run_id=run_id, verbosity="full")
- _run_tool(_run, json_output=json_output, hint_on_exception="Check the run ID and API key.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check the run ID and API key.",
+ action="skyvern_workflow_status",
+ )
@workflow_app.command("cancel")
@@ -268,4 +251,9 @@ def workflow_cancel(
async def _run() -> dict[str, Any]:
return await tool_workflow_cancel(run_id=run_id)
- _run_tool(_run, json_output=json_output, hint_on_exception="Check the run ID and API key.")
+ run_tool(
+ _run,
+ json_output=json_output,
+ hint_on_exception="Check the run ID and API key.",
+ action="skyvern_workflow_cancel",
+ )
diff --git a/tests/unit/test_cli_agent_aware.py b/tests/unit/test_cli_agent_aware.py
new file mode 100644
index 000000000..54a2d0607
--- /dev/null
+++ b/tests/unit/test_cli_agent_aware.py
@@ -0,0 +1,417 @@
+"""Tests for agent-aware CLI features: JSON envelope, TTY detection, capabilities."""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+from unittest.mock import patch
+
+import pytest
+
+from skyvern.cli.commands._output import (
+ ENVELOPE_SCHEMA_VERSION,
+ emit_tool_result,
+ output,
+ output_error,
+ resolve_inline_or_file,
+ run_tool,
+)
+from skyvern.cli.commands._tty import is_interactive, require_interactive_or_flag
+
+# ---------------------------------------------------------------------------
+# JSON envelope tests
+# ---------------------------------------------------------------------------
+
+
+class TestOutputEnvelope:
+ def test_json_envelope_has_schema_version(self):
+ buf = io.StringIO()
+ with patch("sys.stdout", buf):
+ output({"key": "value"}, action="test", json_mode=True)
+ envelope = json.loads(buf.getvalue())
+ assert envelope["schema_version"] == ENVELOPE_SCHEMA_VERSION
+ assert envelope["ok"] is True
+ assert envelope["action"] == "test"
+ assert envelope["data"] == {"key": "value"}
+ assert envelope["error"] is None
+
+ def test_json_envelope_has_mcp_fields(self):
+ buf = io.StringIO()
+ with patch("sys.stdout", buf):
+ output({"x": 1}, action="t", json_mode=True)
+ envelope = json.loads(buf.getvalue())
+ assert "warnings" in envelope
+ assert envelope["warnings"] == []
+ assert "browser_context" in envelope
+ assert envelope["browser_context"] is None
+ assert "artifacts" in envelope
+ assert envelope["artifacts"] is None
+ assert "timing_ms" in envelope
+ assert envelope["timing_ms"] is None
+
+ def test_json_error_envelope_has_schema_version(self):
+ buf = io.StringIO()
+ with patch("sys.stdout", buf), pytest.raises(SystemExit) as exc_info:
+ output_error("bad thing", hint="try again", json_mode=True)
+ assert exc_info.value.code == 1
+ envelope = json.loads(buf.getvalue())
+ assert envelope["schema_version"] == ENVELOPE_SCHEMA_VERSION
+ assert envelope["ok"] is False
+ assert envelope["error"]["message"] == "bad thing"
+ assert envelope["error"]["hint"] == "try again"
+
+ def test_json_error_envelope_preserves_action(self):
+ buf = io.StringIO()
+ with patch("sys.stdout", buf), pytest.raises(SystemExit) as exc_info:
+ output_error("bad thing", hint="try again", action="tasks.list", json_mode=True)
+ assert exc_info.value.code == 1
+ envelope = json.loads(buf.getvalue())
+ assert envelope["action"] == "tasks.list"
+
+ def test_human_output_unchanged(self, capsys):
+ output({"name": "test", "value": 42}, json_mode=False)
+ captured = capsys.readouterr()
+ assert "name" in captured.out
+ assert "42" in captured.out
+
+
+# ---------------------------------------------------------------------------
+# emit_tool_result tests
+# ---------------------------------------------------------------------------
+
+
+class TestEmitToolResult:
+ def test_preserves_mcp_result_shape(self):
+ mcp_result = {
+ "ok": True,
+ "action": "credential_list",
+ "data": [{"id": "cred_1"}],
+ "error": None,
+ "browser_context": {"session_id": "pbs_123"},
+ "artifacts": [{"type": "screenshot"}],
+ "timing_ms": 150,
+ }
+ buf = io.StringIO()
+ with patch("sys.stdout", buf):
+ emit_tool_result(mcp_result.copy(), json_output=True)
+ result = json.loads(buf.getvalue())
+ assert result["browser_context"] == {"session_id": "pbs_123"}
+ assert result["artifacts"] == [{"type": "screenshot"}]
+ assert result["timing_ms"] == 150
+ assert result["schema_version"] == ENVELOPE_SCHEMA_VERSION
+
+ def test_adds_defaults_to_minimal_result(self):
+ minimal = {"ok": True, "action": "test", "data": {}, "error": None}
+ buf = io.StringIO()
+ with patch("sys.stdout", buf):
+ emit_tool_result(minimal.copy(), json_output=True)
+ result = json.loads(buf.getvalue())
+ assert result["schema_version"] == ENVELOPE_SCHEMA_VERSION
+ assert result["warnings"] == []
+
+ def test_exits_on_not_ok(self):
+ error_result = {"ok": False, "action": "fail", "data": None, "error": {"message": "oops"}}
+ buf = io.StringIO()
+ with patch("sys.stdout", buf), pytest.raises(SystemExit) as exc_info:
+ emit_tool_result(error_result, json_output=True)
+ assert exc_info.value.code == 1
+
+
+# ---------------------------------------------------------------------------
+# run_tool tests
+# ---------------------------------------------------------------------------
+
+
+class TestRunTool:
+ def test_catches_exceptions(self):
+ async def failing():
+ raise RuntimeError("network error")
+
+ buf = io.StringIO()
+ with patch("sys.stdout", buf), pytest.raises(SystemExit):
+ run_tool(failing, json_output=True, hint_on_exception="check connection")
+ envelope = json.loads(buf.getvalue())
+ assert envelope["ok"] is False
+ assert "network error" in envelope["error"]["message"]
+
+ def test_catches_exceptions_with_action(self):
+ async def failing():
+ raise RuntimeError("network error")
+
+ buf = io.StringIO()
+ with patch("sys.stdout", buf), pytest.raises(SystemExit):
+ run_tool(failing, json_output=True, hint_on_exception="check connection", action="workflow.create")
+ envelope = json.loads(buf.getvalue())
+ assert envelope["ok"] is False
+ assert envelope["action"] == "workflow.create"
+
+ def test_passes_bad_parameter_through(self):
+ import typer
+
+ async def bad_param():
+ raise typer.BadParameter("invalid value")
+
+ with pytest.raises(typer.BadParameter):
+ run_tool(bad_param, json_output=False, hint_on_exception="")
+
+
+# ---------------------------------------------------------------------------
+# resolve_inline_or_file tests
+# ---------------------------------------------------------------------------
+
+
+class TestResolveInlineOrFile:
+ def test_returns_none_for_none(self):
+ assert resolve_inline_or_file(None, param_name="test") is None
+
+ def test_returns_literal_string(self):
+ assert resolve_inline_or_file("hello", param_name="test") == "hello"
+
+ def test_reads_file(self, tmp_path):
+ f = tmp_path / "data.txt"
+ f.write_text("file content")
+ assert resolve_inline_or_file(f"@{f}", param_name="test") == "file content"
+
+ def test_raises_on_missing_file(self):
+ import typer
+
+ with pytest.raises(typer.BadParameter):
+ resolve_inline_or_file("@/nonexistent/file.txt", param_name="test")
+
+ def test_raises_on_empty_path(self):
+ import typer
+
+ with pytest.raises(typer.BadParameter):
+ resolve_inline_or_file("@", param_name="test")
+
+
+# ---------------------------------------------------------------------------
+# TTY detection tests
+# ---------------------------------------------------------------------------
+
+
+class TestIsInteractive:
+ def test_returns_false_when_ci_true(self):
+ with patch.dict(os.environ, {"CI": "true"}, clear=False):
+ assert is_interactive() is False
+
+ def test_returns_false_when_ci_one(self):
+ with patch.dict(os.environ, {"CI": "1"}, clear=False):
+ assert is_interactive() is False
+
+ def test_ci_false_does_not_force_non_interactive(self):
+ env = {k: v for k, v in os.environ.items() if k not in ("CI", "SKYVERN_NON_INTERACTIVE")}
+ env["CI"] = "false"
+ with patch.dict(os.environ, env, clear=True), patch("sys.stdin") as mock_stdin:
+ mock_stdin.isatty.return_value = True
+ assert is_interactive() is True
+
+ def test_returns_false_when_non_interactive_set(self):
+ with patch.dict(os.environ, {"SKYVERN_NON_INTERACTIVE": "1"}, clear=False):
+ assert is_interactive() is False
+
+ def test_non_interactive_zero_does_not_force(self):
+ env = {k: v for k, v in os.environ.items() if k not in ("CI", "SKYVERN_NON_INTERACTIVE")}
+ env["SKYVERN_NON_INTERACTIVE"] = "0"
+ with patch.dict(os.environ, env, clear=True), patch("sys.stdin") as mock_stdin:
+ mock_stdin.isatty.return_value = True
+ assert is_interactive() is True
+
+ def test_returns_false_when_stdin_not_tty(self):
+ env = {k: v for k, v in os.environ.items() if k not in ("CI", "SKYVERN_NON_INTERACTIVE")}
+ with patch.dict(os.environ, env, clear=True), patch("sys.stdin") as mock_stdin:
+ mock_stdin.isatty.return_value = False
+ assert is_interactive() is False
+
+ def test_returns_true_when_tty(self):
+ env = {k: v for k, v in os.environ.items() if k not in ("CI", "SKYVERN_NON_INTERACTIVE")}
+ with patch.dict(os.environ, env, clear=True), patch("sys.stdin") as mock_stdin:
+ mock_stdin.isatty.return_value = True
+ assert is_interactive() is True
+
+
+class TestRequireInteractiveOrFlag:
+ def test_returns_flag_value_when_provided(self):
+ assert require_interactive_or_flag("mypass", flag_name="password", message="Need password.") == "mypass"
+
+ def test_returns_none_when_interactive(self):
+ with patch("skyvern.cli.commands._tty.is_interactive", return_value=True):
+ result = require_interactive_or_flag(None, flag_name="password", message="Need password.")
+ assert result is None
+
+ def test_exits_when_non_interactive_no_flag(self):
+ with patch("skyvern.cli.commands._tty.is_interactive", return_value=False), pytest.raises(SystemExit):
+ require_interactive_or_flag(None, flag_name="password", message="Need password.")
+
+ def test_json_mode_produces_json_error(self):
+ buf = io.StringIO()
+ with (
+ patch("skyvern.cli.commands._tty.is_interactive", return_value=False),
+ patch("sys.stdout", buf),
+ pytest.raises(SystemExit),
+ ):
+ require_interactive_or_flag(None, flag_name="password", message="Need password.", json_mode=True)
+ envelope = json.loads(buf.getvalue())
+ assert envelope["ok"] is False
+ assert "SKYVERN_CRED_PASSWORD" in envelope["error"]["hint"]
+
+ def test_json_mode_uses_custom_env_var_prefix(self):
+ buf = io.StringIO()
+ with (
+ patch("skyvern.cli.commands._tty.is_interactive", return_value=False),
+ patch("sys.stdout", buf),
+ pytest.raises(SystemExit),
+ ):
+ require_interactive_or_flag(
+ None,
+ flag_name="password",
+ message="Need password.",
+ json_mode=True,
+ env_var_prefix="SKYVERN_API_",
+ )
+ envelope = json.loads(buf.getvalue())
+ assert envelope["ok"] is False
+ assert "SKYVERN_API_PASSWORD" in envelope["error"]["hint"]
+
+
+# ---------------------------------------------------------------------------
+# Capabilities command tests
+# ---------------------------------------------------------------------------
+
+
+class TestCapabilities:
+ def test_depth_0_returns_names_only(self):
+ import typer
+
+ from skyvern.cli.commands import _walk_command_tree, cli_app
+
+ click_app = typer.main.get_command(cli_app)
+ tree = _walk_command_tree(click_app, max_depth=0)
+ assert tree["name"] == "skyvern"
+ assert "subcommand_names" in tree
+ assert "workflow" in tree["subcommand_names"]
+ assert "subcommands" not in tree # not expanded at depth 0
+
+ def test_depth_1_returns_subcommands(self):
+ import typer
+
+ from skyvern.cli.commands import _walk_command_tree, cli_app
+
+ click_app = typer.main.get_command(cli_app)
+ tree = _walk_command_tree(click_app, max_depth=1)
+ assert "subcommands" in tree
+ sub_names = [s["name"] for s in tree["subcommands"]]
+ assert "workflow" in sub_names
+ assert "credential" in sub_names
+ assert "capabilities" in sub_names
+
+ def test_hidden_commands_excluded(self):
+ import typer
+
+ from skyvern.cli.commands import _walk_command_tree, cli_app
+
+ click_app = typer.main.get_command(cli_app)
+ tree = _walk_command_tree(click_app, max_depth=1)
+ sub_names = [s["name"] for s in tree["subcommands"]]
+ assert "signup" not in sub_names
+
+ def test_deep_tree_has_options(self):
+ import typer
+
+ from skyvern.cli.commands import _walk_command_tree, cli_app
+
+ click_app = typer.main.get_command(cli_app)
+ tree = _walk_command_tree(click_app, max_depth=3)
+ workflow = next(s for s in tree["subcommands"] if s["name"] == "workflow")
+ assert "subcommands" in workflow
+ list_cmd = next(s for s in workflow["subcommands"] if s["name"].endswith("list"))
+ assert "options" in list_cmd
+ option_names = [o["name"] for o in list_cmd["options"]]
+ assert "json_output" in option_names or "json" in option_names
+
+ def test_group_command_includes_group_level_options(self):
+ import typer
+
+ from skyvern.cli.commands import _walk_command_tree, cli_app
+
+ click_app = typer.main.get_command(cli_app)
+ workflow = next(s for s in _walk_command_tree(click_app, max_depth=2)["subcommands"] if s["name"] == "workflow")
+ assert "options" in workflow
+ option_names = [o["name"] for o in workflow["options"]]
+ assert "api_key" in option_names
+
+ def test_subcommand_filter(self):
+ import typer
+
+ from skyvern.cli.commands import _walk_command_tree, cli_app
+
+ click_app = typer.main.get_command(cli_app)
+ import click
+
+ ctx = click.Context(click_app, info_name="skyvern")
+ workflow_cmd = click_app.get_command(ctx, "workflow")
+ tree = _walk_command_tree(workflow_cmd, prefix="workflow", max_depth=2)
+ assert tree["name"] == "workflow"
+ assert "subcommands" in tree
+
+ def test_cli_runner_json_output(self):
+ from typer.testing import CliRunner
+
+ from skyvern.cli.commands import cli_app
+
+ runner = CliRunner()
+ result = runner.invoke(cli_app, ["capabilities", "--json"])
+ assert result.exit_code == 0
+ parsed = json.loads(result.stdout)
+ assert parsed["ok"] is True
+ assert parsed["schema_version"] == "1.0"
+ assert "subcommands" in parsed["data"]
+
+ def test_cli_runner_no_json_output(self):
+ from typer.testing import CliRunner
+
+ from skyvern.cli.commands import cli_app
+
+ runner = CliRunner()
+ result = runner.invoke(cli_app, ["capabilities", "--no-json"])
+ assert result.exit_code == 0
+ assert "workflow" in result.stdout
+
+ def test_cli_runner_depth_parsing(self):
+ from typer.testing import CliRunner
+
+ from skyvern.cli.commands import cli_app
+
+ runner = CliRunner()
+ result = runner.invoke(cli_app, ["capabilities", "--depth", "0", "--json"])
+ assert result.exit_code == 0
+ parsed = json.loads(result.stdout)
+ assert "subcommand_names" in parsed["data"]
+ assert "subcommands" not in parsed["data"]
+
+
+# ---------------------------------------------------------------------------
+# Regression: existing tests should still work after DRY consolidation
+# ---------------------------------------------------------------------------
+
+
+class TestDryConsolidationRegression:
+ def test_credential_imports_shared_run_tool(self):
+ from skyvern.cli.credential import run_tool as imported_run_tool
+
+ assert imported_run_tool is run_tool
+
+ def test_workflow_imports_shared_functions(self):
+ from skyvern.cli.workflow import resolve_inline_or_file as wf_resolve
+ from skyvern.cli.workflow import run_tool as wf_run_tool
+
+ assert wf_run_tool is run_tool
+ assert wf_resolve is resolve_inline_or_file
+
+ def test_block_imports_shared_functions(self):
+ from skyvern.cli.block import resolve_inline_or_file as blk_resolve
+ from skyvern.cli.block import run_tool as blk_run_tool
+
+ assert blk_run_tool is run_tool
+ assert blk_resolve is resolve_inline_or_file
diff --git a/tests/unit/test_cli_commands.py b/tests/unit/test_cli_commands.py
index a3472252b..b05a6f419 100644
--- a/tests/unit/test_cli_commands.py
+++ b/tests/unit/test_cli_commands.py
@@ -325,7 +325,10 @@ class TestWorkflowCommands:
workflow_cmd.workflow_get(workflow_id="wpid_123", version=2, json_output=True)
parsed = json.loads(capsys.readouterr().out)
- assert parsed == expected
+ # emit_tool_result adds schema_version and warnings defaults to the output copy
+ assert parsed["ok"] is True
+ assert parsed["data"] == expected["data"]
+ assert parsed["schema_version"] == "1.0"
assert tool.await_args.kwargs == {"workflow_id": "wpid_123", "version": 2}
def test_workflow_create_reads_definition_from_file(
@@ -370,6 +373,42 @@ class TestWorkflowCommands:
assert parsed["ok"] is True
assert parsed["data"]["workflow_permanent_id"] == "wpid_new"
+ def test_workflow_create_preserves_empty_definition_file(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture,
+ ) -> None:
+ from skyvern.cli import workflow as workflow_cmd
+
+ definition_file = tmp_path / "workflow.json"
+ definition_file.write_text("")
+
+ tool = AsyncMock(
+ return_value={
+ "ok": True,
+ "action": "skyvern_workflow_create",
+ "browser_context": {"mode": "none", "session_id": None, "cdp_url": None},
+ "data": {"workflow_permanent_id": "wpid_empty"},
+ "artifacts": [],
+ "timing_ms": {},
+ "warnings": [],
+ "error": None,
+ }
+ )
+ monkeypatch.setattr(workflow_cmd, "tool_workflow_create", tool)
+
+ workflow_cmd.workflow_create(
+ definition=f"@{definition_file}",
+ definition_format="json",
+ folder_id=None,
+ json_output=True,
+ )
+
+ assert tool.await_args.kwargs["definition"] == ""
+ parsed = json.loads(capsys.readouterr().out)
+ assert parsed["ok"] is True
+
def test_workflow_run_reads_params_file_and_maps_options(
self,
tmp_path: Path,
@@ -497,6 +536,42 @@ class TestWorkflowCommands:
tool.assert_not_called()
+ def test_workflow_update_preserves_empty_definition_file(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture,
+ ) -> None:
+ from skyvern.cli import workflow as workflow_cmd
+
+ definition_file = tmp_path / "workflow.json"
+ definition_file.write_text("")
+
+ tool = AsyncMock(
+ return_value={
+ "ok": True,
+ "action": "skyvern_workflow_update",
+ "browser_context": {"mode": "none", "session_id": None, "cdp_url": None},
+ "data": {"workflow_permanent_id": "wpid_123"},
+ "artifacts": [],
+ "timing_ms": {},
+ "warnings": [],
+ "error": None,
+ }
+ )
+ monkeypatch.setattr(workflow_cmd, "tool_workflow_update", tool)
+
+ workflow_cmd.workflow_update(
+ workflow_id="wpid_123",
+ definition=f"@{definition_file}",
+ definition_format="json",
+ json_output=True,
+ )
+
+ assert tool.await_args.kwargs["definition"] == ""
+ parsed = json.loads(capsys.readouterr().out)
+ assert parsed["ok"] is True
+
# ---------------------------------------------------------------------------
# PR C parity command behavior
@@ -644,6 +719,87 @@ class TestBlockParityCommands:
assert parsed["ok"] is True
assert parsed["data"]["valid"] is True
+ def test_block_validate_preserves_empty_file(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
+ ) -> None:
+ from skyvern.cli import block as block_cmd
+
+ block_file = tmp_path / "block.json"
+ block_file.write_text("")
+
+ tool = AsyncMock(
+ return_value={
+ "ok": True,
+ "action": "skyvern_block_validate",
+ "browser_context": {"mode": "none", "session_id": None, "cdp_url": None},
+ "data": {"valid": False},
+ "artifacts": [],
+ "timing_ms": {},
+ "warnings": [],
+ "error": None,
+ }
+ )
+ monkeypatch.setattr(block_cmd, "tool_block_validate", tool)
+
+ block_cmd.block_validate(block_json=f"@{block_file}", json_output=True)
+
+ assert tool.await_args.kwargs["block_json"] == ""
+ parsed = json.loads(capsys.readouterr().out)
+ assert parsed["ok"] is True
+
+
+class TestTasksCommands:
+ def test_tasks_list_json_error_includes_action(
+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
+ ) -> None:
+ from skyvern.cli import tasks as tasks_cmd
+
+ monkeypatch.setattr(tasks_cmd, "_get_client", lambda _api_key=None: object())
+ monkeypatch.setattr(
+ tasks_cmd, "_list_workflow_tasks", lambda _client, _run_id: (_ for _ in ()).throw(RuntimeError("boom"))
+ )
+
+ with pytest.raises(SystemExit, match="1"):
+ tasks_cmd.list_tasks(
+ ctx=SimpleNamespace(obj={}),
+ workflow_run_id="wr_123",
+ json_output=True,
+ )
+
+ parsed = json.loads(capsys.readouterr().out)
+ assert parsed["ok"] is False
+ assert parsed["action"] == "tasks.list"
+
+
+class TestCredentialsCommands:
+ def test_add_credential_invalid_type_json_error_includes_action(self, capsys: pytest.CaptureFixture) -> None:
+ from skyvern.cli import credentials as credentials_cmd
+
+ ctx = SimpleNamespace(obj={})
+
+ with pytest.raises(SystemExit, match="1"):
+ credentials_cmd.add_credential(
+ ctx=ctx,
+ name="Bad",
+ credential_type="not-real",
+ username=None,
+ password=None,
+ totp=None,
+ card_number=None,
+ cvv=None,
+ exp_month=None,
+ exp_year=None,
+ card_brand=None,
+ holder_name=None,
+ secret_value=None,
+ secret_label=None,
+ json_output=True,
+ )
+
+ parsed = json.loads(capsys.readouterr().out)
+ assert parsed["ok"] is False
+ assert parsed["action"] == "credentials.add"
+
class TestBrowserPRCCommands:
def test_run_task_uses_resolved_connection(
@@ -742,20 +898,27 @@ class TestBrowserPRCCommands:
class TestParityErrorFormatting:
def test_credential_emit_tool_result_handles_none_message_and_hint(self, monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.cli import credential as credential_cmd
+ from skyvern.cli.commands import _output as output_mod
captured: dict[str, str | bool] = {}
- def _fake_output_error(message: str, *, hint: str = "", json_mode: bool = False, exit_code: int = 1) -> None:
+ def _fake_output_error(
+ message: str,
+ *,
+ hint: str = "",
+ action: str = "",
+ json_mode: bool = False,
+ exit_code: int = 1,
+ ) -> None:
captured["message"] = message
captured["hint"] = hint
captured["json_mode"] = json_mode
raise SystemExit(exit_code)
- monkeypatch.setattr(credential_cmd, "output_error", _fake_output_error)
+ monkeypatch.setattr(output_mod, "output_error", _fake_output_error)
with pytest.raises(SystemExit, match="1"):
- credential_cmd._emit_tool_result(
+ output_mod.emit_tool_result(
{"ok": False, "error": {"message": None, "hint": None}},
json_output=False,
)
@@ -763,20 +926,27 @@ class TestParityErrorFormatting:
assert captured == {"message": "Unknown error", "hint": "", "json_mode": False}
def test_block_emit_tool_result_handles_none_message_and_hint(self, monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.cli import block as block_cmd
+ from skyvern.cli.commands import _output as output_mod
captured: dict[str, str | bool] = {}
- def _fake_output_error(message: str, *, hint: str = "", json_mode: bool = False, exit_code: int = 1) -> None:
+ def _fake_output_error(
+ message: str,
+ *,
+ hint: str = "",
+ action: str = "",
+ json_mode: bool = False,
+ exit_code: int = 1,
+ ) -> None:
captured["message"] = message
captured["hint"] = hint
captured["json_mode"] = json_mode
raise SystemExit(exit_code)
- monkeypatch.setattr(block_cmd, "output_error", _fake_output_error)
+ monkeypatch.setattr(output_mod, "output_error", _fake_output_error)
with pytest.raises(SystemExit, match="1"):
- block_cmd._emit_tool_result(
+ output_mod.emit_tool_result(
{"ok": False, "error": {"message": None, "hint": None}},
json_output=False,
)
@@ -804,3 +974,21 @@ class TestParityErrorFormatting:
)
assert captured == {"message": "Unknown error", "hint": "", "json_mode": False}
+
+
+class TestStopCommands:
+ def test_stop_all_json_reports_failure_when_nothing_running(
+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
+ ) -> None:
+ from skyvern.cli import stop_commands as stop_cmd
+
+ monkeypatch.setattr(stop_cmd, "get_pids_on_port", lambda _port: [])
+ monkeypatch.setattr(stop_cmd, "kill_pids", lambda pids, service_name, quiet=False: False)
+
+ with pytest.raises(SystemExit, match="1"):
+ stop_cmd.stop_all(json_output=True)
+
+ parsed = json.loads(capsys.readouterr().out)
+ assert parsed["ok"] is False
+ assert parsed["action"] == "stop.all"
+ assert parsed["error"]["message"] == "No Skyvern services found running on ports 8000, 8080, or 9090."