sitcod3's picture
sync: backend/src -> Space (browser settings autosave + writable settings file)
6eb6c4e verified
Raw History Blame Contribute Delete
8.87 kB
"""The tool registry — single source of truth (plan Chapter 7 / Table 5).
For every tool it holds the name, description, argument model (whose JSON
schema is what the provider receives, in OpenAI function-calling JSON with
``additionalProperties: false``), the handler, and the risk level
(``read`` | ``act`` | ``consequential``).
Nothing else in the codebase may hand-write a tool schema or a dispatch
branch: ``build_tool_schemas`` (the litellm call site) and the executor both
read from :data:`REGISTRY`.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Generic, Literal, TypeVar
from pydantic import BaseModel
from . import handlers as h
from .schemas import (
BrowserCapabilitiesArgs,
ClickArgs,
ExtractTextArgs,
HttpFetchArgs,
NavigateArgs,
ObserveArgs,
PressKeyArgs,
ScreenshotArgs,
ScrollArgs,
SelectOptionArgs,
TabCloseArgs,
TabListArgs,
TabOpenArgs,
TabSelectArgs,
TypeArgs,
WaitForArgs,
WebSearchArgs,
)
Risk = Literal["read", "act", "consequential"]
# Each tool owns its argument model; the handler receives exactly that model.
ArgsT = TypeVar("ArgsT", bound=BaseModel)
Handler = Callable[[Any, ArgsT], Awaitable[dict[str, Any]]]
@dataclass(frozen=True)
class ToolSpec(Generic[ArgsT]):
name: str
description: str
model: type[ArgsT]
handler: Handler[ArgsT]
risk: Risk
# Browser tools require a live browser; http_fetch runs without one.
requires_browser: bool = True
# Argument field carrying a URL the executor policy must gate, if any.
url_field: str | None = None
# Table 5's browser tool set, in table order, plus the pre-existing web-search
# capability that Phase 2 preserved rather than dropped. The registry IS the
# tool set — nothing else in the codebase may add a tool schema or a dispatch
# branch. JavaScript evaluation is deliberately NOT a tool: it would bypass the
# executor's URL policy (plan Chapter 7.1).
TOOLS: tuple[ToolSpec[Any], ...] = (
ToolSpec(
name="browser_capabilities",
description=(
"Report the REAL browser name and version currently running. Always "
"call this before answering which browser you use. If the user asked "
"for a different engine, pass request_engine; a mismatch is refused "
"with needs_consent instead of silently substituting."
),
model=BrowserCapabilitiesArgs,
handler=h.browser_capabilities,
risk="read",
),
ToolSpec(
name="tab_open",
description=(
"Open a NEW tab, optionally at an absolute http(s) URL. Without a URL "
"it opens about:blank ONLY, never an external site. Returns the new "
"tab_id after confirming the tab in the browser's own tab list."
),
model=TabOpenArgs,
handler=h.tab_open,
risk="act",
url_field="url",
),
ToolSpec(
name="tab_list",
description="List open tabs with their tab_id, title and URL. The source of truth for tab ids.",
model=TabListArgs,
handler=h.tab_list,
risk="read",
),
ToolSpec(
name="tab_select",
description="Make a tab active. Takes a tab_id from tab_list.",
model=TabSelectArgs,
handler=h.tab_select,
risk="act",
),
ToolSpec(
name="tab_close",
description="Close a tab by tab_id (the active tab when omitted). Unknown ids are reported.",
model=TabCloseArgs,
handler=h.tab_close,
risk="act",
),
ToolSpec(
name="navigate",
description=(
"Go to an absolute http(s) URL in the active tab. The final URL and "
"title are read back and returned in verification before ok=true."
),
model=NavigateArgs,
handler=h.navigate,
risk="act",
url_field="url",
),
ToolSpec(
name="observe",
description=(
"Snapshot the active tab: url, title, capped visible text and the "
"interactive elements (index, role, accessible_name, state, visible, "
"enabled). Returns a snapshot_id you MUST pass to click/type/"
"select_option. Call again after every navigation or action."
),
model=ObserveArgs,
handler=h.observe,
risk="read",
),
ToolSpec(
name="click",
description=(
"Click an element by its index from the latest observe. Requires the "
"CURRENT snapshot_id; a stale one returns STALE_ELEMENT."
),
model=ClickArgs,
handler=h.click,
risk="act",
),
ToolSpec(
name="type",
description=(
"Type text into an element by its observe index. Requires the CURRENT "
"snapshot_id. submit=true presses Enter to submit — that counts as a "
"consequential action and is refused pending user approval."
),
model=TypeArgs,
handler=h.type_tool,
risk="act",
),
ToolSpec(
name="select_option",
description=(
"Select an option in a dropdown by its observe index. Requires the "
"CURRENT snapshot_id."
),
model=SelectOptionArgs,
handler=h.select_option,
risk="act",
),
ToolSpec(
name="scroll",
description="Scroll the active tab by pixels (positive down, negative up). Bounded amounts.",
model=ScrollArgs,
handler=h.scroll,
risk="act",
),
ToolSpec(
name="press_key",
description="Send a single key or key combo (e.g. Enter, Escape, Control+a).",
model=PressKeyArgs,
handler=h.press_key,
risk="act",
),
ToolSpec(
name="extract_text",
description=(
"Read trimmed text of the page or of a CSS selector. Output size is "
"capped."
),
model=ExtractTextArgs,
handler=h.extract_text,
risk="read",
),
ToolSpec(
name="screenshot",
description="Capture the active tab image; returns the saved PNG path. Feeds the UI and the model provider.",
model=ScreenshotArgs,
handler=h.screenshot,
risk="read",
),
ToolSpec(
name="wait_for",
description=(
"Wait for a named condition: 'selector' (a CSS selector appears), "
"'network_idle', or 'navigation'. timeout_ms is hard-capped at 15000."
),
model=WaitForArgs,
handler=h.wait_for_tool,
risk="read",
),
ToolSpec(
name="http_fetch",
description=(
"Fetch a public http(s) page with a plain server-side request, "
"OUTSIDE the browser. The result is marked source=http — it is never "
"a tab result. Use when you only need to read a page, not drive a tab."
),
model=HttpFetchArgs,
handler=h.http_fetch,
risk="act",
requires_browser=False,
url_field="url",
),
ToolSpec(
name="web_search",
description=(
"Search the web and return ranked results with their URLs. Runs "
"OUTSIDE the browser (source=search) — never a tab result. Use it "
"for current facts, news, prices and lookups."
),
model=WebSearchArgs,
handler=h.web_search,
risk="read",
requires_browser=False,
),
)
REGISTRY: dict[str, ToolSpec[Any]] = {spec.name: spec for spec in TOOLS}
def tool_schemas(registry: dict[str, ToolSpec[Any]] | None = None) -> list[dict[str, Any]]:
"""OpenAI function-calling schemas derived from the registry pydantic models.
This is the exact shape the provider receives through
``litellm.acompletion(tools=...)`` (see docs/AUDIT.md): ``{"type":
"function", "function": {name, description, parameters}}`` with
``parameters.additionalProperties`` false.
"""
schemas: list[dict[str, Any]] = []
for spec in (registry or REGISTRY).values():
parameters = spec.model.model_json_schema()
parameters.pop("title", None)
parameters.pop("$defs", None) # flat models only — no nested definitions
schemas.append({
"type": "function",
"function": {
"name": spec.name,
"description": spec.description,
"parameters": parameters,
},
})
return schemas