mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-09 23:53:15 +08:00
重构主控编排与运行时预热链路,统一工作区提示词/专家调度协议并补齐 wiki 记忆注入与写回闭环。
同时收敛启动与运维脚本默认行为(含 wiki worker)、更新 Admin 可观测性与相关测试,降低首轮时延并提高运行稳定性。 Made-with: Cursor
This commit is contained in:
parent
4a23b715a2
commit
dbbe3add6a
14438 changed files with 2693620 additions and 2546 deletions
|
|
@ -9,21 +9,4 @@ def system_info_tool() -> ToolSpec:
|
|||
return factory()
|
||||
|
||||
|
||||
def geo_info_tool() -> ToolSpec:
|
||||
from .geo_info import geo_info_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def weather_tool() -> ToolSpec:
|
||||
from .weather import weather_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def web_search_tool() -> ToolSpec:
|
||||
from .web_search import web_search_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
__all__ = ["system_info_tool", "geo_info_tool", "weather_tool", "web_search_tool"]
|
||||
__all__ = ["system_info_tool"]
|
||||
|
|
|
|||
|
|
@ -1,66 +0,0 @@
|
|||
"""系统工具共用 HTTP 辅助函数(Nominatim 逆地理编码与 ipapi.co)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
NOMINATIM_REQUEST_HEADERS = {"User-Agent": "OpsAssistant/1.0 (internal tool)"}
|
||||
DEFAULT_HTTP_TIMEOUT = 10.0
|
||||
|
||||
|
||||
def nominatim_reverse(
|
||||
client: httpx.Client,
|
||||
lat: float,
|
||||
lon: float,
|
||||
*,
|
||||
accept_language: str = "en",
|
||||
) -> dict[str, Any]:
|
||||
"""调用 Nominatim 逆地理编码并返回解析后的 JSON,失败时返回空字典。"""
|
||||
try:
|
||||
r = client.get(
|
||||
"https://nominatim.openstreetmap.org/reverse",
|
||||
params={"lat": lat, "lon": lon, "format": "json", "accept-language": accept_language},
|
||||
headers=NOMINATIM_REQUEST_HEADERS,
|
||||
)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def ipapi_approximate_location(client: httpx.Client) -> dict[str, Any] | None:
|
||||
try:
|
||||
ip_resp = client.get("https://ipapi.co/json/")
|
||||
ip_resp.raise_for_status()
|
||||
ip_data = ip_resp.json()
|
||||
lat = ip_data.get("latitude")
|
||||
lon = ip_data.get("longitude")
|
||||
if lat is None or lon is None:
|
||||
return None
|
||||
lat_f = float(lat)
|
||||
lon_f = float(lon)
|
||||
geo = nominatim_reverse(client, lat_f, lon_f)
|
||||
display_name = geo.get("display_name") if geo else None
|
||||
if not display_name or not str(display_name).strip():
|
||||
parts = [ip_data.get("city"), ip_data.get("region"), ip_data.get("country_name")]
|
||||
display_name = ", ".join(str(p) for p in parts if p)
|
||||
if not display_name:
|
||||
display_name = f"Approximate ({lat_f:.4f}, {lon_f:.4f})"
|
||||
return {
|
||||
"latitude": lat_f,
|
||||
"longitude": lon_f,
|
||||
"display_name": str(display_name).strip(),
|
||||
"ip": ip_data.get("ip"),
|
||||
"city": ip_data.get("city"),
|
||||
"region": ip_data.get("region"),
|
||||
"country_name": ip_data.get("country_name"),
|
||||
"nominatim": geo,
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
__all__ = ["DEFAULT_HTTP_TIMEOUT", "NOMINATIM_REQUEST_HEADERS", "ipapi_approximate_location", "nominatim_reverse"]
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
from .geo_http import DEFAULT_HTTP_TIMEOUT, ipapi_approximate_location, nominatim_reverse
|
||||
|
||||
|
||||
def _reverse_geocode(lat: float, lon: float) -> dict[str, Any]:
|
||||
with httpx.Client(timeout=DEFAULT_HTTP_TIMEOUT) as client:
|
||||
return nominatim_reverse(client, lat, lon)
|
||||
|
||||
|
||||
def geo_info_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
lat = args.get("latitude")
|
||||
lon = args.get("longitude")
|
||||
if lat is None or lon is None:
|
||||
return {"ok": False, "error": "latitude and longitude are required"}
|
||||
try:
|
||||
lat_f = float(lat)
|
||||
lon_f = float(lon)
|
||||
except (TypeError, ValueError):
|
||||
return {"ok": False, "error": "latitude and longitude must be numbers"}
|
||||
data = _reverse_geocode(lat_f, lon_f)
|
||||
if not data or "error" in data:
|
||||
error_msg = data.get("error") if data else "Unknown error"
|
||||
return {"ok": False, "error": error_msg}
|
||||
return {"ok": True, "address": data.get("display_name"), "details": data.get("address"), "latitude": lat_f, "longitude": lon_f}
|
||||
|
||||
return ToolSpec(
|
||||
name="reverse_geocode",
|
||||
description="Reverse geocode: get a human-readable address from latitude and longitude.",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"latitude": {"type": "number", "description": "Latitude in decimal degrees."},
|
||||
"longitude": {"type": "number", "description": "Longitude in decimal degrees."},
|
||||
},
|
||||
"required": ["latitude", "longitude"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
def system_location_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
try:
|
||||
with httpx.Client(timeout=DEFAULT_HTTP_TIMEOUT) as client:
|
||||
loc = ipapi_approximate_location(client)
|
||||
if not loc:
|
||||
return {"ok": False, "error": "Could not detect coordinates for this network"}
|
||||
geo = loc.get("nominatim") or {}
|
||||
return {
|
||||
"ok": True,
|
||||
"latitude": loc["latitude"],
|
||||
"longitude": loc["longitude"],
|
||||
"address": loc["display_name"],
|
||||
"ip": loc.get("ip"),
|
||||
"city": loc.get("city"),
|
||||
"region": loc.get("region"),
|
||||
"country": loc.get("country_name"),
|
||||
"details": geo.get("address") if geo else None,
|
||||
}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"Failed to detect location: {e}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="get_system_location",
|
||||
description="Detect this machine's public IP and approximate location (coordinates and address).",
|
||||
parameters={"type": "object", "properties": {}, "additionalProperties": False},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["geo_info_tool", "system_location_tool"]
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
from .geo_http import NOMINATIM_REQUEST_HEADERS, ipapi_approximate_location, nominatim_reverse
|
||||
|
||||
_WEATHER_CODES: dict[int, str] = {
|
||||
0: "Clear sky",
|
||||
1: "Mainly clear",
|
||||
2: "Partly cloudy",
|
||||
3: "Overcast",
|
||||
45: "Fog",
|
||||
48: "Depositing rime fog",
|
||||
51: "Light drizzle",
|
||||
53: "Moderate drizzle",
|
||||
55: "Dense drizzle",
|
||||
61: "Slight rain",
|
||||
63: "Moderate rain",
|
||||
65: "Heavy rain",
|
||||
71: "Slight snow",
|
||||
73: "Moderate snow",
|
||||
75: "Heavy snow",
|
||||
95: "Thunderstorm",
|
||||
}
|
||||
_LOCAL_WEATHER_ALIASES: frozenset[str] = frozenset(
|
||||
{"here", "local", "locally", "nearby", "current", "current location", "my location", "this location", "local area", "unknown", "anywhere", "本地", "当地", "这里", "附近", "当前位置", "当前", "本地天气"}
|
||||
)
|
||||
|
||||
|
||||
def _normalize_city_token(s: str) -> str:
|
||||
t = unicodedata.normalize("NFKC", (s or "").strip()).casefold()
|
||||
t = re.sub(r"\s+", " ", t)
|
||||
return t
|
||||
|
||||
|
||||
def _is_local_weather_alias(city: str) -> bool:
|
||||
return _normalize_city_token(city) in _LOCAL_WEATHER_ALIASES
|
||||
|
||||
|
||||
def _coerce_city(raw: Any) -> str | None:
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, str):
|
||||
raw = str(raw)
|
||||
s = raw.strip()
|
||||
return s if s else None
|
||||
|
||||
|
||||
def weather_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
city = _coerce_city(args.get("city"))
|
||||
lat = args.get("latitude")
|
||||
lon = args.get("longitude")
|
||||
if (lat is None) ^ (lon is None):
|
||||
return {"ok": False, "error": "Provide both latitude and longitude, or neither (for local-IP weather), or use city alone."}
|
||||
has_coords = lat is not None and lon is not None
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=12.0) as client:
|
||||
location_basis: str
|
||||
resolved_city: str
|
||||
lat_f: float
|
||||
lon_f: float
|
||||
extra: dict[str, Any] = {}
|
||||
if has_coords:
|
||||
lat_f = float(lat)
|
||||
lon_f = float(lon)
|
||||
location_basis = "explicit_coordinates"
|
||||
rev = nominatim_reverse(client, lat_f, lon_f)
|
||||
dn = (rev.get("display_name") or "").strip() if rev else ""
|
||||
resolved_city = dn or f"Coordinates ({lat_f}, {lon_f})"
|
||||
elif city and not _is_local_weather_alias(city):
|
||||
geo_resp = client.get(
|
||||
"https://nominatim.openstreetmap.org/search",
|
||||
params={"q": city, "format": "json", "limit": 1},
|
||||
headers=NOMINATIM_REQUEST_HEADERS,
|
||||
)
|
||||
geo_resp.raise_for_status()
|
||||
geo_data = geo_resp.json()
|
||||
if not geo_data:
|
||||
return {"ok": False, "error": f"City not found: {city}"}
|
||||
first = geo_data[0]
|
||||
lat_f = float(first["lat"])
|
||||
lon_f = float(first["lon"])
|
||||
resolved_city = first.get("display_name", city)
|
||||
location_basis = "explicit_place"
|
||||
else:
|
||||
ip_loc = ipapi_approximate_location(client)
|
||||
if not ip_loc:
|
||||
return {"ok": False, "error": "Could not resolve local weather: failed to detect location from this network. Pass a concrete city/region (e.g. 北京) or both latitude and longitude."}
|
||||
lat_f = ip_loc["latitude"]
|
||||
lon_f = ip_loc["longitude"]
|
||||
resolved_city = ip_loc["display_name"]
|
||||
location_basis = "local_network_ip"
|
||||
if ip_loc.get("ip") is not None:
|
||||
extra["approximate_ip"] = ip_loc["ip"]
|
||||
|
||||
weather_url = "https://api.open-meteo.com/v1/forecast"
|
||||
weather_params = {
|
||||
"latitude": lat_f,
|
||||
"longitude": lon_f,
|
||||
"current": ["temperature_2m", "relative_humidity_2m", "apparent_temperature", "is_day", "weather_code", "wind_speed_10m"],
|
||||
"timezone": "auto",
|
||||
}
|
||||
w_resp = client.get(weather_url, params=weather_params)
|
||||
w_resp.raise_for_status()
|
||||
current = w_resp.json().get("current", {})
|
||||
code = int(current.get("weather_code") or 0)
|
||||
condition = _WEATHER_CODES.get(code, "Unknown")
|
||||
out: dict[str, Any] = {
|
||||
"ok": True,
|
||||
"city": resolved_city,
|
||||
"temperature": f"{current.get('temperature_2m')}°C",
|
||||
"feels_like": f"{current.get('apparent_temperature')}°C",
|
||||
"condition": condition,
|
||||
"humidity": f"{current.get('relative_humidity_2m')}%",
|
||||
"wind_speed": f"{current.get('wind_speed_10m')} km/h",
|
||||
"is_day": bool(current.get("is_day")),
|
||||
"latitude": lat_f,
|
||||
"longitude": lon_f,
|
||||
"location_basis": location_basis,
|
||||
}
|
||||
out.update(extra)
|
||||
if location_basis == "local_network_ip":
|
||||
out["disclaimer"] = "Weather is for the approximate location of this deployment's public IP (VPN/proxy/corporate NAT may differ from the end user's actual place)."
|
||||
return out
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"Failed to fetch weather: {e}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="get_weather",
|
||||
description="Get current weather (Open-Meteo, no API key). Default: omit city and coordinates — uses this server's outbound public IP for approximate local weather. Override: pass a concrete placename in `city` or both `latitude` and `longitude`.",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": {"type": "string", "description": "Optional place name."},
|
||||
"latitude": {"type": "number", "description": "Optional. Must pair with longitude."},
|
||||
"longitude": {"type": "number", "description": "Optional. Must pair with latitude."},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["weather_tool"]
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
"""基于 DuckDuckGo(ddgs 包)的公网搜索工具(无需 API Key)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
_MAX_SNIPPET = 800
|
||||
_DDGS_TIMEOUT = 15
|
||||
|
||||
|
||||
def _utc_now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _truncate(s: str, limit: int) -> str:
|
||||
t = (s or "").strip()
|
||||
if len(t) <= limit:
|
||||
return t
|
||||
return t[: limit - 3] + "..."
|
||||
|
||||
|
||||
def _published_display_and_sort_key(raw: Any) -> tuple[str | None, float]:
|
||||
if raw is None:
|
||||
return None, float("-inf")
|
||||
if isinstance(raw, (int, float)):
|
||||
try:
|
||||
ts = float(raw)
|
||||
dt = datetime.fromtimestamp(ts, timezone.utc)
|
||||
return dt.isoformat(), ts
|
||||
except (OSError, OverflowError, ValueError):
|
||||
return str(raw), float("-inf")
|
||||
s = str(raw).strip()
|
||||
if not s:
|
||||
return None, float("-inf")
|
||||
try:
|
||||
s2 = s[:-1] + "+00:00" if s.endswith("Z") else s
|
||||
dt = datetime.fromisoformat(s2)
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
iso = dt.astimezone(timezone.utc).isoformat()
|
||||
return iso, dt.timestamp()
|
||||
except Exception:
|
||||
return s, float("-inf")
|
||||
|
||||
|
||||
def web_search_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
q = str(args.get("query") or "").strip()
|
||||
if not q:
|
||||
return {"ok": False, "error": "query is required"}
|
||||
raw_max = args.get("max_results")
|
||||
try:
|
||||
max_n = int(raw_max) if raw_max is not None else 8
|
||||
except (TypeError, ValueError):
|
||||
max_n = 8
|
||||
max_n = max(1, min(15, max_n))
|
||||
stype = str(args.get("search_type") or "web").strip().lower()
|
||||
if stype not in ("web", "news"):
|
||||
return {"ok": False, "error": "search_type must be 'web' or 'news'"}
|
||||
timelimit = args.get("time_range")
|
||||
if timelimit is not None and timelimit != "":
|
||||
tl = str(timelimit).strip().lower()
|
||||
allowed = {"d", "w", "m", "y"}
|
||||
if tl not in allowed:
|
||||
return {"ok": False, "error": f"time_range must be one of {sorted(allowed)} or omitted"}
|
||||
timelimit = tl
|
||||
else:
|
||||
timelimit = None
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
except ImportError:
|
||||
return {"ok": False, "error": "Package `ddgs` is not installed. Run: pip install ddgs"}
|
||||
|
||||
retrieved_at = _utc_now_iso()
|
||||
try:
|
||||
rows: list[dict[str, Any]] = []
|
||||
with DDGS(timeout=_DDGS_TIMEOUT) as ddgs:
|
||||
if stype == "web":
|
||||
for r in ddgs.text(q, max_results=max_n, timelimit=timelimit):
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
title = _truncate(str(r.get("title") or ""), 300)
|
||||
url = str(r.get("href") or r.get("url") or "").strip()
|
||||
body = _truncate(str(r.get("body") or ""), _MAX_SNIPPET)
|
||||
if title or url or body:
|
||||
rows.append({"title": title, "url": url, "snippet": body, "published_time": None})
|
||||
sort_mode = "relevance"
|
||||
note = "Web index does not provide reliable per-result publication times; order follows search relevance. Use search_type=news for time-sorted news."
|
||||
else:
|
||||
decorated: list[tuple[float, dict[str, Any]]] = []
|
||||
for r in ddgs.news(q, max_results=max_n, timelimit=timelimit):
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
title = _truncate(str(r.get("title") or ""), 300)
|
||||
url = str(r.get("url") or r.get("href") or "").strip()
|
||||
body = _truncate(str(r.get("body") or ""), _MAX_SNIPPET)
|
||||
pub, sk = _published_display_and_sort_key(r.get("date"))
|
||||
src = str(r.get("source") or "").strip()
|
||||
item = {"title": title, "url": url, "snippet": body, "published_time": pub}
|
||||
if src:
|
||||
item["source"] = src
|
||||
if title or url or body:
|
||||
decorated.append((sk, item))
|
||||
decorated.sort(key=lambda x: x[0], reverse=True)
|
||||
rows = [x[1] for x in decorated]
|
||||
sort_mode = "published_time_desc"
|
||||
note = "News results sorted by published_time (newest first). Snippets are from third-party indexes; verify critical facts."
|
||||
|
||||
if not rows:
|
||||
return {"ok": True, "query": q, "search_type": stype, "retrieved_at": retrieved_at, "sort": sort_mode, "results": [], "note": "No results (empty or blocked). Try rephrasing the query."}
|
||||
return {"ok": True, "query": q, "search_type": stype, "retrieved_at": retrieved_at, "sort": sort_mode, "results": rows, "source": "duckduckgo", "note": note}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"Web search failed: {e}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="web_search",
|
||||
description="Search the public web (DuckDuckGo via ddgs, no API key).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Search keywords or question."},
|
||||
"max_results": {"type": "integer", "description": "Optional. Number of results (1–15). Default 8."},
|
||||
"search_type": {"type": "string", "enum": ["web", "news"], "description": "Optional. 'web' or 'news'."},
|
||||
"time_range": {"type": "string", "enum": ["d", "w", "m", "y"], "description": "Optional time limit."},
|
||||
},
|
||||
"required": ["query"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["web_search_tool"]
|
||||
19
runtime/tools/experts/memory/__init__.py
Normal file
19
runtime/tools/experts/memory/__init__.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
from __future__ import annotations
|
||||
|
||||
# Canonical memory expert tools live under this directory.
|
||||
from .wiki_tools import (
|
||||
memory_wiki_apply_tool,
|
||||
memory_wiki_get_tool,
|
||||
memory_wiki_lint_tool,
|
||||
memory_wiki_search_tool,
|
||||
memory_wiki_status_tool,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"memory_wiki_apply_tool",
|
||||
"memory_wiki_get_tool",
|
||||
"memory_wiki_lint_tool",
|
||||
"memory_wiki_search_tool",
|
||||
"memory_wiki_status_tool",
|
||||
]
|
||||
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable
|
||||
|
||||
|
|
@ -27,7 +26,7 @@ def _plugin_cfg() -> dict[str, Any]:
|
|||
|
||||
def _wiki_handlers() -> dict[str, Callable[[dict[str, Any]], dict[str, Any]]]:
|
||||
api_path = (PROJECT_ROOT / "oclaw" / "runtime" / "extensions" / "memory-wiki" / "api.py").resolve()
|
||||
spec = importlib.util.spec_from_file_location("memory_curator_wiki_api", str(api_path))
|
||||
spec = importlib.util.spec_from_file_location("memory_wiki_api", str(api_path))
|
||||
if spec is None or spec.loader is None:
|
||||
return {}
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
|
|
@ -58,10 +57,10 @@ def _delegate(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
|
|||
return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
|
||||
|
||||
|
||||
def memory_curator_wiki_status_tool() -> ToolSpec:
|
||||
def _status_tool(public_name: str, desc: str) -> ToolSpec:
|
||||
return ToolSpec(
|
||||
name="memory_curator_wiki_status",
|
||||
description="Read wiki runtime status for memory curation.",
|
||||
name=public_name,
|
||||
description=desc,
|
||||
parameters={"type": "object", "properties": {}, "required": [], "additionalProperties": False},
|
||||
handler=lambda args: _delegate("wiki_status", args),
|
||||
tags=frozenset({"memory", "wiki", "curator"}),
|
||||
|
|
@ -69,10 +68,10 @@ def memory_curator_wiki_status_tool() -> ToolSpec:
|
|||
)
|
||||
|
||||
|
||||
def memory_curator_wiki_get_tool() -> ToolSpec:
|
||||
def _get_tool(public_name: str, desc: str) -> ToolSpec:
|
||||
return ToolSpec(
|
||||
name="memory_curator_wiki_get",
|
||||
description="Read a markdown file from wiki for curation.",
|
||||
name=public_name,
|
||||
description=desc,
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
@ -89,10 +88,10 @@ def memory_curator_wiki_get_tool() -> ToolSpec:
|
|||
)
|
||||
|
||||
|
||||
def memory_curator_wiki_search_tool() -> ToolSpec:
|
||||
def _search_tool(public_name: str, desc: str) -> ToolSpec:
|
||||
return ToolSpec(
|
||||
name="memory_curator_wiki_search",
|
||||
description="Search wiki markdown for memory curation.",
|
||||
name=public_name,
|
||||
description=desc,
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
@ -110,10 +109,10 @@ def memory_curator_wiki_search_tool() -> ToolSpec:
|
|||
)
|
||||
|
||||
|
||||
def memory_curator_wiki_lint_tool() -> ToolSpec:
|
||||
def _lint_tool(public_name: str, desc: str) -> ToolSpec:
|
||||
return ToolSpec(
|
||||
name="memory_curator_wiki_lint",
|
||||
description="Lint wiki markdown structure for curation quality.",
|
||||
name=public_name,
|
||||
description=desc,
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {"path": {"type": "string"}},
|
||||
|
|
@ -126,10 +125,10 @@ def memory_curator_wiki_lint_tool() -> ToolSpec:
|
|||
)
|
||||
|
||||
|
||||
def memory_curator_wiki_apply_tool() -> ToolSpec:
|
||||
def _apply_tool(public_name: str, desc: str) -> ToolSpec:
|
||||
return ToolSpec(
|
||||
name="memory_curator_wiki_apply",
|
||||
description="Apply curated write/append/delete changes to wiki markdown.",
|
||||
name=public_name,
|
||||
description=desc,
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
@ -147,10 +146,31 @@ def memory_curator_wiki_apply_tool() -> ToolSpec:
|
|||
)
|
||||
|
||||
|
||||
def memory_wiki_status_tool() -> ToolSpec:
|
||||
return _status_tool("memory_wiki_status", "Read wiki runtime status for memory.")
|
||||
|
||||
|
||||
def memory_wiki_get_tool() -> ToolSpec:
|
||||
return _get_tool("memory_wiki_get", "Read a markdown file from memory wiki.")
|
||||
|
||||
|
||||
def memory_wiki_search_tool() -> ToolSpec:
|
||||
return _search_tool("memory_wiki_search", "Search memory wiki markdown.")
|
||||
|
||||
|
||||
def memory_wiki_lint_tool() -> ToolSpec:
|
||||
return _lint_tool("memory_wiki_lint", "Lint memory wiki markdown structure.")
|
||||
|
||||
|
||||
def memory_wiki_apply_tool() -> ToolSpec:
|
||||
return _apply_tool("memory_wiki_apply", "Apply write/append/delete changes to memory wiki markdown.")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"memory_curator_wiki_status_tool",
|
||||
"memory_curator_wiki_get_tool",
|
||||
"memory_curator_wiki_search_tool",
|
||||
"memory_curator_wiki_lint_tool",
|
||||
"memory_curator_wiki_apply_tool",
|
||||
"memory_wiki_status_tool",
|
||||
"memory_wiki_get_tool",
|
||||
"memory_wiki_search_tool",
|
||||
"memory_wiki_lint_tool",
|
||||
"memory_wiki_apply_tool",
|
||||
]
|
||||
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
from .wiki_curator_tools import (
|
||||
memory_curator_wiki_apply_tool,
|
||||
memory_curator_wiki_get_tool,
|
||||
memory_curator_wiki_lint_tool,
|
||||
memory_curator_wiki_search_tool,
|
||||
memory_curator_wiki_status_tool,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"memory_curator_wiki_status_tool",
|
||||
"memory_curator_wiki_get_tool",
|
||||
"memory_curator_wiki_search_tool",
|
||||
"memory_curator_wiki_lint_tool",
|
||||
"memory_curator_wiki_apply_tool",
|
||||
]
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
|
||||
def config_diff_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
left_name = str(args.get("left_name") or "left")
|
||||
right_name = str(args.get("right_name") or "right")
|
||||
left = str(args.get("left") or "")
|
||||
right = str(args.get("right") or "")
|
||||
left_lines = left.splitlines(keepends=False)
|
||||
right_lines = right.splitlines(keepends=False)
|
||||
diff_lines = list(
|
||||
difflib.unified_diff(left_lines, right_lines, fromfile=left_name, tofile=right_name, lineterm="")
|
||||
)
|
||||
return {"ok": True, "diff": "\n".join(diff_lines), "changed": left_lines != right_lines}
|
||||
|
||||
return ToolSpec(
|
||||
name="config_diff",
|
||||
description="Compare two configuration texts and return a unified diff.",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"left_name": {"type": "string", "description": "Optional label for the left side."},
|
||||
"right_name": {"type": "string", "description": "Optional label for the right side."},
|
||||
"left": {"type": "string", "description": "Left configuration text."},
|
||||
"right": {"type": "string", "description": "Right configuration text."},
|
||||
},
|
||||
"required": ["left", "right"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["config_diff_tool"]
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
_TTL_RE = re.compile(r"\bttl[= ]\d+\b", re.IGNORECASE)
|
||||
_AVG_WIN_RE = re.compile(r"Average\s*=\s*(\d+)\s*ms", re.IGNORECASE)
|
||||
_AVG_NIX_RE = re.compile(r"=\s*[\d.]+/([\d.]+)/[\d.]+/[\d.]+\s*ms")
|
||||
|
||||
|
||||
def _ping(host: str, count: int, timeout_ms: int) -> dict[str, Any]:
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
cmd = ["ping", "-n", str(count), "-w", str(timeout_ms), host]
|
||||
timeout_s = max(1, (timeout_ms * count) / 1000 + 2)
|
||||
else:
|
||||
timeout_s_each = max(1, int(round(timeout_ms / 1000)))
|
||||
cmd = ["ping", "-c", str(count), "-W", str(timeout_s_each), host]
|
||||
timeout_s = max(1, timeout_s_each * count + 2)
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s)
|
||||
except FileNotFoundError:
|
||||
return {"ok": False, "error": "ping command not found on this system"}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"ok": True, "reachable": False, "output": "ping timed out"}
|
||||
|
||||
output = (proc.stdout or "") + ("\n" + proc.stderr if proc.stderr else "")
|
||||
reachable = proc.returncode == 0 and bool(_TTL_RE.search(output))
|
||||
avg_ms = None
|
||||
if sys.platform == "win32":
|
||||
m = _AVG_WIN_RE.search(output)
|
||||
if m:
|
||||
try:
|
||||
avg_ms = int(m.group(1))
|
||||
except ValueError:
|
||||
avg_ms = None
|
||||
else:
|
||||
m2 = _AVG_NIX_RE.search(output)
|
||||
if m2:
|
||||
try:
|
||||
avg_ms = int(float(m2.group(1)))
|
||||
except ValueError:
|
||||
avg_ms = None
|
||||
return {"ok": True, "reachable": reachable, "avg_ms": avg_ms, "returncode": proc.returncode, "output": output}
|
||||
|
||||
|
||||
def device_status_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
host = str(args.get("host"))
|
||||
count = int(args.get("count") or 2)
|
||||
timeout_ms = int(args.get("timeout_ms") or 1000)
|
||||
if count < 1 or count > 10:
|
||||
return {"ok": False, "error": "count must be between 1 and 10"}
|
||||
if timeout_ms < 200 or timeout_ms > 10000:
|
||||
return {"ok": False, "error": "timeout_ms must be between 200 and 10000"}
|
||||
return _ping(host=host, count=count, timeout_ms=timeout_ms)
|
||||
|
||||
return ToolSpec(
|
||||
name="device_status",
|
||||
description="Check host reachability using ICMP ping (system ping binary).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {"type": "string", "description": "Hostname or IP address."},
|
||||
"count": {"type": "integer", "description": "Number of ping probes. Default 2."},
|
||||
"timeout_ms": {"type": "integer", "description": "Per-packet timeout in milliseconds. Default 1000."},
|
||||
},
|
||||
"required": ["host"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["device_status_tool"]
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
|
||||
def _default_edges() -> list[tuple[str, str]]:
|
||||
return [
|
||||
("R1", "R2"),
|
||||
("R2", "R3"),
|
||||
("R3", "R4"),
|
||||
("R2", "R5"),
|
||||
("R5", "R4"),
|
||||
("R1", "SW1"),
|
||||
("SW1", "FW1"),
|
||||
("FW1", "R3"),
|
||||
]
|
||||
|
||||
|
||||
def _build_adj(edges: list[tuple[str, str]]) -> dict[str, set[str]]:
|
||||
adj: dict[str, set[str]] = {}
|
||||
for a, b in edges:
|
||||
adj.setdefault(a, set()).add(b)
|
||||
adj.setdefault(b, set()).add(a)
|
||||
return adj
|
||||
|
||||
|
||||
def _bfs_path(adj: dict[str, set[str]], src: str, dst: str) -> list[str] | None:
|
||||
if src == dst:
|
||||
return [src]
|
||||
q: deque[str] = deque([src])
|
||||
prev: dict[str, str | None] = {src: None}
|
||||
while q:
|
||||
cur = q.popleft()
|
||||
for nxt in sorted(adj.get(cur, set())):
|
||||
if nxt in prev:
|
||||
continue
|
||||
prev[nxt] = cur
|
||||
if nxt == dst:
|
||||
q.clear()
|
||||
break
|
||||
q.append(nxt)
|
||||
if dst not in prev:
|
||||
return None
|
||||
path: list[str] = []
|
||||
cur2: str | None = dst
|
||||
while cur2 is not None:
|
||||
path.append(cur2)
|
||||
cur2 = prev[cur2]
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
|
||||
def get_path_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
src = str(args.get("src"))
|
||||
dst = str(args.get("dst"))
|
||||
raw_edges = args.get("topology_edges")
|
||||
|
||||
edges: list[tuple[str, str]]
|
||||
if raw_edges is None:
|
||||
edges = _default_edges()
|
||||
else:
|
||||
edges = []
|
||||
for item in raw_edges:
|
||||
if not isinstance(item, (list, tuple)) or len(item) != 2:
|
||||
return {"ok": False, "error": "topology_edges must be an array of pairs; each item must contain two node names."}
|
||||
edges.append((str(item[0]), str(item[1])))
|
||||
|
||||
adj = _build_adj(edges)
|
||||
path = _bfs_path(adj, src, dst)
|
||||
if not path:
|
||||
return {"ok": False, "src": src, "dst": dst, "error": "No reachable path in the given topology."}
|
||||
return {"ok": True, "src": src, "dst": dst, "hops": path, "hop_count": len(path) - 1}
|
||||
|
||||
return ToolSpec(
|
||||
name="get_path",
|
||||
description="Compute the shortest path from src to dst (BFS) over an undirected topology. Optional topology_edges overrides the built-in demo graph.",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"src": {"type": "string", "description": "Source node name."},
|
||||
"dst": {"type": "string", "description": "Destination node name."},
|
||||
"topology_edges": {
|
||||
"type": "array",
|
||||
"description": 'Optional edge list, e.g. [["R1","R2"],["R2","R3"]].',
|
||||
"items": {"type": "array", "items": {"type": "string"}, "minItems": 2, "maxItems": 2},
|
||||
},
|
||||
},
|
||||
"required": ["src", "dst"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["get_path_tool"]
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
_LEVEL_RE = re.compile(r"\b(ERROR|WARN|WARNING|INFO|DEBUG)\b", re.IGNORECASE)
|
||||
|
||||
|
||||
def log_analysis_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
text = str(args.get("log") or "")
|
||||
max_lines = int(args.get("max_lines") or 2000)
|
||||
lines = text.splitlines()
|
||||
if len(lines) > max_lines:
|
||||
lines = lines[-max_lines:]
|
||||
|
||||
levels: Counter[str] = Counter()
|
||||
samples: dict[str, list[str]] = {"ERROR": [], "WARN": []}
|
||||
for line in lines:
|
||||
m = _LEVEL_RE.search(line)
|
||||
if not m:
|
||||
continue
|
||||
level = m.group(1).upper()
|
||||
if level == "WARNING":
|
||||
level = "WARN"
|
||||
if level in ("ERROR", "WARN", "INFO", "DEBUG"):
|
||||
levels[level] += 1
|
||||
if level in samples and len(samples[level]) < 5:
|
||||
samples[level].append(line[:500])
|
||||
|
||||
top_lines = [l[:500] for l in lines[-20:]]
|
||||
return {"ok": True, "line_count": len(lines), "level_count": dict(levels), "samples": samples, "tail": top_lines}
|
||||
|
||||
return ToolSpec(
|
||||
name="log_analysis",
|
||||
description="Summarize log text: counts of ERROR/WARN/INFO/DEBUG lines, sample lines, and the last lines (tail).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"log": {"type": "string", "description": "Log text to analyze."},
|
||||
"max_lines": {"type": "integer", "description": "Maximum number of lines to analyze (uses the tail if exceeded). Default 2000."},
|
||||
},
|
||||
"required": ["log"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["log_analysis_tool"]
|
||||
|
|
@ -1,259 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import datetime
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
|
||||
def dns_lookup_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
domain = args.get("domain")
|
||||
if not domain:
|
||||
return {"ok": False, "error": "domain is required"}
|
||||
try:
|
||||
ips = socket.gethostbyname_ex(domain)[2]
|
||||
return {"ok": True, "domain": domain, "ips": ips, "count": len(ips)}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"DNS resolution failed: {e}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="dns_lookup",
|
||||
description="Resolve a domain name to IPv4 addresses (A records via system resolver).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"domain": {"type": "string", "description": "Domain name (e.g. example.com)."},
|
||||
},
|
||||
"required": ["domain"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
def ssl_check_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
domain = args.get("domain")
|
||||
port = int(args.get("port") or 443)
|
||||
if not domain:
|
||||
return {"ok": False, "error": "domain is required"}
|
||||
try:
|
||||
context = ssl.create_default_context()
|
||||
with socket.create_connection((domain, port), timeout=10) as sock:
|
||||
with context.wrap_socket(sock, server_hostname=domain) as ssock:
|
||||
cert = ssock.getpeercert()
|
||||
not_before = datetime.datetime.strptime(cert["notBefore"], "%b %d %H:%M:%S %Y %Z")
|
||||
not_after = datetime.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
|
||||
remaining_days = (not_after - datetime.datetime.utcnow()).days
|
||||
subject = dict(x[0] for x in cert["subject"])
|
||||
issuer = dict(x[0] for x in cert["issuer"])
|
||||
return {
|
||||
"ok": True,
|
||||
"domain": domain,
|
||||
"issuer": issuer.get("commonName"),
|
||||
"issued_to": subject.get("commonName"),
|
||||
"valid_from": not_before.strftime("%Y-%m-%d"),
|
||||
"valid_until": not_after.strftime("%Y-%m-%d"),
|
||||
"remaining_days": remaining_days,
|
||||
"is_expired": remaining_days < 0,
|
||||
}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"SSL check failed: {e}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="ssl_cert_check",
|
||||
description="Inspect the TLS certificate presented by host:port (default 443).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"domain": {"type": "string", "description": "Server hostname."},
|
||||
"port": {"type": "integer", "description": "TCP port. Default 443."},
|
||||
},
|
||||
"required": ["domain"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
def port_check_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
host = args.get("host")
|
||||
port = int(args.get("port"))
|
||||
protocol = str(args.get("protocol") or "tcp").lower()
|
||||
timeout = float(args.get("timeout") or 2.0)
|
||||
if not host or not port:
|
||||
return {"ok": False, "error": "host and port are required"}
|
||||
if protocol == "tcp":
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=timeout):
|
||||
return {"ok": True, "host": host, "port": port, "protocol": "TCP", "status": "open"}
|
||||
except socket.timeout:
|
||||
return {"ok": True, "host": host, "port": port, "protocol": "TCP", "status": "timeout"}
|
||||
except Exception as e:
|
||||
return {"ok": True, "host": host, "port": port, "protocol": "TCP", "status": "closed", "error": str(e)}
|
||||
if protocol == "udp":
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
sock.sendto(b"", (host, port))
|
||||
try:
|
||||
sock.recvfrom(1024)
|
||||
return {"ok": True, "host": host, "port": port, "protocol": "UDP", "status": "open", "received": True}
|
||||
except socket.timeout:
|
||||
return {"ok": True, "host": host, "port": port, "protocol": "UDP", "status": "open|filtered"}
|
||||
except Exception as e:
|
||||
return {"ok": True, "host": host, "port": port, "protocol": "UDP", "status": "closed", "error": str(e)}
|
||||
finally:
|
||||
sock.close()
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"UDP check failed: {e}"}
|
||||
return {"ok": False, "error": f"Unsupported protocol: {protocol}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="port_check",
|
||||
description="Test whether a TCP or UDP port appears open on a host.",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {"type": "string", "description": "Hostname or IP address."},
|
||||
"port": {"type": "integer", "description": "Port number."},
|
||||
"protocol": {"type": "string", "enum": ["tcp", "udp"], "description": "tcp or udp. Default tcp."},
|
||||
"timeout": {"type": "number", "description": "Timeout in seconds. Default 2.0."},
|
||||
},
|
||||
"required": ["host", "port"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
def port_scan_tool() -> ToolSpec:
|
||||
COMMON_PORTS = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 1433, 1521, 3306, 3389, 5432, 6379, 8080, 27017]
|
||||
|
||||
def scan_port(host: str, port: int, timeout: float) -> int | None:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=timeout):
|
||||
return port
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
host = args.get("host")
|
||||
start_port = args.get("start_port")
|
||||
end_port = args.get("end_port")
|
||||
ports_to_scan = args.get("ports")
|
||||
timeout = float(args.get("timeout") or 0.5)
|
||||
max_threads = int(args.get("max_threads") or 20)
|
||||
if not host:
|
||||
return {"ok": False, "error": "host is required"}
|
||||
if ports_to_scan:
|
||||
ports = [int(p) for p in ports_to_scan]
|
||||
elif start_port is not None and end_port is not None:
|
||||
s, e = int(start_port), int(end_port)
|
||||
if e - s > 1000:
|
||||
return {"ok": False, "error": "Cannot scan more than 1000 ports in one call"}
|
||||
ports = list(range(s, e + 1))
|
||||
else:
|
||||
ports = COMMON_PORTS
|
||||
open_ports: list[int] = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
|
||||
future_to_port = {executor.submit(scan_port, host, port, timeout): port for port in ports}
|
||||
for future in concurrent.futures.as_completed(future_to_port):
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
open_ports.append(result)
|
||||
open_ports.sort()
|
||||
return {
|
||||
"ok": True,
|
||||
"host": host,
|
||||
"open_ports": open_ports,
|
||||
"scanned_count": len(ports),
|
||||
"open_count": len(open_ports),
|
||||
"status": "completed",
|
||||
}
|
||||
|
||||
return ToolSpec(
|
||||
name="port_scan",
|
||||
description="Scan TCP ports on a host (common ports, a numeric range, or an explicit list).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {"type": "string", "description": "Hostname or IP address."},
|
||||
"start_port": {"type": "integer", "description": "Start of port range (inclusive)."},
|
||||
"end_port": {"type": "integer", "description": "End of port range (inclusive)."},
|
||||
"ports": {"type": "array", "items": {"type": "integer"}, "description": "Explicit list of ports to scan."},
|
||||
"timeout": {"type": "number", "description": "Per-port timeout in seconds. Default 0.5."},
|
||||
"max_threads": {"type": "integer", "description": "Maximum concurrent probes. Default 20."},
|
||||
},
|
||||
"required": ["host"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
def local_net_info_tool() -> ToolSpec:
|
||||
def get_mac_address() -> str:
|
||||
return ":".join(["{:02x}".format((uuid.getnode() >> i) & 0xFF) for i in range(0, 8 * 6, 8)][::-1])
|
||||
|
||||
def get_public_ip() -> str:
|
||||
try:
|
||||
with httpx.Client(timeout=5.0) as client:
|
||||
resp = client.get("https://api64.ipify.org?format=json")
|
||||
return str(resp.json().get("ip") or "Unknown")
|
||||
except Exception:
|
||||
return "Unknown"
|
||||
|
||||
def get_gateway() -> str:
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
output = subprocess.check_output("route print 0.0.0.0", shell=True).decode("gbk", errors="replace")
|
||||
for line in output.splitlines():
|
||||
if "0.0.0.0" in line and "On-link" not in line:
|
||||
parts = line.split()
|
||||
if len(parts) >= 3:
|
||||
return parts[2]
|
||||
else:
|
||||
output = subprocess.check_output("ip route show default", shell=True).decode(errors="replace")
|
||||
return output.split()[2]
|
||||
except Exception:
|
||||
return "Unknown"
|
||||
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
try:
|
||||
hostname = socket.gethostname()
|
||||
local_ip = socket.gethostbyname(hostname)
|
||||
mac = get_mac_address()
|
||||
gateway = get_gateway()
|
||||
public_ip = get_public_ip()
|
||||
return {
|
||||
"ok": True,
|
||||
"hostname": hostname,
|
||||
"local_ip": local_ip,
|
||||
"public_ip": public_ip,
|
||||
"mac_address": mac,
|
||||
"gateway": gateway,
|
||||
"platform": sys.platform,
|
||||
}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"Failed to read local network info: {e}"}
|
||||
|
||||
return ToolSpec(
|
||||
name="get_local_net_info",
|
||||
description="Summarize local hostname, IPs, MAC, default gateway, and OS platform (best-effort).",
|
||||
parameters={"type": "object", "properties": {}, "additionalProperties": False},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["dns_lookup_tool", "ssl_check_tool", "port_check_tool", "port_scan_tool", "local_net_info_tool"]
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
"""网络运维专家工具清单。"""
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
|
||||
def query_route_tool() -> ToolSpec:
|
||||
from .query_route import query_route_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def get_path_tool() -> ToolSpec:
|
||||
from .get_path import get_path_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def config_diff_tool() -> ToolSpec:
|
||||
from .config_diff import config_diff_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def device_status_tool() -> ToolSpec:
|
||||
from .device_status import device_status_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def log_analysis_tool() -> ToolSpec:
|
||||
from .log_analysis import log_analysis_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def dns_lookup_tool() -> ToolSpec:
|
||||
from .network_probe_tools import dns_lookup_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def ssl_check_tool() -> ToolSpec:
|
||||
from .network_probe_tools import ssl_check_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def port_check_tool() -> ToolSpec:
|
||||
from .network_probe_tools import port_check_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def port_scan_tool() -> ToolSpec:
|
||||
from .network_probe_tools import port_scan_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
def local_net_info_tool() -> ToolSpec:
|
||||
from .network_probe_tools import local_net_info_tool as factory
|
||||
|
||||
return factory()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"query_route_tool",
|
||||
"get_path_tool",
|
||||
"config_diff_tool",
|
||||
"device_status_tool",
|
||||
"log_analysis_tool",
|
||||
"dns_lookup_tool",
|
||||
"ssl_check_tool",
|
||||
"port_check_tool",
|
||||
"port_scan_tool",
|
||||
"local_net_info_tool",
|
||||
]
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from typing import Any
|
||||
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
|
||||
|
||||
def _pick_route(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> dict[str, Any]:
|
||||
if isinstance(ip, ipaddress.IPv4Address):
|
||||
if ip in ipaddress.ip_network("10.0.0.0/8"):
|
||||
return {"prefix": "10.0.0.0/8", "next_hop": "192.168.1.1", "out_if": "GigabitEthernet0/0"}
|
||||
if ip in ipaddress.ip_network("172.16.0.0/12"):
|
||||
return {"prefix": "172.16.0.0/12", "next_hop": "192.168.2.1", "out_if": "GigabitEthernet0/1"}
|
||||
if ip in ipaddress.ip_network("192.168.0.0/16"):
|
||||
return {"prefix": "192.168.0.0/16", "next_hop": "direct", "out_if": "Vlan10"}
|
||||
return {"prefix": "0.0.0.0/0", "next_hop": "203.0.113.1", "out_if": "GigabitEthernet1/0"}
|
||||
|
||||
if ip in ipaddress.ip_network("fc00::/7"):
|
||||
return {"prefix": "fc00::/7", "next_hop": "fe80::1", "out_if": "Vlan20"}
|
||||
return {"prefix": "::/0", "next_hop": "2001:db8::1", "out_if": "GigabitEthernet1/0"}
|
||||
|
||||
|
||||
def query_route_tool() -> ToolSpec:
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
destination = str(args.get("destination"))
|
||||
vrf = args.get("vrf")
|
||||
try:
|
||||
ip = ipaddress.ip_address(destination)
|
||||
except ValueError:
|
||||
return {"ok": False, "error": f"Invalid IP address: {destination}"}
|
||||
route = _pick_route(ip)
|
||||
return {"ok": True, "destination": destination, "vrf": vrf, "route": route}
|
||||
|
||||
return ToolSpec(
|
||||
name="query_route",
|
||||
description="Look up route egress and next hop for a destination IP (demo data; replace with a real device or controller API).",
|
||||
parameters={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"destination": {"type": "string", "description": "Destination IP address (IPv4 or IPv6)."},
|
||||
"vrf": {"type": "string", "description": "Optional VRF name."},
|
||||
},
|
||||
"required": ["destination"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
handler=handler,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["query_route_tool"]
|
||||
|
|
@ -3,19 +3,41 @@ from __future__ import annotations
|
|||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
from oclaw.runtime.tools.base import ToolSpec
|
||||
from oclaw.runtime.tools.experts.workspace.workspace_base import resolve_workspace_path, truncate_text
|
||||
|
||||
|
||||
def run_command_tool() -> ToolSpec:
|
||||
def _run_command_enabled() -> bool:
|
||||
import os
|
||||
|
||||
try:
|
||||
raw_setting = str(SqliteStore(db_path()).get_setting("AIA_ENABLE_RUN_COMMAND") or "").strip().lower()
|
||||
if raw_setting in ("0", "false", "no", "off"):
|
||||
return False
|
||||
if raw_setting in ("1", "true", "yes", "on"):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raw_env = str(os.getenv("AIA_ENABLE_RUN_COMMAND") or "").strip().lower()
|
||||
if raw_env in ("0", "false", "no", "off"):
|
||||
return False
|
||||
if raw_env in ("1", "true", "yes", "on"):
|
||||
return True
|
||||
# Default disabled when unset (explicit opt-in only).
|
||||
return False
|
||||
|
||||
def handler(args: dict[str, Any]) -> dict[str, Any]:
|
||||
import os
|
||||
|
||||
if str(os.getenv("AIA_ENABLE_RUN_COMMAND") or "").strip().lower() not in ("1", "true", "yes", "on"):
|
||||
if not _run_command_enabled():
|
||||
return {
|
||||
"ok": False,
|
||||
"error": "disabled",
|
||||
"hint": "Set AIA_ENABLE_RUN_COMMAND=1 to enable this high-risk tool.",
|
||||
"hint": "Enable run_command in Admin -> Plugins -> Tool Policy.",
|
||||
}
|
||||
command = str(args.get("command") or "").strip()
|
||||
cwd = str(args.get("cwd") or "").strip()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue