Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
30 changes: 30 additions & 0 deletions .github/workflows/precommit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# .github/workflows/precommit.yml
name: Pre-commit checks

on:
push:
branches: ["**"] # all branches

jobs:
pre-commit:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"

- name: Install uv
uses: astral-sh/setup-uv@v3

- name: Install dependencies
run: uv sync --frozen

- name: Run pre-commit (all files)
uses: pre-commit/action@v3.0.1
with:
extra_args: --all-files
28 changes: 28 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Run tests
on:
push:
branches: ["**"]

jobs:
tests:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"

- name: Install uv
uses: astral-sh/setup-uv@v3

- name: Install dependencies
run: uv sync --frozen --group dev

- name: Install project (editable)
run: uv pip install -e .

- name: Run pytest
run: uv run pytest -v tests/
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,11 @@ repos:
types: [python]
pass_filenames: false
always_run: true
- id: pyright
name: Type check with Pyright (strict)
entry: uv
args: [run, pyright]
language: system
types: [python]
pass_filenames: false
always_run: true
1 change: 1 addition & 0 deletions openhands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""OpenHands package."""
Empty file added openhands/core/__init__.py
Empty file.
83 changes: 83 additions & 0 deletions openhands/core/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# simple_logger.py
"""
Minimal logger setup that encourages per-module loggers.

Usage:
from openhands.core.logger import get_logger
logger = get_logger(__name__)
logger.info("Hello from this module!")
"""

import logging
import os
from logging.handlers import TimedRotatingFileHandler

# ========= ENV (loaded at import) =========
LEVEL_MAP = (
logging.getLevelNamesMapping()
if hasattr(logging, "getLevelNamesMapping")
else logging._nameToLevel
)

ENV_LOG_LEVEL_STR = os.getenv("LOG_LEVEL", "INFO").upper()
ENV_LOG_LEVEL = LEVEL_MAP.get(ENV_LOG_LEVEL_STR, logging.INFO)
ENV_LOG_TO_FILE = os.getenv("LOG_TO_FILE", "false").lower() in {"1", "true", "yes"}
ENV_LOG_DIR = os.getenv("LOG_DIR", "logs")
ENV_ROTATE_WHEN = os.getenv("LOG_ROTATE_WHEN", "midnight")
ENV_BACKUP_COUNT = int(os.getenv("LOG_BACKUP_COUNT", "7"))
ENV_FORMAT = os.getenv(
"LOG_FORMAT",
"%(asctime)s | %(levelname)s | %(name)s | %(pathname)s:%(lineno)d | %(message)s",
)
ENV_AUTO_CONFIG = os.getenv("LOG_AUTO_CONFIG", "true").lower() in {"1", "true", "yes"}


# ========= SETUP =========
def setup_logging(
level: int | None = None,
log_to_file: bool | None = None,
log_dir: str | None = None,
fmt: str | None = None,
when: str | None = None,
backup_count: int | None = None,
) -> None:
"""Configure the root logger. All child loggers inherit this setup."""
lvl = ENV_LOG_LEVEL if level is None else level
to_file = ENV_LOG_TO_FILE if log_to_file is None else log_to_file
directory = ENV_LOG_DIR if log_dir is None else log_dir
format_str = ENV_FORMAT if fmt is None else fmt
rotate_when = ENV_ROTATE_WHEN if when is None else when
keep = ENV_BACKUP_COUNT if backup_count is None else backup_count

root = logging.getLogger()
root.setLevel(lvl)
root.handlers = [] # reset

formatter = logging.Formatter(format_str)

ch = logging.StreamHandler()
ch.setLevel(lvl)
ch.setFormatter(formatter)
root.addHandler(ch)

if to_file:
os.makedirs(directory, exist_ok=True)
fh = TimedRotatingFileHandler(
os.path.join(directory, "app.log"),
when=rotate_when,
backupCount=keep,
encoding="utf-8",
)
fh.setLevel(lvl)
fh.setFormatter(formatter)
root.addHandler(fh)


def get_logger(name: str) -> logging.Logger:
"""Return a logger for the given module name."""
return logging.getLogger(name)


# Auto-configure if desired
if ENV_AUTO_CONFIG:
setup_logging()
1 change: 1 addition & 0 deletions openhands/core/runtime/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""OpenHands runtime package."""
File renamed without changes.
4 changes: 4 additions & 0 deletions openhands/core/runtime/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from typing import Literal

SECURITY_RISK_DESC = "The LLM's assessment of the safety risk of this action."
SECURITY_RISK_LITERAL = Literal["LOW", "MEDIUM", "HIGH"]
31 changes: 25 additions & 6 deletions openhands/runtime/tool.py → openhands/core/runtime/tool.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
from typing import Any, Callable
from pydantic import BaseModel
from pydantic import BaseModel, Field
from .schema import ActionBase, ObservationBase, Schema


class ToolAnnotations(BaseModel):
title: str | None = None
readOnlyHint: bool | None = None
destructiveHint: bool | None = None
idempotentHint: bool | None = None
openWorldHint: bool | None = None
"""Annotations to provide hints about the tool's behavior.

Based on Model Context Protocol (MCP) spec: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/caf3424488b10b4a7b1f8cb634244a450a1f4400/schema/2025-06-18/schema.ts#L838
"""

