feat: integrate netx ops data access and unify prompt/workspace runtime

Migrate prompt templates into runtime workspaces, add network_ops netx toolchain (latest batch injection, raw fields, SQL query), and align docs/tests/admin/runtime wiring so ops analysis can query netx detail data through stable role-scoped paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
oliver 2026-05-03 23:54:38 +08:00
parent 83f46f8aa2
commit b0e0c05d8a
60 changed files with 1143 additions and 46 deletions

View file

@ -32,7 +32,7 @@ from oclaw.platform.persistence.sqlite_store import (
agent_profile_bindings_setting_key,
is_administrator_model_pool,
)
from oclaw.prompts import render_prompt
from oclaw.runtime.prompt_templates import render_prompt
from oclaw.runtime.tools.catalog import default_registry
from oclaw.runtime.tools.plugin_loader import sync_plugin_metadata

View file

@ -5,14 +5,10 @@ from typing import Any
from oclaw.runtime.chat.agent import Agent
from oclaw.runtime.agent_context import build_role_system_context
from oclaw.platform.persistence.sqlite_store import SqliteStore
from oclaw.prompts.loader import render_prompt
from oclaw.runtime.tools import default_registry
NETWORK_SYSTEM_PROMPT_ZH = render_prompt(
"agents/network_ops_system.zh.md",
variables={"ROLE_SYSTEM_CONTEXT": build_role_system_context("ops")},
strict=True,
)
# Ops 专家走与 specialists 相同的工作区框架:runtime/workspaces/ops/{SOUL,ROLE_SYSTEM}.md
NETWORK_SYSTEM_PROMPT_ZH = build_role_system_context("ops")
class NetworkOpsAgent(Agent):

View file

@ -22,7 +22,7 @@ from oclaw.platform.llm.chat_models import (
build_default_model,
gemini_openai_compat_client,
)
from oclaw.prompts.loader import render_prompt_for_lang
from oclaw.runtime.prompt_templates import render_prompt_for_lang
from oclaw.runtime.tools.tool_validation import validate_tool_arguments
logger = logging.getLogger(__name__)

View file

