Skip to content

The platform for continuously improving AI agents.

4.9 KB
Raw Blame
import json
from collections.abc import Callable
from copy import deepcopy
from functools import cache
from hashlib import sha256
from typing import ClassVar

from jsonschema import Draft202012Validator, FormatChecker
from openhands.sdk.conversation.state import ConversationState
from openhands.sdk.llm import TextContent
from openhands.sdk.tool import Action, Tool, ToolExecutor, register_tool
from openhands.sdk.tool.client_tool import ClientTool, ClientToolSpec
from openhands.sdk.tool.schema import Observation


class NativeObservation(Observation):
    result: dict | None = None

    @property
    def to_llm_content(self):
        return (
            [TextContent(text=json.dumps(self.result))]
            if self.result is not None
            else super().to_llm_content
        )


class NativeExecutor(ToolExecutor):
    def __init__(self, spec, dispatch):
        self.spec = spec
        self.dispatch = dispatch
        self.validator = Draft202012Validator(spec.parameters, format_checker=FormatChecker())

    def __call__(self, action, conversation=None):
        if conversation is None:
            raise RuntimeError("Native dispatch requires a persisted conversation")
        pending = ConversationState.get_unmatched_actions(conversation.state.active_branch())
        matches = [event for event in pending if event.action is action]
        if len(matches) != 1 or matches[0].tool_name != self.spec.name:
            raise RuntimeError("Native action identity is ambiguous")
        # SDK metadata is not part of the platform contract; a native summary field is.
        metadata = {"security_risk", "summary"} - set(self.spec.parameters.get("properties", {}))
        arguments = json.loads(matches[0].tool_call.arguments)
        arguments = {key: value for key, value in arguments.items() if key not in metadata}
        errors = list(self.validator.iter_errors(arguments))
        if errors:
            return NativeObservation(
                is_error=True,
                result={
                    "status": "rejected",
                    "error": "Arguments do not satisfy the tool contract",
                    "fields": [
                        {"path": list(error.absolute_path), "rule": error.validator}
                        for error in errors[:20]
                    ],
                },
            )
        result = self.dispatch(matches[0].id, self.spec.name, arguments)
        return NativeObservation(
            result=result,
            is_error=result.get("status") in {"rejected", "failed", "unknown", "denied"}
            or result.get("accepted") is False,
        )


class NativeTool(ClientTool):
    @property
    def name(self):
        return self.client_tool_name

    def native_schema(self, schema):
        for name in ("summary", "security_risk"):
            if name in self.input_schema.get("properties", {}):
                schema["properties"][name] = deepcopy(self.input_schema["properties"][name])
        return schema

    def to_openai_tool(self, add_security_risk_prediction=False, action_type=None):
        tool = super().to_openai_tool(add_security_risk_prediction, action_type)
        tool["function"]["parameters"] = self.native_schema(tool["function"]["parameters"])
        return tool

    def to_responses_tool(self, add_security_risk_prediction=False, action_type=None):
        tool = super().to_responses_tool(add_security_risk_prediction, action_type)
        tool["parameters"] = self.native_schema(tool["parameters"])
        return tool


class NativeFinishTool(NativeTool):
    ends_turn: ClassVar[bool] = True

    @property
    def name(self):
        return self.client_tool_name


@cache
def native_action(schema_json):
    schema = json.loads(schema_json)
    # The SDK's scalar conversion coerces integers and rejects valid required nulls.
    # Keep wire values intact; the original JSON Schema validates before dispatch.
    return Action.from_mcp_schema(
        model_name=f"OvermindAction_{sha256(schema_json.encode()).hexdigest()}",
        schema={
            "type": "object",
            "properties": {name: {} for name in schema.get("properties", {})},
            "required": schema.get("required", []),
        },
    )


def register_native_tools(
    definitions: list[dict], dispatch: Callable[[str, str, dict], dict]
) -> list[Tool]:
    tools = []
    for definition in definitions:
        spec = ClientToolSpec.model_validate(definition)
        kind = NativeFinishTool if spec.name == "finish" else NativeTool
        tool = kind(
            client_tool_name=spec.name,
            description=spec.description,
            input_schema=spec.parameters,
            action_type=native_action(json.dumps(spec.parameters, sort_keys=True)),
            executor=NativeExecutor(spec, dispatch),
            observation_type=NativeObservation,
            annotations=spec.annotations,
        )
        register_tool(spec.name, tool)
        tools.append(Tool(name=spec.name))
    return tools