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
128 changes: 128 additions & 0 deletions .github/workflows/python.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# CI for bashkit Python bindings
# Builds the native extension via maturin and runs pytest on each PR.
# Complements publish-python.yml (release-only) with per-PR validation.

name: Python

on:
push:
branches: [main]
paths:
- "crates/bashkit-python/**"
- "crates/bashkit/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/python.yml"
pull_request:
branches: [main]
paths:
- "crates/bashkit-python/**"
- "crates/bashkit/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/python.yml"
workflow_call:

permissions:
contents: read

env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1

jobs:
lint:
name: Lint & Format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6

- uses: astral-sh/setup-uv@v7

- name: Ruff check
run: uvx ruff check crates/bashkit-python

- name: Ruff format
run: uvx ruff format --check crates/bashkit-python

test:
name: Test (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.9", "3.12", "3.13"]
steps:
- uses: actions/checkout@v6

- uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}

- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable

- uses: Swatinem/rust-cache@v2

- name: Build wheel
uses: PyO3/maturin-action@v1
with:
command: build
args: --release --out dist -i python${{ matrix.python-version }}
rust-toolchain: stable
working-directory: crates/bashkit-python

- name: Install wheel and test dependencies
run: |
pip install bashkit --no-index --find-links crates/bashkit-python/dist --force-reinstall
pip install pytest pytest-asyncio

- name: Run tests
working-directory: crates/bashkit-python
run: pytest tests/ -v

# Verify wheel builds and passes twine check
build-wheel:
name: Build wheel
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6

- uses: actions/setup-python@v6
with:
python-version: "3.12"

- name: Build wheel
uses: PyO3/maturin-action@v1
with:
command: build
args: --release --out dist
rust-toolchain: stable
working-directory: crates/bashkit-python

- name: Verify wheel metadata
run: |
pip install twine
twine check crates/bashkit-python/dist/*

- uses: actions/upload-artifact@v6
with:
name: python-wheel
path: crates/bashkit-python/dist
retention-days: 5

# Gate job for branch protection
python-check:
name: Python Check
if: always()
needs: [lint, test, build-wheel]
runs-on: ubuntu-latest
steps:
- name: Verify all jobs passed
run: |
if [[ "${{ needs.lint.result }}" != "success" ]] || \
[[ "${{ needs.test.result }}" != "success" ]] || \
[[ "${{ needs.build-wheel.result }}" != "success" ]]; then
echo "One or more Python CI jobs failed"
exit 1
fi
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ just pre-pr # Pre-PR checks
- `cargo fmt` and `cargo clippy -- -D warnings`
- License checks: `cargo deny check` (see `deny.toml`)

### Python

- Python bindings in `crates/bashkit-python/`
- Linter/formatter: `ruff` (config in `pyproject.toml`)
- `ruff check crates/bashkit-python` and `ruff format --check crates/bashkit-python`
- Tests: `pytest crates/bashkit-python/tests/ -v` (requires `maturin develop` first)
- CI: `.github/workflows/python.yml` (lint, test on 3.9/3.12/3.13, build wheel)

### Pre-PR Checklist

1. `just pre-pr` (runs 2-4 automatically)
Expand All @@ -100,6 +108,7 @@ just pre-pr # Pre-PR checks
11. Resolve all PR comments
12. `cargo bench --bench parallel_execution` if touching Arc/async/Interpreter/builtins (see `specs/007-parallel-execution.md`)
13. `just bench` if changes might impact performance (interpreter, builtins, tools)
14. `ruff check crates/bashkit-python && ruff format --check crates/bashkit-python` if touching Python code

### CI

Expand Down
12 changes: 5 additions & 7 deletions crates/bashkit-python/bashkit/_bashkit.pyi
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
"""Type stubs for bashkit_py native module."""

from typing import Optional

class ExecResult:
"""Result from executing bash commands."""

stdout: str
stderr: str
exit_code: int
error: Optional[str]
error: str | None
success: bool

def to_dict(self) -> dict[str, any]: ...
Expand All @@ -33,10 +31,10 @@ class BashTool:

def __init__(
self,
username: Optional[str] = None,
hostname: Optional[str] = None,
max_commands: Optional[int] = None,
max_loop_iterations: Optional[int] = None,
username: str | None = None,
hostname: str | None = None,
max_commands: int | None = None,
max_loop_iterations: int | None = None,
) -> None:
"""Create a new BashTool instance.

Expand Down
80 changes: 50 additions & 30 deletions crates/bashkit-python/bashkit/deepagents.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import uuid
from datetime import datetime, timezone
from typing import Optional, TYPE_CHECKING
from typing import TYPE_CHECKING

from bashkit import BashTool as NativeBashTool

Expand All @@ -25,14 +25,14 @@
# Check for deepagents availability
try:
from deepagents.backends.protocol import (
SandboxBackendProtocol,
EditResult,
ExecuteResponse,
FileDownloadResponse,
FileInfo,
FileUploadResponse,
GrepMatch,
EditResult,
SandboxBackendProtocol,
WriteResult,
FileDownloadResponse,
FileUploadResponse,
)
from langchain.agents.middleware.types import AgentMiddleware
from langchain_core.tools import tool as langchain_tool
Expand Down Expand Up @@ -84,11 +84,11 @@ class BashkitMiddleware(AgentMiddleware):

def __init__(
self,
bash_tool: Optional[NativeBashTool] = None,
username: Optional[str] = None,
hostname: Optional[str] = None,
max_commands: Optional[int] = None,
max_loop_iterations: Optional[int] = None,
bash_tool: NativeBashTool | None = None,
username: str | None = None,
hostname: str | None = None,
max_commands: int | None = None,
max_loop_iterations: int | None = None,
):
"""Initialize middleware.

Expand Down Expand Up @@ -128,7 +128,6 @@ def reset(self) -> None:
if self._owns_bash:
self._bash.reset()


class BashkitBackend(SandboxBackendProtocol):
"""Backend implementing SandboxBackendProtocol with Bashkit VFS.

Expand All @@ -147,10 +146,10 @@ class BashkitBackend(SandboxBackendProtocol):

def __init__(
self,
username: Optional[str] = None,
hostname: Optional[str] = None,
max_commands: Optional[int] = None,
max_loop_iterations: Optional[int] = None,
username: str | None = None,
hostname: str | None = None,
max_commands: int | None = None,
max_loop_iterations: int | None = None,
):
self._bash = NativeBashTool(
username=username,
Expand Down Expand Up @@ -189,7 +188,7 @@ def read(self, file_path: str, offset: int = 0, limit: int = 2000) -> str:
if result.exit_code != 0:
return f"Error: {result.stderr or 'File not found'}"
lines = result.stdout.splitlines()
selected = lines[offset:offset + limit]
selected = lines[offset : offset + limit]
return "\n".join(f"{i:6d}\t{line}" for i, line in enumerate(selected, start=offset + 1))

async def aread(self, file_path: str, offset: int = 0, limit: int = 2000) -> str:
Expand All @@ -213,11 +212,16 @@ def edit(self, file_path: str, old_string: str, new_string: str, replace_all: bo
return EditResult(error="old_string not found")
if count > 1 and not replace_all:
return EditResult(error=f"Found {count} times. Use replace_all=True")
new_content = content.replace(old_string, new_string) if replace_all else content.replace(old_string, new_string, 1)
if replace_all:
new_content = content.replace(old_string, new_string)
else:
new_content = content.replace(old_string, new_string, 1)
wr = self.write(file_path, new_content)
return EditResult(error=wr.error, path=file_path)

async def aedit(self, file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult:
async def aedit(
self, file_path: str, old_string: str, new_string: str, replace_all: bool = False
) -> EditResult:
return self.edit(file_path, old_string, new_string, replace_all)

# === File Discovery ===
Expand All @@ -234,12 +238,16 @@ def ls_info(self, path: str) -> list[FileInfo]:
name = " ".join(parts[8:])
if name in (".", ".."):
continue
files.append(FileInfo(
path=f"{path.rstrip('/')}/{name}", name=name,
is_dir=parts[0].startswith("d"),
size=int(parts[4]) if parts[4].isdigit() else 0,
created_at=_now_iso(), modified_at=_now_iso(),
))
files.append(
FileInfo(
path=f"{path.rstrip('/')}/{name}",
name=name,
is_dir=parts[0].startswith("d"),
size=int(parts[4]) if parts[4].isdigit() else 0,
created_at=_now_iso(),
modified_at=_now_iso(),
)
)
return files

async def als_info(self, path: str) -> list[FileInfo]:
Expand All @@ -251,8 +259,16 @@ def glob_info(self, pattern: str, path: str = "/") -> list[FileInfo]:
if result.exit_code != 0:
return []
return [
FileInfo(path=p.strip(), name=p.strip().split("/")[-1], is_dir=False, size=0, created_at=_now_iso(), modified_at=_now_iso())
for p in result.stdout.splitlines() if p.strip()
FileInfo(
path=p.strip(),
name=p.strip().split("/")[-1],
is_dir=False,
size=0,
created_at=_now_iso(),
modified_at=_now_iso(),
)
for p in result.stdout.splitlines()
if p.strip()
]

async def aglob_info(self, pattern: str, path: str = "/") -> list[FileInfo]:
Expand All @@ -273,7 +289,9 @@ def grep_raw(self, pattern: str, path: str | None = None, glob: str | None = Non
continue
return matches

async def agrep_raw(self, pattern: str, path: str | None = None, glob: str | None = None) -> list[GrepMatch] | str:
async def agrep_raw(
self, pattern: str, path: str | None = None, glob: str | None = None
) -> list[GrepMatch] | str:
return self.grep_raw(pattern, path, glob)

# === File Transfer ===
Expand All @@ -285,7 +303,9 @@ def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
if result.exit_code == 0:
responses.append(FileDownloadResponse(path=p, content=result.stdout.encode(), error=None))
else:
responses.append(FileDownloadResponse(path=p, content=None, error=result.stderr or "File not found"))
responses.append(
FileDownloadResponse(path=p, content=None, error=result.stderr or "File not found")
)
return responses

async def adownload_files(self, paths: list[str]) -> list[FileDownloadResponse]:
Expand Down Expand Up @@ -316,14 +336,14 @@ def reset(self) -> None:
self._bash.reset()


def create_bash_middleware(**kwargs) -> "BashkitMiddleware":
def create_bash_middleware(**kwargs) -> BashkitMiddleware:
"""Create BashkitMiddleware for Deep Agents."""
if not DEEPAGENTS_AVAILABLE:
raise ImportError("deepagents required. Install: pip install 'bashkit[deepagents]'")
return BashkitMiddleware(**kwargs)


def create_bashkit_backend(**kwargs) -> "BashkitBackend":
def create_bashkit_backend(**kwargs) -> BashkitBackend:
"""Create BashkitBackend for Deep Agents."""
if not DEEPAGENTS_AVAILABLE:
raise ImportError("deepagents required. Install: pip install 'bashkit[deepagents]'")
Expand Down
Loading
Loading