@ -6,7 +6,7 @@ from __future__ import annotations
"""
from typing import Any
from oclaw.prompts import render_prompt
from oclaw.runtime.prompt_templates import render_prompt
def format_ollama_failure_banner(*, lang: str, exc: BaseException) -> str:

View file

@ -16,7 +16,7 @@ from typing import Any
from oclaw.platform.llm.chat_models import _normalize_image_b64_payload, gemini_openai_compat_client, ChatModel
from oclaw.runtime.chat.media_redact import redact_embedded_image_blobs
from oclaw.runtime.chat.tool_runtime import tool_llm_message_max_chars, truncate_tool_result_for_llm_messages
from oclaw.prompts import render_prompt
from oclaw.runtime.prompt_templates import render_prompt
from oclaw.platform.files.attachment_assets import attachment_id_to_data_url
from oclaw.runtime.relay_pointer import parse_pointer_uri

View file

@ -24,6 +24,7 @@ from oclaw.runtime.types import OclawMemoryContext
from oclaw.runtime.orchestration.trace import new_span_id
from oclaw.runtime.tools.base import ToolRegistry
from oclaw.runtime.hooks_runtime import trigger_hook_event
from oclaw.runtime.tools.experts.network_ops.netx_tools import ops_netx_system_context_extension
_OCLAW_TOOL_RESULT_HARD_CAP_CHARS = 24_000
_OCLAW_ATTACHMENT_TEXT_REPLAY_CAP_CHARS = 4_000
@ -631,6 +632,13 @@ def _build_model_context(
final_system = f"{prepend}\n\n{final_system}".strip()
except Exception:
pass
try:
if str(skill_binding_role or "").strip().lower() == "ops":
ext = ops_netx_system_context_extension(lang=lang or "zh")
if str(ext or "").strip():
final_system = f"{final_system}\n\n{ext.strip()}".strip()
except Exception:
pass
trunc_raw = str(store.get_setting("AIA_TOOL_CONTEXT_TRUNCATE_ENABLED") or "").strip().lower()
tool_context_truncate_enabled = trunc_raw not in ("0", "false", "no", "off")
llm_messages = build_llm_messages(

View file

@ -27,7 +27,7 @@ from oclaw.runtime.types import (
normalize_requested_specialist,
)
from oclaw.platform.config.paths import PROJECT_ROOT
from oclaw.prompts import render_prompt
from oclaw.runtime.prompt_templates import render_prompt
from oclaw.runtime.command_parser import parse_internal_command
from oclaw.runtime.core.agent_execution import AgentCoreRunInput, build_memory_context, run_agent_core

View file

@ -6,7 +6,7 @@ from typing import Any
from oclaw.runtime.types import OclawMemoryContext
from oclaw.runtime.orchestration.memory import semantic_retrieve, session_memory_digest
from oclaw.prompts.loader import render_runtime_prompt
from oclaw.runtime.prompt_templates import render_runtime_prompt
_SPECIALIST_FLAGS_SETTING_KEY = "AIA_CHAT_SPECIALIST_FLAGS_JSON"

View file

@ -7,7 +7,7 @@ from typing import Any
from oclaw.runtime.agents.agent_scope import resolve_agent_id_by_workspace_path
from oclaw.runtime.hooks_runtime import get_active_hooks_config, trigger_hook_event
from oclaw.platform.config.paths import PROJECT_ROOT
from oclaw.prompts.loader import render_runtime_prompt
from oclaw.runtime.prompt_templates import render_runtime_prompt
_PROJECT_CONTEXT_FILES: tuple[str, ...] = (
"TOOLS.md",

View file

@ -0,0 +1,17 @@
from .loader import (
PromptDoc,
load_prompt_doc,
load_runtime_prompt_doc,
render_prompt,
render_prompt_for_lang,
render_runtime_prompt,
)
__all__ = [
"PromptDoc",
"load_prompt_doc",
"load_runtime_prompt_doc",
"render_prompt",
"render_prompt_for_lang",
"render_runtime_prompt",
]

View file

@ -0,0 +1,92 @@
from __future__ import annotations
import json
import os
from typing import Any
try:
import yaml
except ImportError: # pragma: no cover - requirements.txt includes PyYAML
yaml = None # type: ignore[assignment]
def split_markdown_frontmatter(raw: str) -> tuple[str, str]:
"""Split leading YAML frontmatter from markdown body (oclaw-style `---` fences)."""
txt = str(raw or "")
if not txt.startswith("---\n"):
return "", txt
end = txt.find("\n---\n", 4)
if end < 0:
return "", txt
return txt[4:end], txt[end + 5 :]
def _legacy_line_parse(frontmatter_text: str) -> dict[str, Any]:
"""Best-effort key: value lines (pre-YAML migration compatibility)."""
out: dict[str, Any] = {}
for ln in str(frontmatter_text or "").splitlines():
line = ln.strip()
if not line or line.startswith("#") or ":" not in line:
continue
k, v = line.split(":", 1)
key = str(k).strip()
val = str(v).strip()
if (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):
val = val[1:-1]
out[key] = val
meta_raw = str(out.get("metadata") or "").strip()
if meta_raw:
try:
out["metadata"] = json.loads(meta_raw)
except Exception:
out["metadata"] = {}
else:
out["metadata"] = {}
return out
def frontmatter_strict_yaml() -> bool:
return str(os.getenv("AIA_PROMPT_FRONTMATTER_STRICT", "")).strip().lower() in {"1", "true", "yes", "on"}
def parse_frontmatter_dict(frontmatter_text: str, *, source: str = "prompt") -> dict[str, Any]:
"""
Parse YAML frontmatter. On YAML failure, falls back to legacy line parser unless
AIA_PROMPT_FRONTMATTER_STRICT is truthy (then raises).
"""
text = str(frontmatter_text or "").strip()
if not text:
return {}
strict = frontmatter_strict_yaml()
if yaml is None:
if strict:
raise RuntimeError("PyYAML is required when AIA_PROMPT_FRONTMATTER_STRICT is enabled")
return _legacy_line_parse(text)
try:
data = yaml.safe_load(text)
except yaml.YAMLError as exc:
if strict:
raise ValueError(f"invalid YAML frontmatter ({source}): {exc}") from exc
return _legacy_line_parse(text)
if data is None:
return {}
if not isinstance(data, dict):
if strict:
raise ValueError(f"frontmatter YAML root must be a mapping ({source})")
return _legacy_line_parse(text)
return dict(data)
def parse_markdown_document(raw: str, *, source: str = "markdown") -> tuple[dict[str, Any], str]:
"""Split file and parse frontmatter to a dict; body is stripped markdown."""
fm_text, body = split_markdown_frontmatter(raw)
meta = parse_frontmatter_dict(fm_text, source=source) if fm_text.strip() else {}
return meta, str(body or "").strip()
__all__ = [
"frontmatter_strict_yaml",
"parse_frontmatter_dict",
"parse_markdown_document",
"split_markdown_frontmatter",
]

View file

@ -0,0 +1,102 @@
from __future__ import annotations
import re
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Any
from oclaw.platform.config.paths import PROJECT_ROOT
from oclaw.runtime.prompt_templates.frontmatter import parse_markdown_document
_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_]+)\s*\}\}")
@dataclass(frozen=True)
class PromptDoc:
frontmatter: dict[str, Any]
body: str
def _system_prompt_root() -> Path:
"""Builtin Markdown templates: ``runtime/workspaces/_system`` (replaces former ``prompts/``)."""
return (PROJECT_ROOT / "runtime" / "workspaces" / "_system").resolve()
def _prompts_root() -> Path:
return _system_prompt_root()
def _runtime_prompts_root() -> Path:
return _system_prompt_root()
@lru_cache(maxsize=512)
def load_prompt_doc(prompt_path: str) -> PromptDoc:
p = (_prompts_root() / str(prompt_path)).resolve()
if not p.exists():
raise FileNotFoundError(f"prompt not found: {prompt_path}")
raw = p.read_text(encoding="utf-8")
fm, body = parse_markdown_document(raw, source=f"prompt:{prompt_path}")
return PromptDoc(frontmatter=fm, body=body)
@lru_cache(maxsize=512)
def load_runtime_prompt_doc(prompt_path: str) -> PromptDoc:
p = (_runtime_prompts_root() / str(prompt_path)).resolve()
if not p.exists():
raise FileNotFoundError(f"runtime prompt not found: {prompt_path}")
raw = p.read_text(encoding="utf-8")
fm, body = parse_markdown_document(raw, source=f"runtime_prompt:{prompt_path}")
return PromptDoc(frontmatter=fm, body=body)
def render_prompt_for_lang(stem: str, lang: str, *, variables: dict[str, Any] | None = None, strict: bool = True) -> str:
suf = "en" if (lang or "zh").strip().lower().startswith("en") else "zh"
return render_prompt(f"{stem}.{suf}.md", variables=variables, strict=strict)
def render_prompt(prompt_path: str, *, variables: dict[str, Any] | None = None, strict: bool = True) -> str:
doc = load_prompt_doc(prompt_path)
vars_in = dict(variables or {})
missing: set[str] = set()
def _repl(m: re.Match[str]) -> str:
key = str(m.group(1) or "")
if key in vars_in:
return str(vars_in.get(key) or "")
missing.add(key)
return ""
out = _VAR_RE.sub(_repl, doc.body)
if strict and missing:
raise ValueError(f"missing prompt variables for {prompt_path}: {', '.join(sorted(missing))}")
return out.strip()
def render_runtime_prompt(prompt_path: str, *, variables: dict[str, Any] | None = None, strict: bool = True) -> str:
doc = load_runtime_prompt_doc(prompt_path)
vars_in = dict(variables or {})
missing: set[str] = set()
def _repl(m: re.Match[str]) -> str:
key = str(m.group(1) or "")
if key in vars_in:
return str(vars_in.get(key) or "")
missing.add(key)
return ""
out = _VAR_RE.sub(_repl, doc.body)
if strict and missing:
raise ValueError(f"missing runtime prompt variables for {prompt_path}: {', '.join(sorted(missing))}")
return out.strip()
__all__ = [
"PromptDoc",
"load_prompt_doc",
"load_runtime_prompt_doc",
"render_prompt",
"render_prompt_for_lang",
"render_runtime_prompt",
]

View file

@ -7,7 +7,7 @@ from typing import Any
from oclaw.runtime.types import StandardMessage
from oclaw.runtime.types import normalize_interaction_mode, normalize_requested_specialist
from oclaw.prompts.loader import render_runtime_prompt
from oclaw.runtime.prompt_templates import render_runtime_prompt
from oclaw.runtime.chat.model_path_audit import ensure_no_tool_or_embedded_image_payload

View file

@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any
from oclaw.platform.config.paths import PROJECT_ROOT
from oclaw.platform.config.runtime_paths import runtime_skills_root
from oclaw.prompts.frontmatter import parse_frontmatter_dict, split_markdown_frontmatter
from oclaw.runtime.prompt_templates.frontmatter import parse_frontmatter_dict, split_markdown_frontmatter
from oclaw.runtime.skill_manifest_core import (
SkillInstallSpec,
normalize_frontmatter,

View file

@ -12,7 +12,7 @@ from oclaw.runtime.skills_workspace_lane import (
)
from oclaw.runtime.types import OclawMemoryContext
from oclaw.runtime.workspaces.experts import expert_workspace_signature_token
from oclaw.prompts.loader import render_runtime_prompt
from oclaw.runtime.prompt_templates import render_runtime_prompt
from oclaw.runtime.tools.base import ToolRegistry
_EXECUTOR_STATIC_PROMPT_CACHE_LOCK = threading.Lock()

View file

@ -0,0 +1,466 @@
"""Internal read-only tools: query netx REST API (PostgreSQL backend on netx side).
Configure via environment:
- ``OCLAW_NETX_BASE_URL`` (default ``http://127.0.0.1:8890``)
- ``OCLAW_NETX_API_TOKEN`` (optional) → sent as ``Authorization: Bearer …`` if set.
"""
from __future__ import annotations
import os
import threading
import time
from typing import Any
import httpx
from oclaw.runtime.tools.base import ToolSpec
def _netx_base_url() -> str:
return (os.getenv("OCLAW_NETX_BASE_URL") or "http://127.0.0.1:8890").strip().rstrip("/")
def _netx_headers() -> dict[str, str]:
h = {"accept": "application/json"}
tok = (os.getenv("OCLAW_NETX_API_TOKEN") or "").strip()
if tok:
h["authorization"] = f"Bearer {tok}"
return h
def _http_json(method: str, path: str, *, params: dict[str, Any] | None = None) -> dict[str, Any]:
base = _netx_base_url()
url = f"{base}{path}"
try:
with httpx.Client(timeout=45.0) as client:
resp = client.request(method, url, params=params or None, headers=_netx_headers())
text = resp.text
if not resp.is_success:
return {"ok": False, "error": f"netx_http_{resp.status_code}", "detail": text[:800]}
data = resp.json() if text else {}
return {"ok": True, "data": data if isinstance(data, dict) else {"raw": data}}
except Exception as exc:
return {"ok": False, "error": "netx_request_failed", "detail": str(exc)[:800]}
def _resolve_latest_import_batch_id() -> dict[str, Any]:
"""``GET /v1/batches`` 按 created_at 降序;取第一条为当前最新导入批次。"""
r = _http_json("GET", "/v1/batches", params={"limit": 1})
if not r.get("ok"):
return {"ok": False, "error": "netx_list_batches_failed", "detail": r.get("detail"), "upstream": r}
data = r.get("data") or {}
items = data.get("items")
if not isinstance(items, list) or not items:
return {"ok": False, "error": "no_import_batches", "detail": "netx 中尚无导入批次,请先导入或显式提供 batch_id"}
first = items[0]
if not isinstance(first, dict):
return {"ok": False, "error": "no_import_batches", "detail": "batch 列表格式异常"}
bid = str(first.get("batch_id") or "").strip()
if not bid:
return {"ok": False, "error": "no_import_batches", "detail": "batch 列表中无 batch_id"}
return {"ok": True, "batch_id": bid, "batch_row": first}
_OPS_NETX_SYS_CTX_LOCK = threading.Lock()
# Lang code -> (monotonic_ts, formatted extension text); short TTL to avoid hammering netx each tool round.
_OPS_NETX_SYS_CTX_CACHE: dict[str, tuple[float, str]] = {}
_OPS_NETX_SYS_CTX_TTL_SEC = 5.0
def _format_ops_netx_system_extension(r: dict[str, Any], *, lang_en: bool) -> str:
if r.get("ok"):
bid = str(r.get("batch_id") or "")
row = r.get("batch_row") if isinstance(r.get("batch_row"), dict) else {}
created = str(row.get("created_at") or "")
src = str(row.get("source_file") or "")
status = str(row.get("status") or "")
total = row.get("total_rows")
lines_en = [
"[Netx alarm import anchor]",
f"- batch_id: {bid}",
f"- source_file: {src}",
f"- created_at: {created}",
]
lines_zh = [
"[当前 netx 告警导入锚点]",
f"- batch_id: {bid}",
f"- 源文件: {src}",
f"- 导入时间: {created}",
]
if status:
(lines_en if lang_en else lines_zh).append(f"- status: {status}" if lang_en else f"- 状态: {status}")
if total is not None:
(lines_en if lang_en else lines_zh).append(f"- rows: {total}" if lang_en else f"- 行数: {total}")
tail_en = (
"- tools: netx_query_alarms, netx_aggregate_alarms, netx_run_diagnostics (pass batch_id above)\n"
"- note: numbers below are not alarm facts—call tools for evidence."
)
tail_zh = (
"- 工具: netx_query_alarms、netx_aggregate_alarms、netx_run_diagnostics(使用上述 batch_id)\n"
"- 说明: 此处仅为批次锚点;具体告警必须以工具返回为准,勿臆测。"
)
return "\n".join(lines_en + [tail_en]) if lang_en else "\n".join(lines_zh + [tail_zh])
err = str(r.get("error") or "")
detail = str(r.get("detail") or "")[:240]
if err == "no_import_batches":
if lang_en:
return (
"[Netx alarm import anchor]\n"
"- batch_id: (none)\n"
"- note: no import batches in netx yet—import alarms or pass batch_id in chat."
)
return (
"[当前 netx 告警导入锚点]\n"
"- batch_id: (暂无)\n"
"- 说明: netx 中尚无导入批次;请先导入告警或在对话中提供 batch_id。"
)
if lang_en:
return (
"[Netx alarm import anchor]\n"
f"- error: {err}\n"
f"- detail: {detail}\n"
"- fix: check OCLAW_NETX_BASE_URL and that netx API is reachable."
)
return (
"[当前 netx 告警导入锚点]\n"
f"- 错误: {err}\n"
f"- 详情: {detail}\n"
"- 处理: 检查 OCLAW_NETX_BASE_URL 与 netx 服务是否可达。"
)
def ops_netx_system_context_extension(*, lang: str = "zh") -> str:
"""Append to ops specialist system prompt: latest batch_id anchor (direct_loop injection).
Cached briefly to reduce duplicate HTTP calls across tool rounds.
"""
if str(os.getenv("OCLAW_OPS_NETX_CONTEXT_INJECT") or "1").strip().lower() in {"0", "false", "no", "off"}:
return ""
lang_en = str(lang or "").strip().lower().startswith("en")
lk = "en" if lang_en else "zh"
now = time.monotonic()
with _OPS_NETX_SYS_CTX_LOCK:
hit = _OPS_NETX_SYS_CTX_CACHE.get(lk)
if hit and (now - hit[0]) < _OPS_NETX_SYS_CTX_TTL_SEC:
return hit[1]
r = _resolve_latest_import_batch_id()
text = _format_ops_netx_system_extension(r, lang_en=lang_en)
store_ts = time.monotonic()
with _OPS_NETX_SYS_CTX_LOCK:
_OPS_NETX_SYS_CTX_CACHE[lk] = (store_ts, text)
return text
def netx_query_alarms_tool() -> ToolSpec:
"""Paginated alarm rows from netx (same filters as netx UI REST)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
resolution = "explicit"
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
resolution = "latest_import"
page = max(1, int(args.get("page") or 1))
page_size = min(200, max(1, int(args.get("page_size") or 50)))
params: dict[str, Any] = {
"batch_id": batch_id,
"page": page,
"page_size": page_size,
}
if str(args.get("alarm_code") or "").strip():
params["alarm_code"] = str(args.get("alarm_code")).strip()
if str(args.get("ne_name") or "").strip():
params["ne_name"] = str(args.get("ne_name")).strip()
if str(args.get("severity") or "").strip():
params["severity"] = str(args.get("severity")).strip()
out = _http_json("GET", "/v1/alarms", params=params)
if out.get("ok") and resolution == "latest_import":
out = {**out, "batch_id_used": batch_id, "batch_resolution": resolution}
return out
return ToolSpec(
name="netx_query_alarms",
description=(
"从独立运维工具 netx 读取告警明细(PostgreSQL 侧由 netx 托管)。"
"batch_id 可选:不传表示使用 netx 当前「最新」导入批次(/v1/batches 第一条)。"
"可选 alarm_code / ne_name / severity(与 netx 告警列表过滤语义一致);支持分页。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string", "description": "导入批次 ID;省略则用最新导入批次"},
"alarm_code": {"type": "string", "description": "告警码包含匹配(可选)"},
"ne_name": {"type": "string", "description": "网元名包含匹配(可选)"},
"severity": {"type": "string", "description": "规范化级别 critical/major/minor/warning/..."},
"page": {"type": "integer", "minimum": 1, "default": 1},
"page_size": {"type": "integer", "minimum": 1, "maximum": 200, "default": 50},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_aggregate_alarms_tool() -> ToolSpec:
"""Aggregate buckets from netx."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
resolution = "explicit"
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
resolution = "latest_import"
group_by = str(args.get("group_by") or "severity_norm").strip()
if group_by not in {"severity_norm", "alarm_code", "ne_name"}:
return {"ok": False, "error": "invalid_group_by"}
params: dict[str, Any] = {"group_by": group_by, "batch_id": batch_id}
out = _http_json("GET", "/v1/alarms/aggregate", params=params)
if out.get("ok") and resolution == "latest_import":
out = {**out, "batch_id_used": batch_id, "batch_resolution": resolution}
return out
return ToolSpec(
name="netx_aggregate_alarms",
description=(
"按 severity_norm / alarm_code / ne_name 对 netx 告警做聚合统计(读 netx API,不落直连 PG)。"
"batch_id 可选:不传则限定为 netx 当前最新导入批次(与告警查询默认语义一致)。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string"},
"group_by": {
"type": "string",
"enum": ["severity_norm", "alarm_code", "ne_name"],
"default": "severity_norm",
},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "aggregate", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_run_diagnostics_tool() -> ToolSpec:
"""Diagnostics summary (same stats netx uses for dashboard slices)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
resolution = "explicit"
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
resolution = "latest_import"
out = _http_json("GET", "/v1/diagnostics", params={"batch_id": batch_id})
if out.get("ok") and resolution == "latest_import":
out = {**out, "batch_id_used": batch_id, "batch_resolution": resolution}
return out
return ToolSpec(
name="netx_run_diagnostics",
description=(
"读取 netx /v1/diagnostics 统计摘要(批次维度:级别分布、Top 告警码/网元、协议归类等)。"
"batch_id 可选:不传则使用 netx 当前最新导入批次。"
),
parameters={
"type": "object",
"properties": {"batch_id": {"type": "string", "description": "批次 ID;省略则用最新导入批次"}},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "diagnostics", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_list_import_batches_tool() -> ToolSpec:
"""List recent import batches (newest first)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
limit = max(1, min(100, int(args.get("limit") or 20)))
return _http_json("GET", "/v1/batches", params={"limit": limit})
return ToolSpec(
name="netx_list_import_batches",
description="列出 netx 最近导入批次(与 UI 一致,按创建时间降序)。用于核对 batch_id 或确认「最新」批次。",
parameters={
"type": "object",
"properties": {
"limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "batches", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_list_alarm_fields_tool() -> ToolSpec:
"""List alarms_norm columns from netx."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
_ = args
return _http_json("GET", "/v1/alarms/fields", params=None)
return ToolSpec(
name="netx_list_alarm_fields",
description="列出 netx alarms_norm 表所有字段名(供自由查询时选择字段/确认可用字段)。",
parameters={
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "schema", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_query_alarms_raw_tool() -> ToolSpec:
"""Power query alarms_norm with all fields."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
explicit = str(args.get("batch_id") or "").strip()
batch_id = explicit
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
page = max(1, int(args.get("page") or 1))
page_size = min(200, max(1, int(args.get("page_size") or 50)))
params: dict[str, Any] = {
"batch_id": batch_id,
"page": page,
"page_size": page_size,
}
if str(args.get("alarm_code") or "").strip():
params["alarm_code"] = str(args.get("alarm_code")).strip()
if str(args.get("ne_name") or "").strip():
params["ne_name"] = str(args.get("ne_name")).strip()
if str(args.get("severity") or "").strip():
params["severity"] = str(args.get("severity")).strip()
if str(args.get("q") or "").strip():
params["q"] = str(args.get("q")).strip()
if str(args.get("order_by") or "").strip():
params["order_by"] = str(args.get("order_by")).strip()
if str(args.get("order") or "").strip():
params["order"] = str(args.get("order")).strip()
return _http_json("GET", "/v1/alarms/raw", params=params)
return ToolSpec(
name="netx_query_alarms_raw",
description=(
"自由查询 netx alarms_norm:返回所有字段。"
"batch_id 可选(省略则使用最新导入批次);支持 severity/alarm_code/ne_name/q 过滤与分页;"
"order_by 仅允许 id/alarm_time/severity_norm/ne_name/alarm_code。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string", "description": "批次 ID;省略则用最新导入批次"},
"severity": {"type": "string"},
"alarm_code": {"type": "string"},
"ne_name": {"type": "string"},
"q": {"type": "string", "description": "自由文本 contains(alarm_code/ne_name/description/service)"},
"order_by": {"type": "string", "enum": ["id", "alarm_time", "severity_norm", "ne_name", "alarm_code"]},
"order": {"type": "string", "enum": ["asc", "desc"]},
"page": {"type": "integer", "minimum": 1, "default": 1},
"page_size": {"type": "integer", "minimum": 1, "maximum": 200, "default": 50},
},
"required": [],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "alarms", "power_query", "read_only"}),
risk_level="low",
read_only=True,
)
def netx_sql_query_tool() -> ToolSpec:
"""Execute read-only SQL on netx (server enforced SELECT-only)."""
def handler(args: dict[str, Any]) -> dict[str, Any]:
batch_id = str(args.get("batch_id") or "").strip()
if not batch_id:
res = _resolve_latest_import_batch_id()
if not res.get("ok"):
return res
batch_id = str(res.get("batch_id") or "")
sql = str(args.get("sql") or "").strip()
limit = max(1, min(2000, int(args.get("limit") or 200)))
if not sql:
return {"ok": False, "error": "sql_required"}
base = _netx_base_url()
url = f"{base}/v1/sql/query"
try:
with httpx.Client(timeout=60.0) as client:
resp = client.post(url, json={"sql": sql, "batch_id": batch_id, "limit": limit}, headers=_netx_headers())
text = resp.text
if not resp.is_success:
return {"ok": False, "error": f"netx_http_{resp.status_code}", "detail": text[:800]}
data = resp.json() if text else {}
return {"ok": True, "data": data if isinstance(data, dict) else {"raw": data}}
except Exception as exc:
return {"ok": False, "error": "netx_request_failed", "detail": str(exc)[:800]}
return ToolSpec(
name="netx_sql_query",
description=(
"在 netx 上执行只读 SQL(服务端强制 SELECT-only、单语句、必须包含 :batch_id 参数,并强制 limit)。"
"用于自由组合查询;建议先用 netx_list_alarm_fields 确认可用字段。"
),
parameters={
"type": "object",
"properties": {
"batch_id": {"type": "string", "description": "批次 ID;省略则用最新导入批次"},
"sql": {"type": "string", "description": "必须是 SELECT,且包含 :batch_id 占位符"},
"limit": {"type": "integer", "minimum": 1, "maximum": 2000, "default": 200},
},
"required": ["sql"],
"additionalProperties": False,
},
handler=handler,
tags=frozenset({"netx", "ops", "sql", "power_query", "read_only"}),
risk_level="low",
read_only=True,
)
__all__ = [
"netx_query_alarms_tool",
"netx_aggregate_alarms_tool",
"netx_run_diagnostics_tool",
"netx_list_import_batches_tool",
"netx_list_alarm_fields_tool",
"netx_query_alarms_raw_tool",
"netx_sql_query_tool",
]

View file

@ -0,0 +1,9 @@
---
title: fallback_ollama_failure_en
summary: ollama transport failure banner in English
read_when: ollama transport exception
---
**Could not reach the Ollama / compatible endpoint:** `{{error_type}}: {{error_message}}`
_Falling back to the built-in rule engine for this reply._

View file

@ -0,0 +1,9 @@
---
title: fallback_ollama_failure_zh
summary: ollama transport failure banner in Chinese
read_when: ollama transport exception
---
**无法连接本地 Ollama(或兼容接口):** `{{error_type}}: {{error_message}}`
_本次回答已改用内置规则引擎兜底。_

View file

@ -0,0 +1,11 @@
---
title: fallback_openai_missing_key_user_en
summary: user-facing message when openai key is missing
read_when: openai mode selected but no api key
---
**Cannot use this profile:** no API Key is set for the OpenAI-compatible endpoint, and `OPENAI_API_KEY` is not in the environment.
Add a key in **Settings** and save, or switch to the built-in **Local Ollama (default)** profile.
_No request was sent to the model service._

View file

@ -0,0 +1,11 @@
---
title: fallback_openai_missing_key_user_zh
summary: user-facing message when openai key is missing
read_when: openai mode selected but no api key
---
**当前配置无法接入模型:** 本配置为 OpenAI / 兼容 API,但未填写 API Key,且环境中也没有 `OPENAI_API_KEY`。
请在「设置」中填写 Key 并保存,或切换到内置的「本地 Ollama(默认)」配置后再试。
_本次未向模型服务发送请求。_

View file

@ -0,0 +1,9 @@
---
title: fallback_openai_transport_error_en
summary: generic OpenAI-compatible transport error in English
read_when: model request failed
---
**Model request failed:** `{{error_type}}: {{error_message}}`
Check API key, base URL, and network, then try again.{{extra_tail}}

View file

@ -0,0 +1,9 @@
---
title: fallback_openai_transport_error_zh
summary: generic OpenAI-compatible transport error in Chinese
read_when: model request failed
---
**调用模型失败:** `{{error_type}}: {{error_message}}`
请检查 API Key、Base URL 与网络后重试。{{extra_tail}}

View file

@ -0,0 +1,9 @@
---
title: fallback_openai_transport_oversized_en
summary: oversized payload failure in English
read_when: model request too large
---
**Model request failed (message too large):** `{{error_type}}: {{error_message}}`
Common causes: oversized tools schema or large tool results in history. Tune `AIA_OPENAI_TOOLS_MAX_JSON_CHARS`, reduce MCP tools, or narrow the query.

View file

@ -0,0 +1,9 @@
---
title: fallback_openai_transport_oversized_zh
summary: oversized payload failure in Chinese
read_when: model request too large
---
**调用模型失败(单条消息过长):** `{{error_type}}: {{error_message}}`
常见原因:tools 负载过大或 tool 返回过长。可调整 `AIA_OPENAI_TOOLS_MAX_JSON_CHARS`,或减少 MCP / 缩小查询范围后重试。

View file

@ -0,0 +1,7 @@
---
title: fallback_openclaw_runtime_error_en
summary: fallback text when openclaw runtime failed
read_when: gateway exception path
---
oclaw runtime error: executor missing model/tools

View file

@ -0,0 +1,7 @@
---
title: fallback_oclaw_runtime_error_zh
summary: fallback text when oclaw runtime failed
read_when: gateway exception path
---
oclaw 运行失败:执行器缺少 model/tools

View file

@ -0,0 +1,7 @@
---
title: fallback_task_queued_en
summary: User-visible text when async task is enqueued.
read_when: gateway async_task mode
---
Task queued, task_id={{task_id}}

View file

@ -0,0 +1,7 @@
---
title: fallback_task_queued_zh
summary: User-visible text when async task is enqueued.
read_when: gateway async_task mode
---
任务已入队,task_id={{task_id}}

View file

@ -0,0 +1,7 @@
---
title: image_default_edit_prompt_zh
summary: Default image editing prompt text.
read_when: image prompt is empty
---
请基于输入图片和用户要求完成图像编辑,并返回结果图片。

View file

@ -0,0 +1,25 @@
---
title: oclaw_router_decide_route
summary: LLM JSON routing prompt for sync vs async oclaw turns (Chinese only).
read_when: AIA_OCLAW_ROUTER_MODE=llm_json
---
# 路由决策(结构化输出)
你需要判断当前用户输入应采用哪种执行模式:
- `sync_direct`:当前请求内直接回复(默认)。
- `async_task`:明确是多步骤后台流程(例如“总结并发送”)、或输入极大且带附件。
## 输入
- 用户文本:
```
{{user_text}}
```
- 是否有附件:`{{has_attachments}}`
## 输出(严格)
只返回一行 JSON,不要 Markdown、不要解释:
`{"mode":"sync_direct"|"async_task","reason":"<简短原因>"}`
默认倾向 `sync_direct`,只有明确需要异步才选 `async_task`。

View file

@ -0,0 +1,27 @@
---
title: default_runtime_system_en
summary: Default system prompt for general runtime (English template).
read_when: agent runtime start
---
# Identity
You are a general-purpose AI assistant.
## Input Constraints
- Answer in the same language as the user.
## Execution Rules
- When external data or actions are needed, prefer the tools provided by the system.
- Tool calls are carried by the platform protocol; do not paste tool-protocol JSON in the user-visible reply.
## Output Format
- Produce user-readable text; conclusions first, steps concise.
## Safety
- Do not fabricate tool results.
- When uncertain, state limits and ask for missing information.

View file

@ -0,0 +1,22 @@
---
title: default_runtime_system_zh
summary: Default system prompt for general runtime.
read_when: agent runtime start
---
# Identity
你是一个通用 AI 助手。
## Input Constraints
- 使用用户输入的语言回答。
## Execution Rules
- 当需要外部数据或执行动作时,优先调用系统提供的工具。
- 工具调用由平台协议承载,不要在正文里输出工具协议 JSON。
## Output Format
- 直接输出用户可读内容,结论优先,步骤简洁。
## Safety
- 不要伪造工具结果。
- 不确定时先说明边界并请求补充信息。

View file

@ -0,0 +1,10 @@
---
title: oclaw_runtime_memory_context_block
summary: Runtime markdown wrapper for memory context.
read_when: assembling runtime memory context
---
[short_term_digest]
{{short_term_block}}
[semantic_memory_hits]
{{semantic_hits_block}}

View file

@ -0,0 +1,7 @@
---
title: oclaw_runtime_project_context_block
summary: Inject workspace bootstrap files into system prompt project context.
read_when: oclaw system assembly with workspace context
---
[project_context]
{{project_context}}

View file

@ -0,0 +1,9 @@
---
title: oclaw_runtime_system_with_memory
summary: Runtime system prompt wrapper with injected memory context.
read_when: oclaw system assembly
---
{{system_prompt}}
[memory_context]
{{memory_context}}

View file

@ -0,0 +1,6 @@
---
title: oclaw_runtime_system_with_skills
summary: System prompt body plus optional skills catalog XML.
read_when: oclaw direct loop with skill runtime
---
{{system_body}}{{skills_catalog}}

View file

@ -0,0 +1,8 @@
---
title: image_attachment_meta_block
summary: Metadata-only image attachment block for LLM message context.
read_when: building user message content
---
--- Image Attachment (meta only) ---
{{meta_line}}

View file

@ -0,0 +1,9 @@
---
title: text_attachment_wrap_block
summary: Wrapper for text file attachments in LLM context.
read_when: building user message content
---
--- File: {{name}} ---
{{content}}
--- End of File ---

View file

@ -0,0 +1,8 @@
---
title: tool_result_unpaired_block
summary: Downgraded tool result block when call id pairing is broken.
read_when: building assistant fallback message
---
[{{tag}}]
{{payload}}

View file

@ -90,6 +90,10 @@ def _workspace_signature() -> tuple[Any, ...]:
for item in sorted(root.iterdir(), key=lambda p: p.name.lower()):
if not item.is_dir():
continue
# Internal workspace directories (single underscore prefix) are not experts.
# Example: `_system` is used for builtin prompt templates.
if item.name.startswith("_"):
continue
if item.name.startswith("__"):
continue
eid = normalize_expert_id(item.name)
@ -159,6 +163,10 @@ def list_experts() -> list[dict[str, Any]]:
for item in sorted(root.iterdir(), key=lambda p: p.name.lower()):
if not item.is_dir():
continue
# Internal workspace directories (single underscore prefix) are not experts.
# Example: `_system` is used for builtin prompt templates.
if item.name.startswith("_"):
continue
eid = normalize_expert_id(item.name)
if not eid:
continue

View file

@ -10,3 +10,13 @@
## 输出格式:
- 先结论,再给证据与最小修复步骤。
## netx 明细与统计(内部工具)
每轮对话 **system 末尾会自动附带当前最新导入的 batch_id 锚点**(类似附件里的 id),无需你先「查列表再找 batch」。涉及告警/统计时仍应用工具拉明细。
- **省略 batch_id**:`netx_query_alarms`、`netx_aggregate_alarms`、`netx_run_diagnostics` 也可不传 batch_id,此时与锚点一致(最新导入批次)。
- **netx_list_import_batches**:仅在需要多看几个历史批次时使用。
- **netx_query_alarms** / **netx_aggregate_alarms** / **netx_run_diagnostics**:用锚点中的 batch_id(或省略 batch_id)获取明细与诊断。
工具走 netx(`OCLAW_NETX_BASE_URL` / `OCLAW_NETX_API_TOKEN`)。关闭自动锚点:环境变量 `OCLAW_OPS_NETX_CONTEXT_INJECT=0`。