title: str | None = Field(
default=None, description="A human-readable title for the tool."
)
readOnlyHint: bool = Field(
default=False,
description="If true, the tool does not modify its environment. Default: false",
)
destructiveHint: bool = Field(
default=True,
description="If true, the tool may perform destructive updates to its environment. If false, the tool performs only additive updates. (This property is meaningful only when `readOnlyHint == false`) Default: true",
)
idempotentHint: bool = Field(
default=False,
description="If true, calling the tool repeatedly with the same arguments will have no additional effect on the its environment. (This property is meaningful only when `readOnlyHint == false`) Default: false",
)
openWorldHint: bool = Field(
default=True,
description="If true, this tool may interact with an 'open world' of external entities. If false, the tool's domain of interaction is closed. For example, the world of a web search tool is open, whereas that of a memory tool is not. Default: true",
)


class Tool:
Expand Down
1 change: 1 addition & 0 deletions openhands/core/runtime/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Runtime tools package."""
5 changes: 5 additions & 0 deletions openhands/core/runtime/tools/str_replace_editor/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from .definition import str_replace_editor_tool, StrReplaceEditorAction
from .impl import file_editor


__all__ = ["str_replace_editor_tool", "StrReplaceEditorAction", "file_editor"]
120 changes: 120 additions & 0 deletions openhands/core/runtime/tools/str_replace_editor/definition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""String replace editor tool implementation."""

from typing import Literal

from pydantic import Field

from openhands.core.runtime.tool import Tool, ToolAnnotations
from openhands.core.runtime.schema import ActionBase, ObservationBase
from openhands.core.runtime.security import SECURITY_RISK_DESC, SECURITY_RISK_LITERAL

CommandLiteral = Literal["view", "create", "str_replace", "insert", "undo_edit"]


class StrReplaceEditorAction(ActionBase):
"""Schema for string replace editor operations."""

command: CommandLiteral = Field(
description="The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`."
)
path: str = Field(
description="Absolute path to file or directory, e.g. `/workspace/file.py` or `/workspace`."
)
file_text: str | None = Field(
default=None,
description="Required parameter of `create` command, with the content of the file to be created.",
)
old_str: str | None = Field(
default=None,
description="Required parameter of `str_replace` command containing the string in `path` to replace.",
)
new_str: str | None = Field(
default=None,
description="Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.",
)
insert_line: int | None = Field(
default=None,
description="Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",
)
view_range: list[int] | None = Field(
default=None,
description="Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
)
security_risk: SECURITY_RISK_LITERAL = Field(description=SECURITY_RISK_DESC)


class StrReplaceEditorObservation(ObservationBase):
"""A ToolResult that can be rendered as a CLI output."""

output: str = Field(
default="", description="The output message from the tool for the LLM to see."
)
path: str | None = Field(default=None, description="The file path that was edited.")
prev_exist: bool = Field(
default=True,
description="Indicates if the file previously existed. If not, it was created.",
)
old_content: str | None = Field(
default=None, description="The content of the file before the edit."
)
new_content: str | None = Field(
default=None, description="The content of the file after the edit."
)
error: str | None = Field(default=None, description="Error message if any.")


Command = Literal[
"view",
"create",
"str_replace",
"insert",
"undo_edit",
]


TOOL_DESCRIPTION = """Custom editing tool for viewing, creating and editing files in plain-text format
* State is persistent across command calls and discussions with the user
* If `path` is a text file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep
* The following binary file extensions can be viewed in Markdown format: [".xlsx", ".pptx", ".wav", ".mp3", ".m4a", ".flac", ".pdf", ".docx"]. IT DOES NOT HANDLE IMAGES.
* The `create` command cannot be used if the specified `path` already exists as a file
* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`
* The `undo_edit` command will revert the last edit made to the file at `path`
* This tool can be used for creating and editing files in plain-text format.


Before using this tool:
1. Use the view tool to understand the file's contents and context
2. Verify the directory path is correct (only applicable when creating new files):
- Use the view tool to verify the parent directory exists and is the correct location

When making edits:
- Ensure the edit results in idiomatic, correct code
- Do not leave the code in a broken state
- Always use absolute file paths (starting with /)

CRITICAL REQUIREMENTS FOR USING THIS TOOL:

1. EXACT MATCHING: The `old_str` parameter must match EXACTLY one or more consecutive lines from the file, including all whitespace and indentation. The tool will fail if `old_str` matches multiple locations or doesn't match exactly with the file content.

2. UNIQUENESS: The `old_str` must uniquely identify a single instance in the file:
- Include sufficient context before and after the change point (3-5 lines recommended)
- If not unique, the replacement will not be performed

3. REPLACEMENT: The `new_str` parameter should contain the edited lines that replace the `old_str`. Both strings must be different.

Remember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.
"""


str_replace_editor_tool = Tool(
name="str_replace_editor",
input_schema=StrReplaceEditorAction,
description=TOOL_DESCRIPTION,
annotations=ToolAnnotations(
title="str_replace_editor",
readOnlyHint=False,
destructiveHint=True,
idempotentHint=False,
openWorldHint=False,
),
)
Loading