mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-09 03:30:48 +08:00
重构仓库目录为统一的 runtime 分层并清理历史 openclaw 残留。
本次迁移将网关/通道/工具/技能/脚本与协议资源集中到新结构,统一路径常量与脚本转发机制,减少顶层噪音并保证运行与测试行为一致。 Made-with: Cursor
This commit is contained in:
parent
ba3836f00f
commit
4a23b715a2
498 changed files with 2760 additions and 2200 deletions
5
runtime/operations/__init__.py
Normal file
5
runtime/operations/__init__.py
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from .main import main
|
||||
|
||||
__all__ = ["main"]
|
||||
7
runtime/operations/__main__.py
Normal file
7
runtime/operations/__main__.py
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from .main import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
63
runtime/operations/main.py
Normal file
63
runtime/operations/main.py
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from oclaw.runtime.operations.memory import register_memory_parser
|
||||
from oclaw.runtime.operations.providers.registry import build_channel_registry
|
||||
from oclaw.runtime.operations.stack import register_stack_parser
|
||||
|
||||
|
||||
def _cmd_gateway_start(args: argparse.Namespace) -> int:
|
||||
if args.host:
|
||||
os.environ["AIA_ASSISTANT_GATEWAY_HOST"] = args.host
|
||||
if args.port is not None:
|
||||
os.environ["AIA_ASSISTANT_GATEWAY_PORT"] = str(args.port)
|
||||
from oclaw.runtime.operations.mcp_env import apply_gateway_mcp_env_to_os
|
||||
|
||||
apply_gateway_mcp_env_to_os()
|
||||
from oclaw.interfaces.http.fastapi_app import main as fastapi_main
|
||||
|
||||
return fastapi_main()
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
p = argparse.ArgumentParser(prog="python -m oclaw.runtime.operations", description="Unified operational CLI")
|
||||
root_sub = p.add_subparsers(dest="root_cmd", required=True)
|
||||
|
||||
registry = build_channel_registry()
|
||||
channel = root_sub.add_parser("channel", help="Channel operations")
|
||||
channel_sub = channel.add_subparsers(dest="channel_name", required=True)
|
||||
channel_list = channel_sub.add_parser("list", help="List available channel providers")
|
||||
channel_list.set_defaults(func=lambda _a: (print("channels=" + ",".join(sorted(registry.keys()))) or 0))
|
||||
for provider in registry.values():
|
||||
provider.register(channel_sub)
|
||||
|
||||
gateway = root_sub.add_parser("gateway", help="Gateway operations")
|
||||
gateway_sub = gateway.add_subparsers(dest="gateway_cmd", required=True)
|
||||
gateway_start = gateway_sub.add_parser("start", help="Start inbound HTTP gateway")
|
||||
gateway_start.add_argument("--host", default=None, help="Bind host")
|
||||
gateway_start.add_argument("--port", type=int, default=None, help="Bind port")
|
||||
gateway_start.set_defaults(func=_cmd_gateway_start)
|
||||
|
||||
register_memory_parser(root_sub)
|
||||
register_stack_parser(root_sub)
|
||||
return p
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
if argv is None:
|
||||
argv = list(sys.argv[1:])
|
||||
if argv and len(argv) >= 1 and argv[0] == "wecom":
|
||||
argv = ["channel", "wecom", *argv[1:]]
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
func = getattr(args, "func", None)
|
||||
if not callable(func):
|
||||
parser.print_help()
|
||||
return 2
|
||||
return int(func(args) or 0)
|
||||
|
||||
|
||||
__all__ = ["main"]
|
||||
97
runtime/operations/mcp_env.py
Normal file
97
runtime/operations/mcp_env.py
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
from __future__ import annotations
|
||||
|
||||
"""MCP 相关进程环境:默认 allowlist + 可选本地 env 文件(首选 `oclaw/_local/mcp_local.env`)。"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from oclaw.platform.config.paths import PROJECT_ROOT, db_path
|
||||
|
||||
_DEFAULT_ALLOWLIST = (
|
||||
"BRAVE_API_KEY,GOOGLE_OAUTH_CREDENTIALS,GOOGLE_CALENDAR_MCP_TOKEN_PATH,"
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN,CONTEXT7_API_KEY"
|
||||
)
|
||||
|
||||
|
||||
def mcp_env_allowlist_keys() -> list[str]:
|
||||
raw = str(os.getenv("AIA_MCP_ENV_ALLOWLIST") or "").strip()
|
||||
if not raw:
|
||||
return [x.strip() for x in _DEFAULT_ALLOWLIST.split(",") if x.strip()]
|
||||
return [x.strip() for x in raw.split(",") if x.strip()]
|
||||
|
||||
|
||||
def _parse_env_file(path: Path) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
if not path.is_file():
|
||||
return out
|
||||
try:
|
||||
raw = path.read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return out
|
||||
for line in raw.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if "=" not in line:
|
||||
continue
|
||||
k, _, v = line.partition("=")
|
||||
k = k.strip()
|
||||
v = v.strip().strip('"').strip("'")
|
||||
if k:
|
||||
out[k] = _expand_env_value(v)
|
||||
return out
|
||||
|
||||
|
||||
def _expand_env_value(v: str) -> str:
|
||||
s = v.strip()
|
||||
if "${PROJECT_ROOT}" in s:
|
||||
rel = s.split("${PROJECT_ROOT}", 1)[1].lstrip("/\\")
|
||||
s = str((PROJECT_ROOT / rel).resolve())
|
||||
return os.path.expandvars(s)
|
||||
|
||||
|
||||
def _mcp_local_env_paths_in_load_order() -> list[Path]:
|
||||
return [
|
||||
Path(db_path()).resolve().parent / "mcp_local.env",
|
||||
(PROJECT_ROOT / "oclaw" / "_local" / "mcp_local.env").resolve(),
|
||||
]
|
||||
|
||||
|
||||
def mcp_local_env_merged() -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for p in _mcp_local_env_paths_in_load_order():
|
||||
if p.is_file():
|
||||
out.update(_parse_env_file(p))
|
||||
return out
|
||||
|
||||
|
||||
def mcp_local_env_file_path() -> Path:
|
||||
return (PROJECT_ROOT / "oclaw" / "_local" / "mcp_local.env").resolve()
|
||||
|
||||
|
||||
def gateway_mcp_env_extras() -> dict[str, str]:
|
||||
extra: dict[str, str] = {}
|
||||
has_aia = str(os.getenv("AIA_MCP_ENV_ALLOWLIST") or "").strip()
|
||||
if not has_aia:
|
||||
extra["AIA_MCP_ENV_ALLOWLIST"] = _DEFAULT_ALLOWLIST
|
||||
file_vals = mcp_local_env_merged()
|
||||
for k, v in file_vals.items():
|
||||
if not v.strip():
|
||||
continue
|
||||
if not str(os.getenv(k) or "").strip():
|
||||
extra[k] = v
|
||||
return extra
|
||||
|
||||
|
||||
def apply_gateway_mcp_env_to_os() -> None:
|
||||
for k, v in gateway_mcp_env_extras().items():
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
__all__ = [
|
||||
"apply_gateway_mcp_env_to_os",
|
||||
"gateway_mcp_env_extras",
|
||||
"mcp_env_allowlist_keys",
|
||||
"mcp_local_env_file_path",
|
||||
"mcp_local_env_merged",
|
||||
]
|
||||
109
runtime/operations/mcp_registry_export.py
Normal file
109
runtime/operations/mcp_registry_export.py
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
"""Build a reinstallable MCP JSON from SQLite and persist under ``oclaw/_local/`` for migration."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import warnings
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from oclaw.platform.config.paths import PROJECT_ROOT
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
from oclaw.runtime.tools.mcp.registry import McpRegistry
|
||||
|
||||
_EXPORT_FILENAME = "mcp_registry_migrated.json"
|
||||
_LOCAL_DIR = (PROJECT_ROOT / "oclaw" / "_local").resolve()
|
||||
_EXPORT_PATH = (_LOCAL_DIR / _EXPORT_FILENAME).resolve()
|
||||
|
||||
|
||||
def mcp_migrated_json_path() -> Path:
|
||||
return _EXPORT_PATH
|
||||
|
||||
|
||||
def _collapse_entry_arg(arg: str, root: Path) -> str:
|
||||
"""Rewrite absolute / repo-relative paths to ``__REPO_ROOT__/...`` when they exist on disk under root.
|
||||
|
||||
Skips npx flags (``-y``) and tokens that are not an existing file or directory, so package names
|
||||
(e.g. ``mcp-sqlite``, ``@upstash/foo``) are not mistaken for paths.
|
||||
"""
|
||||
t = (arg or "").strip()
|
||||
if not t or t.startswith("__REPO_ROOT__") or t.startswith("-"):
|
||||
return str(arg)
|
||||
r = root.resolve()
|
||||
a = Path(os.path.expanduser(t))
|
||||
if not a.is_absolute():
|
||||
a = (r / t).resolve()
|
||||
else:
|
||||
a = a.resolve()
|
||||
if not a.exists():
|
||||
return str(arg)
|
||||
try:
|
||||
rel = a.relative_to(r)
|
||||
except ValueError:
|
||||
return str(arg)
|
||||
return "__REPO_ROOT__/" + rel.as_posix()
|
||||
|
||||
|
||||
def _collapse_entry_args(args: list[str], root: Path) -> list[str]:
|
||||
return [_collapse_entry_arg(x, root) for x in args]
|
||||
|
||||
|
||||
def build_mcp_install_export_document(store: SqliteStore) -> dict[str, Any]:
|
||||
rows = McpRegistry(store).list_servers(enabled_only=False)
|
||||
root = PROJECT_ROOT.resolve()
|
||||
servers: list[dict[str, Any]] = []
|
||||
for r in rows:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
raw_args = r.get("entry_args")
|
||||
if isinstance(raw_args, list):
|
||||
entry_args = _collapse_entry_args([str(x) for x in raw_args if str(x).strip()], root)
|
||||
else:
|
||||
entry_args = []
|
||||
es = r.get("env_schema")
|
||||
env_schema = es if isinstance(es, dict) else {}
|
||||
perms = r.get("required_permissions")
|
||||
if not isinstance(perms, list):
|
||||
perms = []
|
||||
servers.append(
|
||||
{
|
||||
"server_id": str(r.get("server_id") or ""),
|
||||
"source_type": str(r.get("source_type") or ""),
|
||||
"source_ref": str(r.get("source_ref") or ""),
|
||||
"version": str(r.get("version") or ""),
|
||||
"entry_command": str(r.get("entry_command") or ""),
|
||||
"entry_args": entry_args,
|
||||
"env_schema": env_schema,
|
||||
"required_permissions": [str(x) for x in perms if str(x).strip()],
|
||||
"risk_level": str(r.get("risk_level") or "high"),
|
||||
"enabled": bool(r.get("enabled")),
|
||||
"timeout_s": float(r.get("timeout_s") or 30.0),
|
||||
"dry_run": False,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"_comment": "管理台导出 / 新安装后自动落盘。可粘到「Install from JSON」;`__REPO_ROOT__/` 在管理台与 seed 中展开为仓库根。已存在路径会写成占位符,其余参数保持原样。",
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||||
"servers": servers,
|
||||
}
|
||||
|
||||
|
||||
def persist_mcp_migrated_file(store: SqliteStore) -> str | None:
|
||||
"""Write ``oclaw/_local/mcp_registry_migrated.json``. Fails open (warn only). Returns path or None."""
|
||||
try:
|
||||
mcp_migrated_json_path().parent.mkdir(parents=True, exist_ok=True)
|
||||
doc = build_mcp_install_export_document(store)
|
||||
path = mcp_migrated_json_path()
|
||||
path.write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
return str(path)
|
||||
except OSError as exc:
|
||||
warnings.warn(f"mcp_registry_migrated write failed: {exc}", RuntimeWarning, stacklevel=1)
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"build_mcp_install_export_document",
|
||||
"mcp_migrated_json_path",
|
||||
"persist_mcp_migrated_file",
|
||||
]
|
||||
162
runtime/operations/memory.py
Normal file
162
runtime/operations/memory.py
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _now_date() -> dt.date:
|
||||
return dt.date.today()
|
||||
|
||||
|
||||
def _iso_week_label(day: dt.date) -> str:
|
||||
year, week, _weekday = day.isocalendar()
|
||||
return f"{year}-W{week:02d}"
|
||||
|
||||
|
||||
def _ensure_dirs(base_dir: Path) -> None:
|
||||
for name in ("Projects", "Areas", "Resources", "Archives", "Inbox", "runs"):
|
||||
(base_dir / name).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def _count_notes(path: Path) -> int:
|
||||
if not path.exists():
|
||||
return 0
|
||||
count = 0
|
||||
for item in path.rglob("*.md"):
|
||||
if item.name.lower() == "readme.md":
|
||||
continue
|
||||
if "templates" in item.parts or "runs" in item.parts:
|
||||
continue
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _recommend_new_cards(inbox_count: int, backlog_count: int, fresh_resources: int) -> int:
|
||||
target = 10
|
||||
if backlog_count > 0:
|
||||
target -= min(6, backlog_count // 20)
|
||||
if inbox_count > 20:
|
||||
target -= 2
|
||||
if fresh_resources >= 5 and backlog_count < 20:
|
||||
target += 1
|
||||
return max(3, min(10, target))
|
||||
|
||||
|
||||
def _build_focus_order(projects: int, areas: int, resources: int) -> list[str]:
|
||||
ranked = [("Projects", projects * 3), ("Areas", areas * 2), ("Resources", resources)]
|
||||
ranked.sort(key=lambda x: x[1], reverse=True)
|
||||
return [name for name, score in ranked if score > 0][:3]
|
||||
|
||||
|
||||
def _parse_date(text: str | None) -> dt.date:
|
||||
if not text:
|
||||
return _now_date()
|
||||
return dt.date.fromisoformat(text)
|
||||
|
||||
|
||||
def _cmd_memory_status(args: argparse.Namespace) -> int:
|
||||
base = Path(args.base_dir).resolve()
|
||||
_ensure_dirs(base)
|
||||
projects = _count_notes(base / "Projects")
|
||||
areas = _count_notes(base / "Areas")
|
||||
resources = _count_notes(base / "Resources")
|
||||
archives = _count_notes(base / "Archives")
|
||||
inbox = _count_notes(base / "Inbox")
|
||||
suggested = _recommend_new_cards(inbox, int(args.review_backlog), resources)
|
||||
focus = _build_focus_order(projects, areas, resources)
|
||||
print(f"base_dir={base}")
|
||||
print(f"projects={projects} areas={areas} resources={resources} archives={archives} inbox={inbox}")
|
||||
print(f"suggested_new_cards_per_day={suggested}")
|
||||
print("focus_topics=" + (",".join(focus) if focus else "Resources"))
|
||||
return 0
|
||||
|
||||
|
||||
def _cmd_memory_daily(args: argparse.Namespace) -> int:
|
||||
base = Path(args.base_dir).resolve()
|
||||
_ensure_dirs(base)
|
||||
day = _parse_date(args.date)
|
||||
projects = _count_notes(base / "Projects")
|
||||
areas = _count_notes(base / "Areas")
|
||||
resources = _count_notes(base / "Resources")
|
||||
inbox = _count_notes(base / "Inbox")
|
||||
suggested = _recommend_new_cards(inbox, int(args.review_backlog), resources)
|
||||
focus = _build_focus_order(projects, areas, resources)
|
||||
focus_topic = args.focus or (focus[0] if focus else "Resources")
|
||||
out = base / "runs" / f"daily-{day.isoformat()}.md"
|
||||
text = (
|
||||
f"# Daily Memory Run ({day.isoformat()})\n\n"
|
||||
f"- Focus topic: `{focus_topic}`\n"
|
||||
f"- Suggested new cards today: `{suggested}`\n"
|
||||
f"- Current inbox notes: `{inbox}`\n"
|
||||
f"- Review backlog input: `{int(args.review_backlog)}`\n\n"
|
||||
"## Auto Steps\n\n"
|
||||
"1. Capture 3-5 high-value items into `Inbox`.\n"
|
||||
"2. Distill 1-3 items into atomic notes under `Resources`.\n"
|
||||
"3. Convert notes into Q/A or cloze cards (respect suggested limit).\n"
|
||||
"4. Produce one output (summary/answer/code note).\n\n"
|
||||
"## Smart Suggestions\n\n"
|
||||
f"- Priority order now: `{', '.join(focus) if focus else 'Resources'}`\n"
|
||||
"- If reviews feel overloaded, reduce new cards before skipping due reviews.\n"
|
||||
"- If inbox keeps growing for 2+ days, process inbox first before new captures.\n"
|
||||
)
|
||||
out.write_text(text, encoding="utf-8")
|
||||
print(f"created={out}")
|
||||
return 0
|
||||
|
||||
|
||||
def _cmd_memory_weekly(args: argparse.Namespace) -> int:
|
||||
base = Path(args.base_dir).resolve()
|
||||
_ensure_dirs(base)
|
||||
day = _parse_date(args.date)
|
||||
week_label = _iso_week_label(day)
|
||||
projects = _count_notes(base / "Projects")
|
||||
areas = _count_notes(base / "Areas")
|
||||
resources = _count_notes(base / "Resources")
|
||||
archives = _count_notes(base / "Archives")
|
||||
inbox = _count_notes(base / "Inbox")
|
||||
suggested = _recommend_new_cards(inbox, int(args.review_backlog), resources)
|
||||
focus = _build_focus_order(projects, areas, resources)
|
||||
out = base / "runs" / f"weekly-{week_label}.md"
|
||||
text = (
|
||||
f"# Weekly Memory Review ({week_label})\n\n"
|
||||
f"- Run date: `{day.isoformat()}`\n"
|
||||
f"- Suggested next-week new cards/day: `{suggested}`\n\n"
|
||||
"## Snapshot\n\n"
|
||||
f"- Projects notes: `{projects}`\n"
|
||||
f"- Areas notes: `{areas}`\n"
|
||||
f"- Resources notes: `{resources}`\n"
|
||||
f"- Archives notes: `{archives}`\n"
|
||||
f"- Inbox notes: `{inbox}`\n\n"
|
||||
"## Fixed Review Checklist\n\n"
|
||||
"- [ ] Inbox zero\n- [ ] Linking/backlinks completion\n- [ ] Move inactive notes to Archives\n- [ ] Tune next-week card load\n\n"
|
||||
"## Auto Focus for Next Week\n\n"
|
||||
f"- Top topics: `{', '.join(focus) if focus else 'Resources'}`\n"
|
||||
"- Keep new cards within 3-10/day and adjust by real review pressure.\n"
|
||||
)
|
||||
out.write_text(text, encoding="utf-8")
|
||||
print(f"created={out}")
|
||||
return 0
|
||||
|
||||
|
||||
def register_memory_parser(root_sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
|
||||
memory = root_sub.add_parser("memory", help="Memory system automation")
|
||||
memory_sub = memory.add_subparsers(dest="memory_cmd", required=True)
|
||||
|
||||
status = memory_sub.add_parser("status", help="Show memory workload status")
|
||||
status.add_argument("--base-dir", default="oclaw/docs/memory-system", help="Memory system base directory")
|
||||
status.add_argument("--review-backlog", type=int, default=0, help="Current due review backlog")
|
||||
status.set_defaults(func=_cmd_memory_status)
|
||||
|
||||
daily = memory_sub.add_parser("daily", help="Generate today's automated memory run")
|
||||
daily.add_argument("--base-dir", default="oclaw/docs/memory-system", help="Memory system base directory")
|
||||
daily.add_argument("--date", default=None, help="Run date in YYYY-MM-DD")
|
||||
daily.add_argument("--focus", default=None, help="Override focus topic")
|
||||
daily.add_argument("--review-backlog", type=int, default=0, help="Current due review backlog")
|
||||
daily.set_defaults(func=_cmd_memory_daily)
|
||||
|
||||
weekly = memory_sub.add_parser("weekly", help="Generate weekly review run sheet")
|
||||
weekly.add_argument("--base-dir", default="oclaw/docs/memory-system", help="Memory system base directory")
|
||||
weekly.add_argument("--date", default=None, help="Run date in YYYY-MM-DD")
|
||||
weekly.add_argument("--review-backlog", type=int, default=0, help="Current due review backlog")
|
||||
weekly.set_defaults(func=_cmd_memory_weekly)
|
||||
4
runtime/operations/providers/__init__.py
Normal file
4
runtime/operations/providers/__init__.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
from __future__ import annotations
|
||||
|
||||
__all__ = []
|
||||
|
||||
14
runtime/operations/providers/base.py
Normal file
14
runtime/operations/providers/base.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from argparse import _SubParsersAction
|
||||
|
||||
|
||||
class ChannelProvider(ABC):
|
||||
@property
|
||||
@abstractmethod
|
||||
def name(self) -> str: ...
|
||||
|
||||
@abstractmethod
|
||||
def register(self, channel_subparsers: _SubParsersAction) -> None: ...
|
||||
|
||||
9
runtime/operations/providers/registry.py
Normal file
9
runtime/operations/providers/registry.py
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from .base import ChannelProvider
|
||||
from .wecom import WecomProvider
|
||||
|
||||
|
||||
def build_channel_registry() -> dict[str, ChannelProvider]:
|
||||
providers: list[ChannelProvider] = [WecomProvider()]
|
||||
return {p.name: p for p in providers}
|
||||
211
runtime/operations/providers/wecom.py
Normal file
211
runtime/operations/providers/wecom.py
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from argparse import _SubParsersAction
|
||||
|
||||
from oclaw.interfaces.channels.wecom.longconn_runner import run_forever as run_wecom_longconn
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
from .base import ChannelProvider
|
||||
|
||||
_CLEAR_KEYS = [
|
||||
"wecom_mode",
|
||||
"wecom_bot_id",
|
||||
"wecom_bot_secret",
|
||||
"wecom_corp_id",
|
||||
"wecom_agent_id",
|
||||
"wecom_agent_secret",
|
||||
"wecom_access_token_cache",
|
||||
"wecom_last_msg_ts",
|
||||
"wecom_last_from_user",
|
||||
"wecom_recent_from_users",
|
||||
"wecom_last_cmd",
|
||||
"wecom_last_unknown_cmd_payload",
|
||||
"wecom_last_raw_body",
|
||||
"wecom_last_raw_from_user",
|
||||
"wecom_last_parse_error",
|
||||
]
|
||||
|
||||
|
||||
def _store() -> SqliteStore:
|
||||
return SqliteStore(db_path())
|
||||
|
||||
|
||||
class WecomProvider(ChannelProvider):
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "wecom"
|
||||
|
||||
def register(self, channel_subparsers: _SubParsersAction) -> None:
|
||||
p = channel_subparsers.add_parser(self.name, help="WeCom channel operations")
|
||||
sub = p.add_subparsers(dest="channel_action", required=True)
|
||||
|
||||
start = sub.add_parser("start", help="Start WeCom long connection runner")
|
||||
start.add_argument("--mode", choices=["ws", "pull", "mock"], help="Runner mode")
|
||||
start.add_argument("--interval", type=float, help="Polling interval for non-ws modes")
|
||||
start.add_argument("--deliver-outbound", action=argparse.BooleanOptionalAction, default=None)
|
||||
start.add_argument("--ws-url", help="Override websocket URL")
|
||||
start.add_argument("--pull-url", help="Pull mode URL")
|
||||
start.set_defaults(func=self._cmd_start)
|
||||
|
||||
status = sub.add_parser("status", help="Show WeCom status snapshot")
|
||||
status.set_defaults(func=self._cmd_status)
|
||||
|
||||
doctor = sub.add_parser("doctor", help="Run lightweight environment checks")
|
||||
doctor.set_defaults(func=self._cmd_doctor)
|
||||
|
||||
config = sub.add_parser("config", help="Configure WeCom credentials")
|
||||
config_sub = config.add_subparsers(dest="config_cmd", required=True)
|
||||
conf_set = config_sub.add_parser("set", help="Set bot credentials (bot_api)")
|
||||
conf_set.add_argument("--bot-id", required=True)
|
||||
conf_set.add_argument("--bot-secret", required=True)
|
||||
conf_set.set_defaults(func=self._cmd_config_set)
|
||||
|
||||
auto_bind = sub.add_parser("auto-bind", help="Manage auto bind behavior")
|
||||
auto_bind.add_argument("action", choices=["on", "off", "show"])
|
||||
auto_bind.add_argument("tenant_name", nargs="?")
|
||||
auto_bind.add_argument("role", nargs="?")
|
||||
auto_bind.set_defaults(func=self._cmd_auto_bind)
|
||||
|
||||
smoke = sub.add_parser("smoke", help="Run smoke test")
|
||||
smoke.add_argument("--ws", action="store_true", help="Run bot websocket subscribe smoke")
|
||||
smoke.set_defaults(func=self._cmd_smoke)
|
||||
|
||||
create_bind = sub.add_parser("create-bind", help="Create a bind code")
|
||||
create_bind.add_argument("--role", default="member")
|
||||
create_bind.set_defaults(func=self._cmd_create_bind)
|
||||
|
||||
unbind = sub.add_parser("unbind", help="Clear local wecom config and wecom bindings")
|
||||
unbind.set_defaults(func=self._cmd_unbind)
|
||||
|
||||
switch = sub.add_parser("switch-bot", help="Switch to a new bot quickly")
|
||||
switch.add_argument("bot_id")
|
||||
switch.add_argument("bot_secret")
|
||||
switch.set_defaults(func=self._cmd_switch)
|
||||
|
||||
def _cmd_start(self, args: argparse.Namespace) -> int:
|
||||
if args.mode:
|
||||
os.environ["WECOM_LONGCONN_MODE"] = args.mode
|
||||
if args.interval is not None:
|
||||
os.environ["WECOM_LONGCONN_INTERVAL_SEC"] = str(args.interval)
|
||||
if args.deliver_outbound is not None:
|
||||
os.environ["WECOM_LONGCONN_DELIVER_OUTBOUND"] = "1" if args.deliver_outbound else "0"
|
||||
if args.ws_url:
|
||||
os.environ["WECOM_LONGCONN_WS_URL"] = args.ws_url
|
||||
if args.pull_url:
|
||||
os.environ["WECOM_LONGCONN_PULL_URL"] = args.pull_url
|
||||
return run_wecom_longconn()
|
||||
|
||||
def _cmd_status(self, _args: argparse.Namespace) -> int:
|
||||
from oclaw.runtime.operations.scripts.wecom_status import main as status_main
|
||||
|
||||
return status_main()
|
||||
|
||||
def _cmd_doctor(self, _args: argparse.Namespace) -> int:
|
||||
s = _store()
|
||||
print("ok=1")
|
||||
print(f"db_path={db_path()}")
|
||||
mode = str(s.get_setting("wecom_mode") or "").strip() or "auto"
|
||||
print(f"mode_setting={mode}")
|
||||
print(f"bot_id_set={1 if s.get_setting('wecom_bot_id') else 0}")
|
||||
print(f"bot_secret_set={1 if s.get_secret('wecom_bot_secret') else 0}")
|
||||
try:
|
||||
import websocket # type: ignore # noqa: F401
|
||||
|
||||
print("websocket_client=ok")
|
||||
except Exception as exc:
|
||||
print(f"websocket_client=missing ({type(exc).__name__})")
|
||||
return 0
|
||||
|
||||
def _cmd_config_set(self, args: argparse.Namespace) -> int:
|
||||
s = _store()
|
||||
s.set_setting("wecom_mode", "bot_api")
|
||||
s.set_setting("wecom_bot_id", args.bot_id)
|
||||
s.set_secret("wecom_bot_secret", args.bot_secret)
|
||||
s.delete_setting("wecom_access_token_cache")
|
||||
print("ok=1")
|
||||
print("mode=bot_api")
|
||||
return 0
|
||||
|
||||
def _cmd_auto_bind(self, args: argparse.Namespace) -> int:
|
||||
s = _store()
|
||||
if args.action == "show":
|
||||
print("ok=1")
|
||||
print(f"enabled={str(s.get_setting('wecom_auto_bind_enabled') or '1').strip()}")
|
||||
print(f"tenant_name={str(s.get_setting('wecom_auto_bind_tenant_name') or 'Team').strip() or 'Team'}")
|
||||
print(f"role={str(s.get_setting('wecom_auto_bind_role') or 'member').strip() or 'member'}")
|
||||
return 0
|
||||
enabled = "1" if args.action == "on" else "0"
|
||||
s.set_setting("wecom_auto_bind_enabled", enabled)
|
||||
if args.tenant_name:
|
||||
s.set_setting("wecom_auto_bind_tenant_name", args.tenant_name.strip())
|
||||
if args.role:
|
||||
s.set_setting("wecom_auto_bind_role", args.role.strip())
|
||||
print("ok=1")
|
||||
print(f"enabled={enabled}")
|
||||
return 0
|
||||
|
||||
def _cmd_smoke(self, args: argparse.Namespace) -> int:
|
||||
from oclaw.runtime.operations.scripts.wecom_smoke_test import main as smoke_main
|
||||
|
||||
old = sys.argv
|
||||
try:
|
||||
argv = ["wecom_smoke_test.py"]
|
||||
if args.ws:
|
||||
argv.append("--ws")
|
||||
sys.argv = argv
|
||||
return smoke_main()
|
||||
finally:
|
||||
sys.argv = old
|
||||
|
||||
def _cmd_create_bind(self, args: argparse.Namespace) -> int:
|
||||
s = _store()
|
||||
tenants = s.list_tenants(limit=1)
|
||||
if tenants:
|
||||
tenant_id = tenants[0]["id"]
|
||||
tenant_name = tenants[0]["name"]
|
||||
else:
|
||||
t = s.create_tenant("Team")
|
||||
tenant_id = t["id"]
|
||||
tenant_name = t["name"]
|
||||
role = args.role or "member"
|
||||
code = secrets.token_urlsafe(6)
|
||||
s.create_bind_code(tenant_id=tenant_id, role=role, code=code)
|
||||
print(f"tenant={tenant_name} ({tenant_id})")
|
||||
print(f"role={role}")
|
||||
print(f"bind_code={code}")
|
||||
print(f"wecom_cmd=bind {code}")
|
||||
return 0
|
||||
|
||||
def _cmd_unbind(self, _args: argparse.Namespace) -> int:
|
||||
s = _store()
|
||||
with s._connect() as conn:
|
||||
cur_ident = conn.execute("DELETE FROM channel_identity WHERE channel = ?", ("wecom",))
|
||||
ident_deleted = int(cur_ident.rowcount or 0)
|
||||
cur_sess = conn.execute("DELETE FROM channel_session WHERE channel = ?", ("wecom",))
|
||||
sess_deleted = int(cur_sess.rowcount or 0)
|
||||
for k in _CLEAR_KEYS:
|
||||
s.delete_setting(k)
|
||||
print("ok=1")
|
||||
print(f"deleted_channel_identity={ident_deleted}")
|
||||
print(f"deleted_channel_session={sess_deleted}")
|
||||
return 0
|
||||
|
||||
def _cmd_switch(self, args: argparse.Namespace) -> int:
|
||||
s = _store()
|
||||
s.set_setting("wecom_mode", "bot_api")
|
||||
s.set_setting("wecom_bot_id", args.bot_id)
|
||||
s.set_secret("wecom_bot_secret", args.bot_secret)
|
||||
for k in _CLEAR_KEYS:
|
||||
if k not in ("wecom_bot_id", "wecom_bot_secret", "wecom_mode"):
|
||||
s.delete_setting(k)
|
||||
print("ok=1")
|
||||
print("mode=bot_api")
|
||||
print(f"bot_id={args.bot_id}")
|
||||
print("next=python -m oclaw.runtime.operations channel wecom start")
|
||||
return 0
|
||||
|
||||
293
runtime/operations/runtime.py
Normal file
293
runtime/operations/runtime.py
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
|
||||
|
||||
def _runtime_file() -> Path:
|
||||
return Path(db_path()).resolve().parent / "ops_runtime_state.json"
|
||||
|
||||
|
||||
def _runtime_log_dir() -> Path:
|
||||
p = str(os.getenv("AIA_RUNTIME_LOG_DIR") or "").strip()
|
||||
if p:
|
||||
return Path(p).expanduser().resolve()
|
||||
return Path(db_path()).resolve().parent / "logs"
|
||||
|
||||
|
||||
def _read_state() -> dict[str, Any]:
|
||||
p = _runtime_file()
|
||||
if not p.exists():
|
||||
return {"services": {}}
|
||||
try:
|
||||
obj = json.loads(p.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {"services": {}}
|
||||
if not isinstance(obj, dict):
|
||||
return {"services": {}}
|
||||
if not isinstance(obj.get("services"), dict):
|
||||
obj["services"] = {}
|
||||
return obj
|
||||
|
||||
|
||||
def _write_state(state: dict[str, Any]) -> None:
|
||||
p = _runtime_file()
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _is_running(pid: int) -> bool:
|
||||
if pid <= 0:
|
||||
return False
|
||||
if os.name == "nt":
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["tasklist", "/FI", f"PID eq {int(pid)}", "/FO", "CSV", "/NH"],
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
)
|
||||
text = (out or "").strip().lower()
|
||||
return bool(text and "no tasks are running" not in text and "info:" not in text)
|
||||
except Exception:
|
||||
return False
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _python_bin() -> str:
|
||||
return sys.executable or "python"
|
||||
|
||||
|
||||
def _service_signature(name: str) -> str | None:
|
||||
n = str(name or "").strip().lower()
|
||||
if n == "gateway":
|
||||
return "-m oclaw.runtime.operations gateway start"
|
||||
if n == "ui":
|
||||
return "-m oclaw.runtime.operations ui start"
|
||||
if n.startswith("channel:"):
|
||||
ch = n.split(":", 1)[1].strip()
|
||||
if ch:
|
||||
return f"-m oclaw.runtime.operations channel {ch} start"
|
||||
return None
|
||||
|
||||
|
||||
def _find_pids_by_signature(signature: str) -> list[int]:
|
||||
sig = str(signature or "").strip().lower()
|
||||
if not sig:
|
||||
return []
|
||||
out: list[int] = []
|
||||
if os.name == "nt":
|
||||
try:
|
||||
raw = subprocess.check_output(
|
||||
["wmic", "process", "where", "name='python.exe'", "get", "ProcessId,CommandLine"],
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
for line in (raw or "").splitlines():
|
||||
txt = line.strip()
|
||||
if not txt or txt.lower().startswith("commandline"):
|
||||
continue
|
||||
parts = txt.rsplit(None, 1)
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
cmd, pid_s = parts[0].strip(), parts[1].strip()
|
||||
if not pid_s.isdigit():
|
||||
continue
|
||||
if sig in cmd.lower():
|
||||
out.append(int(pid_s))
|
||||
return out
|
||||
try:
|
||||
raw = subprocess.check_output(
|
||||
["ps", "-eo", "pid=,args="],
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
for line in (raw or "").splitlines():
|
||||
txt = line.strip()
|
||||
if not txt:
|
||||
continue
|
||||
parts = txt.split(None, 1)
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
pid_s, cmd = parts
|
||||
if not pid_s.isdigit():
|
||||
continue
|
||||
if sig in cmd.lower():
|
||||
out.append(int(pid_s))
|
||||
return out
|
||||
|
||||
|
||||
def _kill_pid_force(pid: int) -> bool:
|
||||
if pid <= 0:
|
||||
return False
|
||||
try:
|
||||
if os.name == "nt":
|
||||
subprocess.call(["taskkill", "/PID", str(pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
else:
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _cleanup_orphan_service_processes(name: str, *, keep_pids: set[int] | None = None) -> list[int]:
|
||||
sig = _service_signature(name)
|
||||
if not sig:
|
||||
return []
|
||||
keep = keep_pids or set()
|
||||
killed: list[int] = []
|
||||
for pid in _find_pids_by_signature(sig):
|
||||
if pid in keep:
|
||||
continue
|
||||
if _kill_pid_force(pid):
|
||||
killed.append(pid)
|
||||
return killed
|
||||
|
||||
|
||||
def detect_orphan_service_processes(name: str, *, keep_pids: set[int] | None = None) -> list[int]:
|
||||
sig = _service_signature(name)
|
||||
if not sig:
|
||||
return []
|
||||
keep = keep_pids or set()
|
||||
out: list[int] = []
|
||||
for pid in _find_pids_by_signature(sig):
|
||||
if pid in keep:
|
||||
continue
|
||||
out.append(pid)
|
||||
return out
|
||||
|
||||
|
||||
def cleanup_orphan_service_processes(name: str, *, keep_pids: set[int] | None = None) -> list[int]:
|
||||
return _cleanup_orphan_service_processes(name, keep_pids=keep_pids)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ServiceState:
|
||||
name: str
|
||||
pid: int
|
||||
command: list[str]
|
||||
running: bool
|
||||
|
||||
|
||||
def start_service(*, name: str, command: list[str], env: dict[str, str] | None = None, cwd: str | None = None) -> int:
|
||||
state = _read_state()
|
||||
services = state.setdefault("services", {})
|
||||
_cleanup_orphan_service_processes(name)
|
||||
existing = services.get(name)
|
||||
if isinstance(existing, dict):
|
||||
pid = int(existing.get("pid") or 0)
|
||||
if _is_running(pid):
|
||||
return pid
|
||||
merged_env = os.environ.copy()
|
||||
if env:
|
||||
merged_env.update({str(k): str(v) for k, v in env.items()})
|
||||
merged_env.setdefault("PYTHONUNBUFFERED", "1")
|
||||
log_dir = _runtime_log_dir()
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_name = str(name).replace(":", "_").replace("/", "_").replace("\\", "_")
|
||||
stdout_path = log_dir / f"{safe_name}.out.log"
|
||||
stderr_path = log_dir / f"{safe_name}.err.log"
|
||||
stdout_fh = open(stdout_path, "ab")
|
||||
stderr_fh = open(stderr_path, "ab")
|
||||
kwargs: dict[str, Any] = {
|
||||
"env": merged_env,
|
||||
"cwd": cwd or str(Path.cwd()),
|
||||
"stdin": subprocess.DEVNULL,
|
||||
"stdout": stdout_fh,
|
||||
"stderr": stderr_fh,
|
||||
}
|
||||
if os.name == "nt":
|
||||
create_no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
create_detached = getattr(subprocess, "DETACHED_PROCESS", 0)
|
||||
create_group = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
||||
kwargs["creationflags"] = create_group | create_detached | create_no_window
|
||||
startupinfo = subprocess.STARTUPINFO()
|
||||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||
startupinfo.wShowWindow = 0
|
||||
kwargs["startupinfo"] = startupinfo
|
||||
else:
|
||||
kwargs["start_new_session"] = True
|
||||
try:
|
||||
proc = subprocess.Popen(command, **kwargs)
|
||||
finally:
|
||||
try:
|
||||
stdout_fh.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
stderr_fh.close()
|
||||
except Exception:
|
||||
pass
|
||||
services[name] = {
|
||||
"pid": int(proc.pid),
|
||||
"command": command,
|
||||
"stdout_log": str(stdout_path),
|
||||
"stderr_log": str(stderr_path),
|
||||
}
|
||||
_write_state(state)
|
||||
return int(proc.pid)
|
||||
|
||||
|
||||
def status_services() -> list[ServiceState]:
|
||||
state = _read_state()
|
||||
services = state.get("services")
|
||||
if not isinstance(services, dict):
|
||||
return []
|
||||
out: list[ServiceState] = []
|
||||
for name, meta in services.items():
|
||||
if not isinstance(meta, dict):
|
||||
continue
|
||||
pid = int(meta.get("pid") or 0)
|
||||
cmd = meta.get("command") if isinstance(meta.get("command"), list) else []
|
||||
out.append(ServiceState(name=str(name), pid=pid, command=[str(x) for x in cmd], running=_is_running(pid)))
|
||||
return out
|
||||
|
||||
|
||||
def stop_service(name: str) -> bool:
|
||||
state = _read_state()
|
||||
services = state.get("services")
|
||||
if not isinstance(services, dict):
|
||||
return False
|
||||
meta = services.get(name)
|
||||
if not isinstance(meta, dict):
|
||||
return False
|
||||
pid = int(meta.get("pid") or 0)
|
||||
ok = False
|
||||
if _is_running(pid):
|
||||
ok = _kill_pid_force(pid)
|
||||
services.pop(name, None)
|
||||
_write_state(state)
|
||||
orphan_killed = _cleanup_orphan_service_processes(name, keep_pids={pid})
|
||||
return bool(ok or orphan_killed)
|
||||
|
||||
|
||||
def stop_all() -> list[str]:
|
||||
stopped: list[str] = []
|
||||
for s in status_services():
|
||||
if stop_service(s.name):
|
||||
stopped.append(s.name)
|
||||
return stopped
|
||||
|
||||
|
||||
def default_python_command(args: list[str]) -> list[str]:
|
||||
return [_python_bin(), *args]
|
||||
|
||||
51
runtime/operations/scripts/bootstrap_venv.ps1
Normal file
51
runtime/operations/scripts/bootstrap_venv.ps1
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
param(
|
||||
[string]$Python = "python",
|
||||
[switch]$Recreate = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
function Fail([string]$msg) {
|
||||
Write-Host "[ERROR] $msg" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $repoRoot
|
||||
|
||||
$venvDir = Join-Path $repoRoot "oclaw/.venv"
|
||||
$venvPython = Join-Path $venvDir "Scripts/python.exe"
|
||||
|
||||
$py = Get-Command $Python -ErrorAction SilentlyContinue
|
||||
if (-not $py) {
|
||||
Fail "python not found in PATH. Please install Python 3.10+ and retry."
|
||||
}
|
||||
|
||||
if ($Recreate -and (Test-Path $venvDir)) {
|
||||
Write-Step "Removing existing venv: $venvDir"
|
||||
Remove-Item -Recurse -Force $venvDir
|
||||
}
|
||||
|
||||
if (-not (Test-Path $venvPython)) {
|
||||
Write-Step "Creating venv: $venvDir"
|
||||
& $Python -m venv $venvDir
|
||||
}
|
||||
|
||||
if (-not (Test-Path $venvPython)) {
|
||||
Fail "venv python not found after creation: $venvPython"
|
||||
}
|
||||
|
||||
Write-Step "Upgrading pip"
|
||||
& $venvPython -m pip install -U pip
|
||||
|
||||
Write-Step "Installing requirements"
|
||||
& $venvPython -m pip install -r "requirements.txt"
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "OK. Next:" -ForegroundColor Green
|
||||
Write-Host " powershell -ExecutionPolicy Bypass -File .\\oclaw\\scripts\\start_gateway.ps1"
|
||||
Write-Host ""
|
||||
37
runtime/operations/scripts/create_bind_code.py
Normal file
37
runtime/operations/scripts/create_bind_code.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import sys
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def main() -> int:
|
||||
store = SqliteStore(db_path())
|
||||
tenants = store.list_tenants(limit=1)
|
||||
if tenants:
|
||||
tenant_id = tenants[0]["id"]
|
||||
tenant_name = tenants[0]["name"]
|
||||
else:
|
||||
created = store.create_tenant("Team")
|
||||
tenant_id = created["id"]
|
||||
tenant_name = created["name"]
|
||||
|
||||
role = "member"
|
||||
if len(sys.argv) >= 2 and str(sys.argv[1]).strip():
|
||||
role = str(sys.argv[1]).strip()
|
||||
|
||||
code = secrets.token_urlsafe(6)
|
||||
store.create_bind_code(tenant_id=tenant_id, role=role, code=code)
|
||||
|
||||
print(f"tenant={tenant_name} ({tenant_id})")
|
||||
print(f"role={role}")
|
||||
print(f"bind_code={code}")
|
||||
print(f"wecom_cmd=bind {code}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
74
runtime/operations/scripts/generate_forwarders.py
Normal file
74
runtime/operations/scripts/generate_forwarders.py
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from oclaw.platform.config.runtime_paths import oclaw_root
|
||||
|
||||
|
||||
_PS1_FORWARDERS: dict[str, str] = {
|
||||
"bootstrap_venv.ps1": "& $real @args",
|
||||
"start_web.ps1": "& $real @args",
|
||||
"status_all.ps1": "& $real @args",
|
||||
"status_ops.ps1": "& $real @args",
|
||||
"status_wiki_worker.ps1": "& $real @args",
|
||||
"stop_all.ps1": "& $real @args",
|
||||
"stop_desktop.ps1": "& $real @args",
|
||||
"stop_gateway.ps1": "& $real @args",
|
||||
"stop_ops.ps1": "& $real @args",
|
||||
"stop_web.ps1": "& $real @args",
|
||||
"stop_wiki_worker.ps1": "& $real @args",
|
||||
}
|
||||
|
||||
|
||||
def _ps1_template(name: str, invoke_line: str) -> str:
|
||||
return (
|
||||
"param()\n\n"
|
||||
"$ErrorActionPreference = \"Stop\"\n\n"
|
||||
f"$real = Join-Path $PSScriptRoot \"..\\\\runtime\\\\operations\\\\scripts\\\\{name}\"\n"
|
||||
"if (-not (Test-Path $real)) {\n"
|
||||
" throw \"Forward script target not found: $real\"\n"
|
||||
"}\n\n"
|
||||
f"{invoke_line}\n"
|
||||
)
|
||||
|
||||
|
||||
def _sh_template(name: str) -> str:
|
||||
return (
|
||||
"#!/usr/bin/env bash\n"
|
||||
"set -euo pipefail\n\n"
|
||||
f"REAL_PATH=\"$(cd \"$(dirname \"${{BASH_SOURCE[0]}}\")/../runtime/operations/scripts\" && pwd)/{name}\"\n"
|
||||
"if [[ ! -f \"$REAL_PATH\" ]]; then\n"
|
||||
" echo \"[ERROR] Forward script target not found: $REAL_PATH\" >&2\n"
|
||||
" exit 1\n"
|
||||
"fi\n\n"
|
||||
"exec bash \"$REAL_PATH\" \"$@\"\n"
|
||||
)
|
||||
|
||||
|
||||
def generate_forwarders() -> list[Path]:
|
||||
out: list[Path] = []
|
||||
scripts_root = (oclaw_root() / "scripts").resolve()
|
||||
scripts_root.mkdir(parents=True, exist_ok=True)
|
||||
for name, invoke in _PS1_FORWARDERS.items():
|
||||
p = scripts_root / name
|
||||
p.write_text(_ps1_template(name, invoke), encoding="utf-8")
|
||||
out.append(p)
|
||||
|
||||
for name in ("start_ops.sh", "status_ops.sh", "stop_ops.sh"):
|
||||
p = scripts_root / name
|
||||
p.write_text(_sh_template(name), encoding="utf-8")
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
generated = generate_forwarders()
|
||||
print(f"generated_forwarders={len(generated)}")
|
||||
for p in generated:
|
||||
print(str(p))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
71
runtime/operations/scripts/install_extra_mcp_batch.py
Normal file
71
runtime/operations/scripts/install_extra_mcp_batch.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"""One-off helper: install additional npm MCP servers into local registry (stdio / npx).
|
||||
|
||||
Run from repo root: python oclaw/scripts/install_extra_mcp_batch.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# repo root
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from oclaw.platform.config.paths import db_path # noqa: E402
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore # noqa: E402
|
||||
from oclaw.runtime.tools.mcp.installer import McpServerManifest, _safe_server_id, install_mcp_server # noqa: E402
|
||||
|
||||
|
||||
# (server_id_seed, npm package ref, entry_args for npx)
|
||||
# Note: mcp-smart-crawler was tried; stdio JSON-RPC handshake failed on Windows — not registered.
|
||||
BATCH: list[tuple[str, str, list[str]]] = [
|
||||
("mcp-git-cyanheads", "@cyanheads/git-mcp-server", ["-y", "@cyanheads/git-mcp-server"]),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
store = SqliteStore(db_path())
|
||||
for seed, source_ref, entry_args in BATCH:
|
||||
server_id = _safe_server_id(seed)
|
||||
manifest = McpServerManifest(
|
||||
server_id=server_id,
|
||||
source_type="npm",
|
||||
source_ref=source_ref,
|
||||
version="",
|
||||
entry_command="npx",
|
||||
entry_args=entry_args,
|
||||
env_schema={},
|
||||
permissions=[],
|
||||
risk_level="high",
|
||||
enabled=True,
|
||||
timeout_s=60.0,
|
||||
)
|
||||
print(f"\n=== Installing {server_id} ({source_ref}) ===")
|
||||
inst = install_mcp_server(manifest, dry_run=False)
|
||||
store.upsert_mcp_server(
|
||||
server_id=manifest.server_id,
|
||||
source_type=manifest.source_type,
|
||||
source_ref=manifest.source_ref,
|
||||
version=manifest.version,
|
||||
entry_command=manifest.entry_command,
|
||||
entry_args=manifest.entry_args,
|
||||
env_schema=manifest.env_schema,
|
||||
required_permissions=manifest.permissions,
|
||||
risk_level=manifest.risk_level,
|
||||
timeout_s=manifest.timeout_s,
|
||||
enabled=manifest.enabled if inst.ok else False,
|
||||
)
|
||||
store.add_mcp_installation_log(
|
||||
server_id=manifest.server_id,
|
||||
status="ok" if inst.ok else "error",
|
||||
error_code=inst.error_code,
|
||||
detail={"error": inst.error, **(inst.details or {})},
|
||||
install_command=inst.install_command,
|
||||
)
|
||||
print("ok:", inst.ok, inst.error_code or "-", inst.install_command)
|
||||
if not inst.ok:
|
||||
print("stderr snippet:", (inst.error or "")[:400])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
145
runtime/operations/scripts/install_mcp_context7.py
Normal file
145
runtime/operations/scripts/install_mcp_context7.py
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
"""Install MCP: Context7 (up-to-date library docs) — npm global + registry + Sync Tools + generalist binding.
|
||||
|
||||
Run from repo root: python oclaw/scripts/install_mcp_context7.py
|
||||
|
||||
Requires CONTEXT7_API_KEY in src/_local/mcp_local.env or data/mcp_local.env (or environment). Default OPS_MCP_ENV_ALLOWLIST
|
||||
now includes CONTEXT7_API_KEY when unset; restart gateway after changing env.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from oclaw.platform.config.paths import db_path # noqa: E402
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore # noqa: E402
|
||||
from oclaw.runtime.tools.mcp.installer import McpServerManifest, install_mcp_server # noqa: E402
|
||||
from oclaw.runtime.tools.mcp.runtime import McpProcessRuntime # noqa: E402
|
||||
|
||||
_BINDING_KEY = "mcp_specialist_server_binding"
|
||||
|
||||
|
||||
def _sync_tools(store: SqliteStore, server_id: str) -> bool:
|
||||
rows = store.list_mcp_servers(enabled_only=False)
|
||||
row = next((x for x in rows if str(x.get("server_id") or "") == server_id), None)
|
||||
if not row:
|
||||
return False
|
||||
cmd = str(row.get("entry_command") or "").strip()
|
||||
args = [str(x) for x in (row.get("entry_args") or []) if str(x).strip()]
|
||||
if not cmd:
|
||||
return False
|
||||
rt = McpProcessRuntime([cmd] + args, timeout_s=float(row.get("timeout_s") or 60.0))
|
||||
try:
|
||||
h = rt.health()
|
||||
if not bool(h.get("ok")):
|
||||
store.set_mcp_server_health(server_id=server_id, status="error", detail=h)
|
||||
return False
|
||||
tr = rt.tools_list()
|
||||
items = tr.get("tools") if isinstance(tr, dict) else None
|
||||
if not isinstance(items, list) or not bool(tr.get("ok")):
|
||||
store.set_mcp_server_health(
|
||||
server_id=server_id,
|
||||
status="error",
|
||||
detail=tr if isinstance(tr, dict) else {"error": "tools_list_failed"},
|
||||
)
|
||||
return False
|
||||
norm: list[dict] = []
|
||||
for it in items:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
tool_name = str(it.get("tool_name") or it.get("name") or "").strip()
|
||||
if not tool_name:
|
||||
continue
|
||||
norm.append(
|
||||
{
|
||||
"tool_name": tool_name,
|
||||
"description": str(it.get("description") or ""),
|
||||
"parameters": it.get("parameters") if isinstance(it.get("parameters"), dict) else {},
|
||||
}
|
||||
)
|
||||
store.replace_mcp_server_tools(server_id=server_id, tools=norm)
|
||||
store.set_mcp_server_health(server_id=server_id, status="ok", detail={"synced_tools": len(norm)})
|
||||
return True
|
||||
finally:
|
||||
rt.stop()
|
||||
|
||||
|
||||
def _append_generalist_binding(store: SqliteStore, server_id: str) -> None:
|
||||
raw = str(store.get_setting(_BINDING_KEY) or "").strip()
|
||||
try:
|
||||
obj = json.loads(raw) if raw else {}
|
||||
except json.JSONDecodeError:
|
||||
obj = {}
|
||||
if not isinstance(obj, dict):
|
||||
obj = {}
|
||||
cur = obj.get("generalist")
|
||||
gl: list[str] = list(cur) if isinstance(cur, list) else []
|
||||
sid = str(server_id or "").strip()
|
||||
if sid and sid not in gl:
|
||||
gl.append(sid)
|
||||
obj["generalist"] = gl
|
||||
store.set_setting(_BINDING_KEY, json.dumps(obj, ensure_ascii=False))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
store = SqliteStore(db_path())
|
||||
manifest = McpServerManifest(
|
||||
server_id="mcp-context7",
|
||||
source_type="npm",
|
||||
source_ref="@upstash/context7-mcp",
|
||||
version="",
|
||||
entry_command="npx",
|
||||
entry_args=["-y", "@upstash/context7-mcp"],
|
||||
env_schema={
|
||||
"CONTEXT7_API_KEY": {
|
||||
"type": "string",
|
||||
"description": "Context7 API key (https://context7.com/dashboard)",
|
||||
}
|
||||
},
|
||||
permissions=[],
|
||||
risk_level="medium",
|
||||
enabled=True,
|
||||
timeout_s=60.0,
|
||||
)
|
||||
print(f"\n=== npm install {manifest.server_id} ({manifest.source_ref}) ===")
|
||||
inst = install_mcp_server(manifest, dry_run=False)
|
||||
store.upsert_mcp_server(
|
||||
server_id=manifest.server_id,
|
||||
source_type=manifest.source_type,
|
||||
source_ref=manifest.source_ref,
|
||||
version=manifest.version,
|
||||
entry_command=manifest.entry_command,
|
||||
entry_args=manifest.entry_args,
|
||||
env_schema=manifest.env_schema,
|
||||
required_permissions=manifest.permissions,
|
||||
risk_level=manifest.risk_level,
|
||||
timeout_s=manifest.timeout_s,
|
||||
enabled=manifest.enabled if inst.ok else False,
|
||||
)
|
||||
store.add_mcp_installation_log(
|
||||
server_id=manifest.server_id,
|
||||
status="ok" if inst.ok else "error",
|
||||
error_code=inst.error_code,
|
||||
detail={"error": inst.error, **(inst.details or {})},
|
||||
install_command=inst.install_command,
|
||||
)
|
||||
print("install ok:", inst.ok, inst.install_command)
|
||||
if not inst.ok:
|
||||
return
|
||||
print(f"=== sync tools {manifest.server_id} ===")
|
||||
synced = _sync_tools(store, manifest.server_id)
|
||||
print("sync ok:", synced)
|
||||
if synced:
|
||||
_append_generalist_binding(store, manifest.server_id)
|
||||
print("binding: appended mcp-context7 to generalist")
|
||||
else:
|
||||
print("Set CONTEXT7_API_KEY in src/_local/mcp_local.env (or data/mcp_local.env), restart gateway, then Admin → Sync Tools; save binding with mcp-context7 if needed.")
|
||||
|
||||
print("\nDone.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
153
runtime/operations/scripts/install_mcp_sqlite_brave_calendar.py
Normal file
153
runtime/operations/scripts/install_mcp_sqlite_brave_calendar.py
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
"""Install MCP: SQLite (project DB), Brave Search, Google Calendar — npm global + registry upsert.
|
||||
|
||||
Run from repo root: python oclaw/scripts/install_mcp_sqlite_brave_calendar.py
|
||||
|
||||
Brave Search needs BRAVE_API_KEY in environment (+ OPS_MCP_ENV_ALLOWLIST includes it).
|
||||
Google Calendar needs GOOGLE_OAUTH_CREDENTIALS=path/to/oauth.json (+ allowlist).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from oclaw.platform.config.paths import db_path # noqa: E402
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore # noqa: E402
|
||||
from oclaw.runtime.tools.mcp.installer import McpServerManifest, install_mcp_server # noqa: E402
|
||||
from oclaw.runtime.tools.mcp.runtime import McpProcessRuntime # noqa: E402
|
||||
|
||||
|
||||
def _sync_tools(store: SqliteStore, server_id: str) -> bool:
|
||||
rows = store.list_mcp_servers(enabled_only=False)
|
||||
row = next((x for x in rows if str(x.get("server_id") or "") == server_id), None)
|
||||
if not row:
|
||||
return False
|
||||
cmd = str(row.get("entry_command") or "").strip()
|
||||
args = [str(x) for x in (row.get("entry_args") or []) if str(x).strip()]
|
||||
if not cmd:
|
||||
return False
|
||||
rt = McpProcessRuntime([cmd] + args, timeout_s=float(row.get("timeout_s") or 60.0))
|
||||
try:
|
||||
h = rt.health()
|
||||
if not bool(h.get("ok")):
|
||||
store.set_mcp_server_health(server_id=server_id, status="error", detail=h)
|
||||
return False
|
||||
tr = rt.tools_list()
|
||||
items = tr.get("tools") if isinstance(tr, dict) else None
|
||||
if not isinstance(items, list) or not bool(tr.get("ok")):
|
||||
store.set_mcp_server_health(server_id=server_id, status="error", detail=tr if isinstance(tr, dict) else {"error": "tools_list_failed"})
|
||||
return False
|
||||
norm: list[dict] = []
|
||||
for it in items:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
tool_name = str(it.get("tool_name") or it.get("name") or "").strip()
|
||||
if not tool_name:
|
||||
continue
|
||||
norm.append(
|
||||
{
|
||||
"tool_name": tool_name,
|
||||
"description": str(it.get("description") or ""),
|
||||
"parameters": it.get("parameters") if isinstance(it.get("parameters"), dict) else {},
|
||||
}
|
||||
)
|
||||
store.replace_mcp_server_tools(server_id=server_id, tools=norm)
|
||||
store.set_mcp_server_health(server_id=server_id, status="ok", detail={"synced_tools": len(norm)})
|
||||
return True
|
||||
finally:
|
||||
rt.stop()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
store = SqliteStore(db_path())
|
||||
db_file = db_path()
|
||||
|
||||
bundles: list[McpServerManifest] = [
|
||||
McpServerManifest(
|
||||
server_id="mcp-sqlite",
|
||||
source_type="npm",
|
||||
source_ref="mcp-sqlite",
|
||||
version="",
|
||||
entry_command="npx",
|
||||
entry_args=["-y", "mcp-sqlite", db_file],
|
||||
env_schema={},
|
||||
permissions=[],
|
||||
risk_level="high",
|
||||
enabled=True,
|
||||
timeout_s=90.0,
|
||||
),
|
||||
McpServerManifest(
|
||||
server_id="mcp-brave-search",
|
||||
source_type="npm",
|
||||
source_ref="@modelcontextprotocol/server-brave-search",
|
||||
version="",
|
||||
entry_command="npx",
|
||||
entry_args=["-y", "@modelcontextprotocol/server-brave-search"],
|
||||
env_schema={
|
||||
"BRAVE_API_KEY": {
|
||||
"type": "string",
|
||||
"description": "Brave Search API key (https://brave.com/search/api/)",
|
||||
}
|
||||
},
|
||||
permissions=[],
|
||||
risk_level="high",
|
||||
enabled=True,
|
||||
timeout_s=60.0,
|
||||
),
|
||||
McpServerManifest(
|
||||
server_id="mcp-google-calendar",
|
||||
source_type="npm",
|
||||
source_ref="@cocal/google-calendar-mcp",
|
||||
version="",
|
||||
entry_command="npx",
|
||||
entry_args=["-y", "@cocal/google-calendar-mcp"],
|
||||
env_schema={
|
||||
"GOOGLE_OAUTH_CREDENTIALS": {
|
||||
"type": "string",
|
||||
"description": "Absolute path to Google Cloud OAuth client JSON (Desktop app)",
|
||||
}
|
||||
},
|
||||
permissions=[],
|
||||
risk_level="high",
|
||||
enabled=True,
|
||||
timeout_s=120.0,
|
||||
),
|
||||
]
|
||||
|
||||
for manifest in bundles:
|
||||
print(f"\n=== npm install {manifest.server_id} ({manifest.source_ref}) ===")
|
||||
inst = install_mcp_server(manifest, dry_run=False)
|
||||
store.upsert_mcp_server(
|
||||
server_id=manifest.server_id,
|
||||
source_type=manifest.source_type,
|
||||
source_ref=manifest.source_ref,
|
||||
version=manifest.version,
|
||||
entry_command=manifest.entry_command,
|
||||
entry_args=manifest.entry_args,
|
||||
env_schema=manifest.env_schema,
|
||||
required_permissions=manifest.permissions,
|
||||
risk_level=manifest.risk_level,
|
||||
timeout_s=manifest.timeout_s,
|
||||
enabled=manifest.enabled if inst.ok else False,
|
||||
)
|
||||
store.add_mcp_installation_log(
|
||||
server_id=manifest.server_id,
|
||||
status="ok" if inst.ok else "error",
|
||||
error_code=inst.error_code,
|
||||
detail={"error": inst.error, **(inst.details or {})},
|
||||
install_command=inst.install_command,
|
||||
)
|
||||
print("install ok:", inst.ok, inst.install_command)
|
||||
if not inst.ok:
|
||||
continue
|
||||
print(f"=== sync tools {manifest.server_id} ===")
|
||||
ok = _sync_tools(store, manifest.server_id)
|
||||
print("sync ok:", ok)
|
||||
|
||||
print("\nDone. If Brave/Calendar show sync errors, set env vars and OPS_MCP_ENV_ALLOWLIST, then run Check Installed from Admin.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
46
runtime/operations/scripts/offline_eval.py
Normal file
46
runtime/operations/scripts/offline_eval.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _iter_jsonl(path: Path):
|
||||
for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
s = line.strip()
|
||||
if not s:
|
||||
continue
|
||||
try:
|
||||
yield i, json.loads(s)
|
||||
except Exception as e:
|
||||
raise SystemExit(f"{path}: invalid json at line {i}: {e}") from e
|
||||
|
||||
|
||||
def main() -> int:
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
data_dir = root / "data" / "eval"
|
||||
if not data_dir.exists():
|
||||
print("offline_eval: no data/eval directory, skip")
|
||||
return 0
|
||||
files = sorted(p for p in data_dir.glob("*.jsonl"))
|
||||
if not files:
|
||||
print("offline_eval: no eval jsonl files, skip")
|
||||
return 0
|
||||
total = 0
|
||||
for fp in files:
|
||||
for line_no, obj in _iter_jsonl(fp):
|
||||
total += 1
|
||||
if not isinstance(obj, dict):
|
||||
raise SystemExit(f"{fp}:{line_no}: expected object")
|
||||
if not str(obj.get("id") or "").strip():
|
||||
raise SystemExit(f"{fp}:{line_no}: missing id")
|
||||
# Optional lightweight schema checks used by repo's eval fixtures.
|
||||
for k in ("assert_contains", "assert_not_contains"):
|
||||
if k in obj and not isinstance(obj.get(k), list):
|
||||
raise SystemExit(f"{fp}:{line_no}: {k} must be a list")
|
||||
print(f"offline_eval: ok files={len(files)} cases={total}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
96
runtime/operations/scripts/seed_mcp_registry.py
Normal file
96
runtime/operations/scripts/seed_mcp_registry.py
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
"""将 oclaw/data/mcp_registry.seed.json 中的 MCP 定义写入本地 SQLite(与管理台 Install 等价)。
|
||||
|
||||
库表被清空、换库或新环境时:在项目根执行
|
||||
python oclaw/scripts/seed_mcp_registry.py
|
||||
可选:python oclaw/scripts/seed_mcp_registry.py path/to/other.seed.json
|
||||
|
||||
随后在各 MCP 上点 Health → Sync Tools;Context7 等需在 src/_local/mcp_local.env 配密钥。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from oclaw.platform.config.paths import PROJECT_ROOT, db_path # noqa: E402
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore # noqa: E402
|
||||
from oclaw.runtime.tools.mcp.installer import McpServerManifest, _safe_server_id, install_mcp_server # noqa: E402
|
||||
|
||||
|
||||
def _subst_repo(path_str: str) -> str:
|
||||
s = str(path_str or "").strip()
|
||||
if s.startswith("__REPO_ROOT__/"):
|
||||
return str((PROJECT_ROOT / s.replace("__REPO_ROOT__/", "", 1)).resolve())
|
||||
return s
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
seed_path = Path(argv[1]).resolve() if len(argv) > 1 else (ROOT / "data" / "mcp_registry.seed.json")
|
||||
if not seed_path.is_file():
|
||||
print(f"seed file not found: {seed_path}", file=sys.stderr)
|
||||
return 2
|
||||
raw = json.loads(seed_path.read_text(encoding="utf-8"))
|
||||
items = raw.get("servers") if isinstance(raw, dict) else raw
|
||||
if not isinstance(items, list) or not items:
|
||||
print("no servers[] in seed file", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
store = SqliteStore(db_path())
|
||||
ok_n = 0
|
||||
for payload in items:
|
||||
if not isinstance(payload, dict):
|
||||
continue
|
||||
source_type = str(payload.get("source_type") or "").strip().lower()
|
||||
source_ref = str(payload.get("source_ref") or "").strip()
|
||||
if source_type not in {"github", "npm", "pypi"} or not source_ref:
|
||||
print(f"skip invalid: {payload.get('server_id')!r}")
|
||||
continue
|
||||
server_id = _safe_server_id(str(payload.get("server_id") or source_ref))
|
||||
entry_args = [_subst_repo(x) for x in (payload.get("entry_args") or []) if str(x).strip()]
|
||||
manifest = McpServerManifest(
|
||||
server_id=server_id,
|
||||
source_type=source_type,
|
||||
source_ref=source_ref,
|
||||
version=str(payload.get("version") or "").strip(),
|
||||
entry_command=str(payload.get("entry_command") or "").strip(),
|
||||
entry_args=entry_args,
|
||||
env_schema=payload.get("env_schema") if isinstance(payload.get("env_schema"), dict) else {},
|
||||
permissions=[str(x) for x in (payload.get("required_permissions") or [])],
|
||||
risk_level=str(payload.get("risk_level") or "high"),
|
||||
enabled=bool(payload.get("enabled")),
|
||||
timeout_s=float(payload.get("timeout_s") or 30.0),
|
||||
)
|
||||
dry_run = bool(payload.get("dry_run", False))
|
||||
inst = install_mcp_server(manifest, dry_run=dry_run)
|
||||
store.upsert_mcp_server(
|
||||
server_id=manifest.server_id,
|
||||
source_type=manifest.source_type,
|
||||
source_ref=manifest.source_ref,
|
||||
version=manifest.version,
|
||||
entry_command=manifest.entry_command,
|
||||
entry_args=manifest.entry_args,
|
||||
env_schema=manifest.env_schema,
|
||||
required_permissions=manifest.permissions,
|
||||
risk_level=manifest.risk_level,
|
||||
timeout_s=manifest.timeout_s,
|
||||
enabled=manifest.enabled if inst.ok else False,
|
||||
)
|
||||
store.add_mcp_installation_log(
|
||||
server_id=manifest.server_id,
|
||||
status="ok" if inst.ok else "error",
|
||||
error_code=inst.error_code,
|
||||
detail={"error": inst.error, **(inst.details or {}), "seed": True},
|
||||
install_command=inst.install_command,
|
||||
)
|
||||
print(f"{server_id}: install_ok={inst.ok} enabled={manifest.enabled if inst.ok else False} cmd={inst.install_command[:120]!r}")
|
||||
if inst.ok:
|
||||
ok_n += 1
|
||||
print(f"done: {ok_n}/{len(items)} npm/pypi install steps succeeded; rows upserted for all valid entries.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv))
|
||||
55
runtime/operations/scripts/set_wecom_auto_bind.py
Normal file
55
runtime/operations/scripts/set_wecom_auto_bind.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def _to_bool(v: str) -> str:
|
||||
return "1" if str(v).strip().lower() in ("1", "true", "yes", "on") else "0"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = [str(x).strip() for x in sys.argv[1:]]
|
||||
if not args:
|
||||
print("usage:")
|
||||
print(" python -m scripts.set_wecom_auto_bind on|off")
|
||||
print(" python -m scripts.set_wecom_auto_bind on <tenant_name> <role>")
|
||||
print(" python -m scripts.set_wecom_auto_bind show")
|
||||
return 2
|
||||
|
||||
cmd = args[0].lower()
|
||||
store = SqliteStore(db_path())
|
||||
|
||||
if cmd == "show":
|
||||
enabled = str(store.get_setting("wecom_auto_bind_enabled") or "1").strip()
|
||||
tenant_name = str(store.get_setting("wecom_auto_bind_tenant_name") or "Team").strip() or "Team"
|
||||
role = str(store.get_setting("wecom_auto_bind_role") or "member").strip() or "member"
|
||||
print("ok=1")
|
||||
print(f"enabled={enabled}")
|
||||
print(f"tenant_name={tenant_name}")
|
||||
print(f"role={role}")
|
||||
return 0
|
||||
|
||||
if cmd not in ("on", "off"):
|
||||
print("error=invalid_command")
|
||||
return 2
|
||||
|
||||
enabled = _to_bool("1" if cmd == "on" else "0")
|
||||
tenant_name = (args[1] if len(args) >= 2 else "Team").strip() or "Team"
|
||||
role = (args[2] if len(args) >= 3 else "member").strip() or "member"
|
||||
|
||||
store.set_setting("wecom_auto_bind_enabled", enabled)
|
||||
store.set_setting("wecom_auto_bind_tenant_name", tenant_name)
|
||||
store.set_setting("wecom_auto_bind_role", role)
|
||||
|
||||
print("ok=1")
|
||||
print(f"enabled={enabled}")
|
||||
print(f"tenant_name={tenant_name}")
|
||||
print(f"role={role}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
35
runtime/operations/scripts/set_wecom_config.py
Normal file
35
runtime/operations/scripts/set_wecom_config.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = [str(x).strip() for x in sys.argv[1:]]
|
||||
if not args:
|
||||
print("usage:")
|
||||
print(" python -m scripts.set_wecom_config <bot_id> <bot_secret>")
|
||||
return 2
|
||||
|
||||
store = SqliteStore(db_path())
|
||||
if len(args) < 2:
|
||||
print("error=missing_required_args")
|
||||
return 2
|
||||
bot_id, bot_secret = args[0], args[1]
|
||||
if not bot_id or not bot_secret:
|
||||
print("error=missing_required_args")
|
||||
return 2
|
||||
store.set_setting("wecom_mode", "bot_api")
|
||||
store.set_setting("wecom_bot_id", bot_id)
|
||||
store.set_secret("wecom_bot_secret", bot_secret)
|
||||
store.delete_setting("wecom_access_token_cache")
|
||||
print("ok=1")
|
||||
print("mode=bot_api")
|
||||
print("saved=wecom_bot_id,wecom_bot_secret(secret)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
49
runtime/operations/scripts/start_all.ps1
Normal file
49
runtime/operations/scripts/start_all.ps1
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
param(
|
||||
[string]$BindHost = "127.0.0.1",
|
||||
[int]$Port = 8787,
|
||||
[switch]$SkipInstall = $false,
|
||||
[switch]$Background = $false,
|
||||
[switch]$WithWeixin = $false,
|
||||
[switch]$WithWikiWorker = $false,
|
||||
[string]$WeixinChannelId = "oclaw-weixin",
|
||||
[string]$WeixinGatewayBaseUrl = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $repoRoot
|
||||
|
||||
Write-Step "Starting gateway + desktop"
|
||||
|
||||
& "$PSScriptRoot/start_gateway.ps1" -BindHost $BindHost -Port $Port -SkipInstall:$SkipInstall -Background:$Background
|
||||
|
||||
# When gateway is started in foreground, the call above blocks; desktop won't start.
|
||||
if (-not $Background) {
|
||||
Write-Host ""
|
||||
Write-Host "[INFO] Gateway started in foreground and will block. Use -Background to start both." -ForegroundColor Yellow
|
||||
exit 0
|
||||
}
|
||||
|
||||
& "$PSScriptRoot/start_desktop.ps1" -SkipInstall:$SkipInstall -Background
|
||||
|
||||
if ($WithWeixin) {
|
||||
$gwBase = ($WeixinGatewayBaseUrl | ForEach-Object { "$_".Trim() })
|
||||
if (-not $gwBase) {
|
||||
$gwBase = "http://$BindHost`:$Port"
|
||||
}
|
||||
Write-Step "Starting weixin sidecar"
|
||||
& "$PSScriptRoot/weixin_start.ps1" -ChannelId $WeixinChannelId -GatewayBaseUrl $gwBase
|
||||
}
|
||||
if ($WithWikiWorker) {
|
||||
Write-Step "Starting wiki worker"
|
||||
& "$PSScriptRoot/start_wiki_worker.ps1" -Background
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "All started." -ForegroundColor Green
|
||||
|
||||
49
runtime/operations/scripts/start_desktop.ps1
Normal file
49
runtime/operations/scripts/start_desktop.ps1
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
param(
|
||||
[switch]$SkipInstall = $false,
|
||||
[switch]$Background = $false,
|
||||
[switch]$KeepExistingGateway = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
$desktopDir = Join-Path $repoRoot "oclaw\\desktop"
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
New-Item -ItemType Directory -Force -Path $runDir | Out-Null
|
||||
$pidFile = Join-Path $runDir "desktop.pid"
|
||||
$outLog = Join-Path $runDir "desktop.out.log"
|
||||
$errLog = Join-Path $runDir "desktop.err.log"
|
||||
|
||||
if (-not (Test-Path $desktopDir)) {
|
||||
Write-Host "[ERROR] desktop directory not found: $desktopDir" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Set-Location $desktopDir
|
||||
|
||||
if (-not $KeepExistingGateway) {
|
||||
Write-Host "==> Cleaning previous gateway listener" -ForegroundColor Cyan
|
||||
try {
|
||||
& "$PSScriptRoot/stop_gateway.ps1" -Force
|
||||
} catch {
|
||||
Write-Host "[WARN] Failed to pre-stop gateway: $($_.Exception.Message)" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $SkipInstall) {
|
||||
Write-Host "==> Installing desktop dependencies" -ForegroundColor Cyan
|
||||
npm install
|
||||
}
|
||||
|
||||
Write-Host "==> Launching desktop app" -ForegroundColor Cyan
|
||||
if ($Background) {
|
||||
# Avoid launching npm.ps1 directly (can be file-associated and open in Notepad on some setups).
|
||||
# Use hidden cmd and redirect logs to avoid black console window popup.
|
||||
$p = Start-Process -FilePath "cmd.exe" -ArgumentList @("/c","npm.cmd","run","dev") -WorkingDirectory $desktopDir -PassThru -WindowStyle Hidden -RedirectStandardOutput $outLog -RedirectStandardError $errLog
|
||||
Set-Content -Path $pidFile -Value "$($p.Id)" -Encoding ascii
|
||||
Write-Host "desktop.pid = $pidFile" -ForegroundColor DarkGray
|
||||
Write-Host "desktop.out = $outLog" -ForegroundColor DarkGray
|
||||
Write-Host "desktop.err = $errLog" -ForegroundColor DarkGray
|
||||
Write-Host "PID = $($p.Id)" -ForegroundColor Green
|
||||
exit 0
|
||||
}
|
||||
& "npm.cmd" "run" "dev"
|
||||
72
runtime/operations/scripts/start_gateway.ps1
Normal file
72
runtime/operations/scripts/start_gateway.ps1
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
param(
|
||||
[string]$BindHost = "127.0.0.1",
|
||||
[int]$Port = 8787,
|
||||
[switch]$SkipInstall = $false,
|
||||
[switch]$Background = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
function Fail([string]$msg) {
|
||||
Write-Host "[ERROR] $msg" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $repoRoot
|
||||
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
New-Item -ItemType Directory -Force -Path $runDir | Out-Null
|
||||
$pidFile = Join-Path $runDir "gateway.pid"
|
||||
|
||||
Write-Step "Project root: $repoRoot"
|
||||
|
||||
$venvPython = Join-Path $repoRoot "oclaw/.venv/Scripts/python.exe"
|
||||
if (Test-Path $venvPython) {
|
||||
Write-Step "Using venv python: $venvPython"
|
||||
$pythonExe = $venvPython
|
||||
} else {
|
||||
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue
|
||||
if (-not $pythonCmd) {
|
||||
Fail "python not found in PATH. Please install Python and retry."
|
||||
}
|
||||
Write-Step "Python detected: $($pythonCmd.Source)"
|
||||
$pythonExe = "python"
|
||||
}
|
||||
|
||||
if (-not $SkipInstall) {
|
||||
Write-Step "Installing dependencies (pip install -r requirements.txt)"
|
||||
& $pythonExe -m pip install -r "requirements.txt"
|
||||
} else {
|
||||
Write-Step "Skip dependency install"
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Step "Gateway URL"
|
||||
Write-Host "Admin: http://$BindHost`:$Port/admin"
|
||||
Write-Host "Chat: http://$BindHost`:$Port/chat"
|
||||
Write-Host "WS: ws://$BindHost`:$Port/ws"
|
||||
Write-Host ""
|
||||
|
||||
$configPath = Join-Path $repoRoot "oclaw\oclaw.json"
|
||||
if (Test-Path $configPath) {
|
||||
$env:OCLAW_CONFIG_PATH = $configPath
|
||||
Write-Step "Using OCLAW_CONFIG_PATH: $configPath"
|
||||
}
|
||||
|
||||
if ($Background) {
|
||||
Write-Step "Starting gateway in background"
|
||||
$p = Start-Process -FilePath $pythonExe -ArgumentList @("-m","oclaw.runtime.operations","gateway","start","--host",$BindHost,"--port",$Port) -WorkingDirectory $repoRoot -PassThru -WindowStyle Hidden
|
||||
Set-Content -Path $pidFile -Value "$($p.Id)" -Encoding ascii
|
||||
Write-Host "gateway.pid = $pidFile" -ForegroundColor DarkGray
|
||||
Write-Host "PID = $($p.Id)" -ForegroundColor Green
|
||||
exit 0
|
||||
}
|
||||
|
||||
Write-Step "Starting gateway (foreground)"
|
||||
& $pythonExe -m oclaw.runtime.operations gateway start --host $BindHost --port $Port
|
||||
|
||||
70
runtime/operations/scripts/start_ops.ps1
Normal file
70
runtime/operations/scripts/start_ops.ps1
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
param(
|
||||
[string]$Channel = "wecom",
|
||||
[switch]$SkipInstall = $false,
|
||||
[switch]$SkipConfigHint = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
function Fail([string]$msg) {
|
||||
Write-Host "[ERROR] $msg" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $repoRoot
|
||||
|
||||
Write-Step "Project root: $repoRoot"
|
||||
|
||||
$venvPython = Join-Path $repoRoot "oclaw/.venv/Scripts/python.exe"
|
||||
if (Test-Path $venvPython) {
|
||||
Write-Step "Using venv python: $venvPython"
|
||||
$pythonExe = $venvPython
|
||||
} else {
|
||||
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue
|
||||
if (-not $pythonCmd) {
|
||||
Fail "python not found in PATH. Please install Python 3.10+ and retry."
|
||||
}
|
||||
Write-Step "Python detected: $($pythonCmd.Source)"
|
||||
$pythonExe = "python"
|
||||
}
|
||||
|
||||
if (-not $SkipInstall) {
|
||||
Write-Step "Installing dependencies (pip install -r requirements.txt)"
|
||||
& $pythonExe -m pip install -r "requirements.txt"
|
||||
} else {
|
||||
Write-Step "Skip dependency install"
|
||||
}
|
||||
|
||||
if (-not $SkipConfigHint) {
|
||||
Write-Step "Current WeCom status"
|
||||
try {
|
||||
python -m oclaw.runtime.operations channel wecom status
|
||||
} catch {
|
||||
Write-Host "[WARN] Unable to read WeCom status yet." -ForegroundColor Yellow
|
||||
}
|
||||
Write-Host ""
|
||||
Write-Host "If WeCom is not configured yet, run this first:" -ForegroundColor Yellow
|
||||
Write-Host " python -m oclaw.runtime.operations channel wecom config --help"
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Step "Stopping previous stack (safe if not running)"
|
||||
& $pythonExe -m oclaw.runtime.operations stack down
|
||||
|
||||
Write-Step "Starting stack: python -m oclaw.runtime.operations stack up --channel $Channel"
|
||||
& $pythonExe -m oclaw.runtime.operations stack up --channel $Channel
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Started successfully." -ForegroundColor Green
|
||||
Write-Host "Admin: http://127.0.0.1:8787/admin"
|
||||
Write-Host "Chat: http://127.0.0.1:8787/chat"
|
||||
Write-Host ""
|
||||
Write-Host "Useful commands:"
|
||||
Write-Host " python -m oclaw.runtime.operations stack status"
|
||||
Write-Host " python -m oclaw.runtime.operations stack down"
|
||||
|
||||
81
runtime/operations/scripts/start_ops.sh
Normal file
81
runtime/operations/scripts/start_ops.sh
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
CHANNEL="wecom"
|
||||
SKIP_INSTALL=0
|
||||
SKIP_CONFIG_HINT=0
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--no-ui)
|
||||
# Kept for compatibility; stack no longer starts Streamlit.
|
||||
shift
|
||||
;;
|
||||
--channel)
|
||||
CHANNEL="${2:-wecom}"
|
||||
shift 2
|
||||
;;
|
||||
--skip-install)
|
||||
SKIP_INSTALL=1
|
||||
shift
|
||||
;;
|
||||
--skip-config-hint)
|
||||
SKIP_CONFIG_HINT=1
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
echo "Unknown arg: $1"
|
||||
echo "Usage: $0 [--no-ui] [--channel wecom] [--skip-install] [--skip-config-hint]"
|
||||
echo "Note: --no-ui is legacy; stack does not start Streamlit. Chat: http://127.0.0.1:8787/chat"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
step() { printf '\n==> %s\n' "$1"; }
|
||||
|
||||
if ! command -v python >/dev/null 2>&1; then
|
||||
echo "[ERROR] python not found in PATH." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
step "Project root: $ROOT_DIR"
|
||||
step "Python: $(command -v python)"
|
||||
|
||||
if [[ "$SKIP_INSTALL" -eq 0 ]]; then
|
||||
step "Installing dependencies"
|
||||
python -m pip install -r requirements.txt
|
||||
else
|
||||
step "Skip dependency install"
|
||||
fi
|
||||
|
||||
if [[ "$SKIP_CONFIG_HINT" -eq 0 ]]; then
|
||||
step "Current WeCom status"
|
||||
python -m oclaw.runtime.operations channel wecom status || true
|
||||
cat <<'EOF'
|
||||
|
||||
If WeCom is not configured yet, run:
|
||||
python -m oclaw.runtime.operations channel wecom config --help
|
||||
EOF
|
||||
fi
|
||||
|
||||
step "Stopping previous stack"
|
||||
python -m oclaw.runtime.operations stack down || true
|
||||
|
||||
step "Starting stack"
|
||||
python -m oclaw.runtime.operations stack up --channel "$CHANNEL"
|
||||
|
||||
cat <<'EOF'
|
||||
|
||||
Started successfully.
|
||||
Admin: http://127.0.0.1:8787/admin
|
||||
Chat: http://127.0.0.1:8787/chat
|
||||
|
||||
Useful commands:
|
||||
python -m oclaw.runtime.operations stack status
|
||||
python -m oclaw.runtime.operations stack down
|
||||
EOF
|
||||
|
||||
10
runtime/operations/scripts/start_web.ps1
Normal file
10
runtime/operations/scripts/start_web.ps1
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
param(
|
||||
[string]$BindHost = "127.0.0.1",
|
||||
[int]$Port = 8787,
|
||||
[switch]$SkipInstall = $false,
|
||||
[switch]$Background = $false
|
||||
)
|
||||
|
||||
# 网页端(/admin、/chat)由网关进程提供,这里只是一个语义化别名。
|
||||
& "$PSScriptRoot/start_gateway.ps1" -BindHost $BindHost -Port $Port -SkipInstall:$SkipInstall -Background:$Background
|
||||
|
||||
37
runtime/operations/scripts/start_wiki_worker.ps1
Normal file
37
runtime/operations/scripts/start_wiki_worker.ps1
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
param(
|
||||
[switch]$Background = $true
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-RepoRoot {
|
||||
$here = Split-Path -Parent $PSCommandPath
|
||||
return (Resolve-Path (Join-Path $here "..")).Path
|
||||
}
|
||||
|
||||
$repoRoot = Resolve-RepoRoot
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
$null = New-Item -ItemType Directory -Force -Path $runDir -ErrorAction SilentlyContinue
|
||||
$pidFile = Join-Path $runDir "wiki_worker.pid"
|
||||
$outLog = Join-Path $runDir "wiki_worker.out.log"
|
||||
$errLog = Join-Path $runDir "wiki_worker.err.log"
|
||||
|
||||
$venvPython = Join-Path $repoRoot "oclaw/.venv/Scripts/python.exe"
|
||||
if (Test-Path $venvPython) {
|
||||
$pythonExe = $venvPython
|
||||
} else {
|
||||
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue
|
||||
if (-not $pythonCmd) {
|
||||
throw "python not found in PATH"
|
||||
}
|
||||
$pythonExe = "python"
|
||||
}
|
||||
|
||||
if (-not $Background) {
|
||||
& $pythonExe -m oclaw.runtime.workers.wiki.main
|
||||
exit 0
|
||||
}
|
||||
|
||||
$p = Start-Process -FilePath $pythonExe -ArgumentList @("-m", "oclaw.runtime.workers.wiki.main") -WorkingDirectory $repoRoot -PassThru -WindowStyle Hidden -RedirectStandardOutput $outLog -RedirectStandardError $errLog
|
||||
Set-Content -Path $pidFile -Value $p.Id -Encoding ascii
|
||||
Write-Host "[ok] started wiki worker pid=$($p.Id) out=$outLog err=$errLog"
|
||||
140
runtime/operations/scripts/status_all.ps1
Normal file
140
runtime/operations/scripts/status_all.ps1
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
param(
|
||||
[string]$BindHost = "127.0.0.1",
|
||||
[int]$Port = 8787,
|
||||
[switch]$WithWeixin = $false,
|
||||
[switch]$WithWikiWorker = $false,
|
||||
[string]$WeixinChannelId = "oclaw-weixin"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
function Warn([string]$msg) {
|
||||
Write-Host "[WARN] $msg" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
$null = New-Item -ItemType Directory -Force -Path $runDir -ErrorAction SilentlyContinue
|
||||
$gwPidFile = Join-Path $runDir "gateway.pid"
|
||||
$desktopPidFile = Join-Path $runDir "desktop.pid"
|
||||
|
||||
Write-Step "URLs"
|
||||
Write-Host "Admin: http://$BindHost`:$Port/admin"
|
||||
Write-Host "Chat: http://$BindHost`:$Port/chat"
|
||||
Write-Host "WS: ws://$BindHost`:$Port/ws"
|
||||
Write-Host ""
|
||||
|
||||
Write-Step "PID files"
|
||||
if (Test-Path $gwPidFile) {
|
||||
$gwPid = (Get-Content $gwPidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
Write-Host "gateway.pid: $gwPidFile => $gwPid"
|
||||
} else {
|
||||
Warn "gateway.pid not found: $gwPidFile"
|
||||
}
|
||||
if (Test-Path $desktopPidFile) {
|
||||
$deskPid = (Get-Content $desktopPidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
Write-Host "desktop.pid: $desktopPidFile => $deskPid"
|
||||
} else {
|
||||
Warn "desktop.pid not found: $desktopPidFile"
|
||||
}
|
||||
Write-Host ""
|
||||
|
||||
Write-Step "Port listener"
|
||||
try {
|
||||
$conns = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
|
||||
if (-not $conns) {
|
||||
Warn "No listener on port $Port"
|
||||
exit 0
|
||||
}
|
||||
$pids = $conns | Select-Object -ExpandProperty OwningProcess -Unique
|
||||
Write-Host "Listening on port $Port; OwningProcess: $($pids -join ', ')"
|
||||
|
||||
# Self-heal: if we have a single owning pid and no gateway.pid, write it back.
|
||||
if (-not (Test-Path $gwPidFile)) {
|
||||
$pidList = @()
|
||||
foreach ($x in @($pids)) {
|
||||
$n = 0
|
||||
if ([int]::TryParse([string]$x, [ref]$n) -and $n -gt 0) {
|
||||
$pidList += $n
|
||||
}
|
||||
}
|
||||
if ($pidList.Count -eq 1) {
|
||||
$procId = [int]$pidList[0]
|
||||
try {
|
||||
$null = Get-Process -Id $procId -ErrorAction Stop
|
||||
Set-Content -Path $gwPidFile -Value "$procId" -Encoding ascii
|
||||
Write-Host "Wrote gateway.pid => $procId" -ForegroundColor Green
|
||||
} catch {
|
||||
Warn "Cannot verify process for PID=$procId; not writing pid file."
|
||||
}
|
||||
} else {
|
||||
# Heuristic: try to pick the gateway python/uvicorn process.
|
||||
$candidates = @()
|
||||
foreach ($p in $pidList) {
|
||||
try {
|
||||
$proc = Get-Process -Id $p -ErrorAction Stop
|
||||
$name = [string]$proc.ProcessName
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
$cmd = ""
|
||||
try {
|
||||
$wmi = Get-CimInstance Win32_Process -Filter "ProcessId=$p" -ErrorAction SilentlyContinue
|
||||
if ($wmi -and $wmi.CommandLine) { $cmd = [string]$wmi.CommandLine }
|
||||
} catch {
|
||||
$cmd = ""
|
||||
}
|
||||
if ($cmd) {
|
||||
$low = ([string]$cmd).ToLowerInvariant()
|
||||
} else {
|
||||
$low = ""
|
||||
}
|
||||
$score = 0
|
||||
if ($name -match "python") { $score += 2 }
|
||||
if ($low -match "uvicorn") { $score += 2 }
|
||||
if ($low -match "src\.ops") { $score += 2 }
|
||||
if ($low -match "gateway\s+start") { $score += 2 }
|
||||
if ($low -match "fastapi_app") { $score += 1 }
|
||||
$candidates += [pscustomobject]@{ Pid = [int]$p; Name = $name; Score = [int]$score; Cmd = $cmd }
|
||||
}
|
||||
$best = $candidates | Sort-Object -Property Score -Descending | Select-Object -First 1
|
||||
if ($best -and $best.Score -ge 2) {
|
||||
try {
|
||||
$null = Get-Process -Id $best.Pid -ErrorAction Stop
|
||||
Set-Content -Path $gwPidFile -Value "$($best.Pid)" -Encoding ascii
|
||||
Write-Host "Wrote gateway.pid => $($best.Pid) ($($best.Name))" -ForegroundColor Green
|
||||
} catch {
|
||||
Warn "Cannot verify process for PID=$($best.Pid); not writing pid file."
|
||||
}
|
||||
} else {
|
||||
Warn "Multiple owning processes for port $Port; cannot confidently pick gateway PID."
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Warn "Get-NetTCPConnection failed: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
if ($WithWeixin) {
|
||||
Write-Host ""
|
||||
Write-Step "Weixin sidecar"
|
||||
try {
|
||||
& "$PSScriptRoot/weixin_status.ps1" -ChannelId $WeixinChannelId
|
||||
} catch {
|
||||
Warn "weixin status failed: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($WithWikiWorker) {
|
||||
Write-Host ""
|
||||
Write-Step "Wiki worker"
|
||||
try {
|
||||
& "$PSScriptRoot/status_wiki_worker.ps1"
|
||||
} catch {
|
||||
Warn "wiki worker status failed: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
21
runtime/operations/scripts/status_ops.ps1
Normal file
21
runtime/operations/scripts/status_ops.ps1
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $repoRoot
|
||||
|
||||
Write-Step "Project root: $repoRoot"
|
||||
Write-Step "Stack status"
|
||||
python -m oclaw.runtime.operations stack status
|
||||
|
||||
Write-Host ""
|
||||
Write-Step "WeCom status"
|
||||
python -m oclaw.runtime.operations channel wecom status
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Admin: http://127.0.0.1:8787/admin"
|
||||
Write-Host "Chat: http://127.0.0.1:8787/chat"
|
||||
|
||||
19
runtime/operations/scripts/status_ops.sh
Normal file
19
runtime/operations/scripts/status_ops.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
printf '==> Project root: %s\n' "$ROOT_DIR"
|
||||
printf '==> Stack status\n'
|
||||
python -m oclaw.runtime.operations stack status
|
||||
|
||||
printf '\n==> WeCom status\n'
|
||||
python -m oclaw.runtime.operations channel wecom status
|
||||
|
||||
cat <<'EOF'
|
||||
|
||||
Admin: http://127.0.0.1:8787/admin
|
||||
Chat: http://127.0.0.1:8787/chat
|
||||
EOF
|
||||
|
||||
23
runtime/operations/scripts/status_wiki_worker.ps1
Normal file
23
runtime/operations/scripts/status_wiki_worker.ps1
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
param()
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
$pidFile = Join-Path $runDir "wiki_worker.pid"
|
||||
|
||||
if (-not (Test-Path $pidFile)) {
|
||||
Write-Host "status=stopped"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$procId = (Get-Content -Path $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
if (-not $procId) {
|
||||
Write-Host "status=stopped"
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
Get-Process -Id $procId -ErrorAction Stop | Out-Null
|
||||
Write-Host "status=running pid=$procId"
|
||||
} catch {
|
||||
Write-Host "status=stale_pid pid=$procId"
|
||||
}
|
||||
48
runtime/operations/scripts/stop_all.ps1
Normal file
48
runtime/operations/scripts/stop_all.ps1
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
param(
|
||||
[int]$Port = 8787,
|
||||
[switch]$Force = $false,
|
||||
[switch]$WithWeixin = $false,
|
||||
[switch]$WithWikiWorker = $false,
|
||||
[string]$WeixinChannelId = "oclaw-weixin"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
Write-Step "Stopping desktop"
|
||||
try {
|
||||
& "$PSScriptRoot/stop_desktop.ps1" -Force:$Force
|
||||
} catch {
|
||||
if (-not $Force) { throw }
|
||||
}
|
||||
|
||||
Write-Step "Stopping gateway/web"
|
||||
try {
|
||||
& "$PSScriptRoot/stop_gateway.ps1" -Port $Port -Force:$Force
|
||||
} catch {
|
||||
if (-not $Force) { throw }
|
||||
}
|
||||
|
||||
if ($WithWeixin) {
|
||||
Write-Step "Stopping weixin sidecar"
|
||||
try {
|
||||
& "$PSScriptRoot/weixin_stop.ps1" -ChannelId $WeixinChannelId -Force:$Force
|
||||
} catch {
|
||||
if (-not $Force) { throw }
|
||||
}
|
||||
}
|
||||
if ($WithWikiWorker) {
|
||||
Write-Step "Stopping wiki worker"
|
||||
try {
|
||||
& "$PSScriptRoot/stop_wiki_worker.ps1" -Force:$Force
|
||||
} catch {
|
||||
if (-not $Force) { throw }
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "All stopped." -ForegroundColor Green
|
||||
|
||||
45
runtime/operations/scripts/stop_desktop.ps1
Normal file
45
runtime/operations/scripts/stop_desktop.ps1
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
param(
|
||||
[switch]$Force = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
function Warn([string]$msg) {
|
||||
Write-Host "[WARN] $msg" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
$pidFile = Join-Path $runDir "desktop.pid"
|
||||
|
||||
Write-Step "Stopping desktop app"
|
||||
|
||||
if (-not (Test-Path $pidFile)) {
|
||||
Warn "No PID file found: $pidFile"
|
||||
if (-not $Force) { exit 0 }
|
||||
}
|
||||
|
||||
$raw = (Get-Content $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
$procId = 0
|
||||
[void][int]::TryParse([string]$raw, [ref]$procId)
|
||||
if ($procId -le 0) {
|
||||
Warn "Invalid PID in $pidFile"
|
||||
if (-not $Force) { exit 1 }
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
# Kill the whole process tree (cmd -> npm -> electron/node)
|
||||
& taskkill /PID $procId /T /F | Out-Null
|
||||
Write-Host "Stopped PID=$procId (tree)" -ForegroundColor Green
|
||||
Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
|
||||
exit 0
|
||||
} catch {
|
||||
Warn "Failed to stop PID=$procId : $($_.Exception.Message)"
|
||||
if (-not $Force) { exit 1 }
|
||||
exit 0
|
||||
}
|
||||
|
||||
62
runtime/operations/scripts/stop_gateway.ps1
Normal file
62
runtime/operations/scripts/stop_gateway.ps1
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
param(
|
||||
[int]$Port = 8787,
|
||||
[switch]$Force = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
function Warn([string]$msg) {
|
||||
Write-Host "[WARN] $msg" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
function Kill-ProcId([int]$procId) {
|
||||
try {
|
||||
Stop-Process -Id $procId -Force
|
||||
Write-Host "Stopped PID=$procId" -ForegroundColor Green
|
||||
return $true
|
||||
} catch {
|
||||
Warn "Failed to stop PID=$procId : $($_.Exception.Message)"
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
$pidFile = Join-Path $runDir "gateway.pid"
|
||||
|
||||
Write-Step "Stopping gateway"
|
||||
|
||||
if (Test-Path $pidFile) {
|
||||
$raw = (Get-Content $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
$procId = 0
|
||||
[void][int]::TryParse([string]$raw, [ref]$procId)
|
||||
if ($procId -gt 0) {
|
||||
$ok = Kill-ProcId -procId $procId
|
||||
if ($ok) {
|
||||
Remove-Item $pidFile -Force -ErrorAction SilentlyContinue
|
||||
exit 0
|
||||
}
|
||||
if (-not $Force) { exit 1 }
|
||||
}
|
||||
}
|
||||
|
||||
Write-Step "No PID file; attempting to stop by port $Port"
|
||||
try {
|
||||
$conns = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
|
||||
if (-not $conns) {
|
||||
Warn "No listener found on port $Port"
|
||||
exit 0
|
||||
}
|
||||
$pids = $conns | Select-Object -ExpandProperty OwningProcess -Unique
|
||||
foreach ($p in $pids) {
|
||||
if ($p -gt 0) { [void](Kill-ProcId -procId $p) }
|
||||
}
|
||||
exit 0
|
||||
} catch {
|
||||
Warn "Stop by port failed: $($_.Exception.Message)"
|
||||
if (-not $Force) { exit 1 }
|
||||
}
|
||||
|
||||
33
runtime/operations/scripts/stop_ops.ps1
Normal file
33
runtime/operations/scripts/stop_ops.ps1
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
param(
|
||||
[switch]$Force = $false
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Write-Step([string]$msg) {
|
||||
Write-Host "==> $msg" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
|
||||
Set-Location $repoRoot
|
||||
|
||||
Write-Step "Project root: $repoRoot"
|
||||
Write-Step "Stopping stack services..."
|
||||
|
||||
try {
|
||||
python -m oclaw.runtime.operations stack down
|
||||
Write-Host "Stack stopped." -ForegroundColor Green
|
||||
} catch {
|
||||
Write-Host "[WARN] stack down failed: $($_.Exception.Message)" -ForegroundColor Yellow
|
||||
if (-not $Force) {
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Write-Step "Current status"
|
||||
try {
|
||||
python -m oclaw.runtime.operations stack status
|
||||
} catch {
|
||||
Write-Host "[WARN] Unable to read status after stop." -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
13
runtime/operations/scripts/stop_ops.sh
Normal file
13
runtime/operations/scripts/stop_ops.sh
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
printf '==> Project root: %s\n' "$ROOT_DIR"
|
||||
printf '==> Stopping stack services...\n'
|
||||
python -m oclaw.runtime.operations stack down || true
|
||||
|
||||
printf '\n==> Current status\n'
|
||||
python -m oclaw.runtime.operations stack status || true
|
||||
|
||||
8
runtime/operations/scripts/stop_web.ps1
Normal file
8
runtime/operations/scripts/stop_web.ps1
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
param(
|
||||
[int]$Port = 8787,
|
||||
[switch]$Force = $false
|
||||
)
|
||||
|
||||
# 网页端(/admin、/chat)由网关进程提供,这里只是一个语义化别名。
|
||||
& "$PSScriptRoot/stop_gateway.ps1" -Port $Port -Force:$Force
|
||||
|
||||
31
runtime/operations/scripts/stop_wiki_worker.ps1
Normal file
31
runtime/operations/scripts/stop_wiki_worker.ps1
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
param(
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$runDir = Join-Path $PSScriptRoot ".run"
|
||||
$pidFile = Join-Path $runDir "wiki_worker.pid"
|
||||
|
||||
if (-not (Test-Path $pidFile)) {
|
||||
Write-Host "[ok] not running (no pid file)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$procId = (Get-Content -Path $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
if (-not $procId) {
|
||||
Remove-Item -Force $pidFile -ErrorAction SilentlyContinue
|
||||
Write-Host "[ok] not running (empty pid file)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
if ($Force) {
|
||||
taskkill.exe /PID $procId /T /F | Out-Null
|
||||
} else {
|
||||
taskkill.exe /PID $procId /T | Out-Null
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
|
||||
Remove-Item -Force $pidFile -ErrorAction SilentlyContinue
|
||||
Write-Host "[ok] stopped pid=$procId"
|
||||
48
runtime/operations/scripts/switch_wecom_bot.py
Normal file
48
runtime/operations/scripts/switch_wecom_bot.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
_CLEAR_KEYS = [
|
||||
"wecom_access_token_cache",
|
||||
"wecom_last_msg_ts",
|
||||
"wecom_last_from_user",
|
||||
"wecom_recent_from_users",
|
||||
"wecom_last_cmd",
|
||||
"wecom_last_unknown_cmd_payload",
|
||||
"wecom_last_raw_body",
|
||||
"wecom_last_raw_from_user",
|
||||
"wecom_last_parse_error",
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = [str(x).strip() for x in sys.argv[1:]]
|
||||
if len(args) < 2:
|
||||
print("usage: python -m scripts.switch_wecom_bot <bot_id> <bot_secret>")
|
||||
return 2
|
||||
bot_id, bot_secret = args[0], args[1]
|
||||
if not bot_id or not bot_secret:
|
||||
print("error=missing_required_args")
|
||||
return 2
|
||||
|
||||
store = SqliteStore(db_path())
|
||||
store.set_setting("wecom_mode", "bot_api")
|
||||
store.set_setting("wecom_bot_id", bot_id)
|
||||
store.set_secret("wecom_bot_secret", bot_secret)
|
||||
for k in _CLEAR_KEYS:
|
||||
store.delete_setting(k)
|
||||
|
||||
print("ok=1")
|
||||
print("mode=bot_api")
|
||||
print(f"bot_id={bot_id}")
|
||||
print("cleared=" + ",".join(_CLEAR_KEYS))
|
||||
print("next=python -m oclaw.runtime.operations stack up --channel wecom")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
47
runtime/operations/scripts/unbind_wecom_bot.py
Normal file
47
runtime/operations/scripts/unbind_wecom_bot.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
_CLEAR_KEYS = [
|
||||
"wecom_mode",
|
||||
"wecom_bot_id",
|
||||
"wecom_bot_secret",
|
||||
"wecom_corp_id",
|
||||
"wecom_agent_id",
|
||||
"wecom_agent_secret",
|
||||
"wecom_access_token_cache",
|
||||
"wecom_last_msg_ts",
|
||||
"wecom_last_from_user",
|
||||
"wecom_recent_from_users",
|
||||
"wecom_last_cmd",
|
||||
"wecom_last_unknown_cmd_payload",
|
||||
"wecom_last_raw_body",
|
||||
"wecom_last_raw_from_user",
|
||||
"wecom_last_parse_error",
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
store = SqliteStore(db_path())
|
||||
with store._connect() as conn: # internal cleanup script; safe to use store connection helper
|
||||
cur_ident = conn.execute("DELETE FROM channel_identity WHERE channel = ?", ("wecom",))
|
||||
ident_deleted = int(cur_ident.rowcount or 0)
|
||||
cur_sess = conn.execute("DELETE FROM channel_session WHERE channel = ?", ("wecom",))
|
||||
sess_deleted = int(cur_sess.rowcount or 0)
|
||||
|
||||
for k in _CLEAR_KEYS:
|
||||
store.delete_setting(k)
|
||||
|
||||
print("ok=1")
|
||||
print("action=unbind_wecom_bot")
|
||||
print(f"deleted_channel_identity={ident_deleted}")
|
||||
print(f"deleted_channel_session={sess_deleted}")
|
||||
print("cleared_settings=" + ",".join(_CLEAR_KEYS))
|
||||
print("next=python -m oclaw.runtime.operations channel wecom config set --type bot --bot-id <bot_id> --bot-secret <bot_secret>")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
58
runtime/operations/scripts/verify_forwarders.py
Normal file
58
runtime/operations/scripts/verify_forwarders.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from oclaw.platform.config.runtime_paths import oclaw_root, runtime_operations_scripts_root
|
||||
|
||||
|
||||
def verify_forwarders() -> tuple[bool, list[str]]:
|
||||
root_scripts = (oclaw_root() / "scripts").resolve()
|
||||
real_scripts = runtime_operations_scripts_root()
|
||||
errors: list[str] = []
|
||||
required = [
|
||||
"start_all.ps1",
|
||||
"start_gateway.ps1",
|
||||
"start_desktop.ps1",
|
||||
"start_ops.ps1",
|
||||
"start_ops.sh",
|
||||
"status_ops.sh",
|
||||
"stop_ops.sh",
|
||||
]
|
||||
for name in required:
|
||||
rp = root_scripts / name
|
||||
if not rp.exists():
|
||||
errors.append(f"missing forwarder: {rp}")
|
||||
continue
|
||||
tp = real_scripts / name
|
||||
if not tp.exists():
|
||||
errors.append(f"missing target: {tp}")
|
||||
continue
|
||||
text = rp.read_text(encoding="utf-8", errors="ignore")
|
||||
normalized = text.replace("\\", "/")
|
||||
while "//" in normalized:
|
||||
normalized = normalized.replace("//", "/")
|
||||
marker_exact = f"runtime/operations/scripts/{name}".replace("\\", "/")
|
||||
marker_base = "runtime/operations/scripts"
|
||||
if name.endswith(".sh"):
|
||||
ok = (marker_base in normalized) and (f"/{name}" in normalized)
|
||||
else:
|
||||
ok = marker_exact in normalized
|
||||
if not ok:
|
||||
errors.append(f"forwarder target mismatch: {rp}")
|
||||
return (len(errors) == 0), errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ok, errors = verify_forwarders()
|
||||
if ok:
|
||||
print("forwarders_ok=1")
|
||||
return 0
|
||||
print("forwarders_ok=0")
|
||||
for err in errors:
|
||||
print(err)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
60
runtime/operations/scripts/wecom_smoke_test.py
Normal file
60
runtime/operations/scripts/wecom_smoke_test.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.integrations.wecom_client import WeComClient
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def main() -> int:
|
||||
store = SqliteStore(db_path())
|
||||
client = WeComClient(store)
|
||||
try:
|
||||
bot_id, _bot_secret = client.get_bot_credentials()
|
||||
except Exception as exc:
|
||||
print("ok=0")
|
||||
print("step=read_bot_config")
|
||||
print(f"error={type(exc).__name__}: {exc}")
|
||||
return 1
|
||||
print("ok=1")
|
||||
print("mode=bot_api")
|
||||
print(f"bot_id={bot_id}")
|
||||
if "--ws" not in sys.argv[1:]:
|
||||
print("ws_skipped=1")
|
||||
print("hint=use --ws for subscribe handshake test")
|
||||
return 0
|
||||
try:
|
||||
import websocket # type: ignore
|
||||
except Exception:
|
||||
print("ok=0")
|
||||
print("step=import_websocket_client")
|
||||
print("error=websocket-client not installed, run: pip install websocket-client")
|
||||
return 1
|
||||
try:
|
||||
ws = websocket.create_connection("wss://openws.work.weixin.qq.com", timeout=15)
|
||||
ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"cmd": "aibot_subscribe",
|
||||
"headers": {"req_id": uuid.uuid4().hex},
|
||||
"body": {"bot_id": bot_id, "secret": client.get_bot_credentials()[1]},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
raw = ws.recv()
|
||||
ws.close()
|
||||
print("ws_subscribe_response=" + str(raw))
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print("ok=0")
|
||||
print("step=ws_subscribe")
|
||||
print(f"error={type(exc).__name__}: {exc}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
78
runtime/operations/scripts/wecom_status.py
Normal file
78
runtime/operations/scripts/wecom_status.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from oclaw.platform.config.paths import db_path
|
||||
from oclaw.platform.integrations.wecom_client import WeComClient
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def _fmt_ts(ts: str) -> str:
|
||||
try:
|
||||
n = int(str(ts).strip())
|
||||
return datetime.fromtimestamp(n, tz=timezone.utc).astimezone().isoformat()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
store = SqliteStore(db_path())
|
||||
client = WeComClient(store)
|
||||
print("ok=1")
|
||||
print(f"mode={client.mode()}")
|
||||
bot_id = str(store.get_setting("wecom_bot_id") or "").strip()
|
||||
print(f"bot_id={bot_id}")
|
||||
|
||||
auto_bind = str(store.get_setting("wecom_auto_bind_enabled") or "1").strip()
|
||||
auto_tenant = str(store.get_setting("wecom_auto_bind_tenant_name") or "Team").strip() or "Team"
|
||||
auto_role = str(store.get_setting("wecom_auto_bind_role") or "member").strip() or "member"
|
||||
print(f"auto_bind_enabled={auto_bind}")
|
||||
print(f"auto_bind_tenant={auto_tenant}")
|
||||
print(f"auto_bind_role={auto_role}")
|
||||
|
||||
last_ts = str(store.get_setting("wecom_last_msg_ts") or "").strip()
|
||||
last_user = str(store.get_setting("wecom_last_from_user") or "").strip()
|
||||
last_cmd = str(store.get_setting("wecom_last_cmd") or "").strip()
|
||||
last_raw_from_user = str(store.get_setting("wecom_last_raw_from_user") or "").strip()
|
||||
last_parse_error = str(store.get_setting("wecom_last_parse_error") or "").strip()
|
||||
last_outbound_mode = str(store.get_setting("wecom_last_outbound_mode") or "").strip()
|
||||
last_outbound_error = str(store.get_setting("wecom_last_outbound_error") or "").strip()
|
||||
print(f"last_from_user={last_user}")
|
||||
print(f"last_raw_from_user={last_raw_from_user}")
|
||||
print(f"last_cmd={last_cmd}")
|
||||
print(f"last_parse_error={last_parse_error}")
|
||||
print(f"last_outbound_mode={last_outbound_mode}")
|
||||
print(f"last_outbound_error={last_outbound_error}")
|
||||
print(f"last_msg_ts={last_ts}")
|
||||
print(f"last_msg_local={_fmt_ts(last_ts)}")
|
||||
|
||||
raw_recent = str(store.get_setting("wecom_recent_from_users") or "[]")
|
||||
try:
|
||||
recent = json.loads(raw_recent)
|
||||
except Exception:
|
||||
recent = []
|
||||
if not isinstance(recent, list):
|
||||
recent = []
|
||||
print("recent_from_users=" + json.dumps(recent[:20], ensure_ascii=False))
|
||||
|
||||
idents = store.list_channel_identities(channel="wecom", limit=50)
|
||||
print(f"bound_identities={len(idents)}")
|
||||
for x in idents[:20]:
|
||||
print(
|
||||
"identity="
|
||||
+ json.dumps(
|
||||
{
|
||||
"external_user_id": x.get("external_user_id"),
|
||||
"display_name": x.get("display_name"),
|
||||
"role": x.get("role"),
|
||||
"tenant_id": x.get("tenant_id"),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
41
runtime/operations/scripts/weixin_install.ps1
Normal file
41
runtime/operations/scripts/weixin_install.ps1
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
param(
|
||||
[string]$ChannelId = "oclaw-weixin",
|
||||
[string]$Package = "@tencent-weixin/oclaw-weixin@2.1.9",
|
||||
[string]$OclawRuntime = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-RepoRoot {
|
||||
$here = Split-Path -Parent $PSCommandPath
|
||||
return (Resolve-Path (Join-Path $here "..")).Path
|
||||
}
|
||||
|
||||
$oclawRoot = Resolve-RepoRoot
|
||||
$sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
||||
$stateDir = Join-Path $sidecarRoot "state"
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $sidecarRoot | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $sidecarRoot "logs") | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path $stateDir | Out-Null
|
||||
|
||||
Push-Location $sidecarRoot
|
||||
try {
|
||||
if (-not (Test-Path (Join-Path $sidecarRoot "package.json"))) {
|
||||
npm.cmd init -y | Out-Null
|
||||
}
|
||||
if (Test-Path (Join-Path $sidecarRoot "package-lock.json")) {
|
||||
npm.cmd ci
|
||||
} else {
|
||||
# First-time setup: install exact versions for reproducible sidecar runtime.
|
||||
if ($OclawRuntime) {
|
||||
npm.cmd install --save-exact $Package $OclawRuntime tsx@4.21.0 typescript@6.0.3
|
||||
} else {
|
||||
npm.cmd install --save-exact $Package tsx@4.21.0 typescript@6.0.3
|
||||
}
|
||||
}
|
||||
Write-Host "[ok] installed $Package into $sidecarRoot"
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
32
runtime/operations/scripts/weixin_login.ps1
Normal file
32
runtime/operations/scripts/weixin_login.ps1
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
param(
|
||||
[string]$ChannelId = "oclaw-weixin"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-RepoRoot {
|
||||
$here = Split-Path -Parent $PSCommandPath
|
||||
return (Resolve-Path (Join-Path $here "..")).Path
|
||||
}
|
||||
|
||||
$oclawRoot = Resolve-RepoRoot
|
||||
$sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
||||
$stateDir = Join-Path $sidecarRoot "state"
|
||||
|
||||
if (-not (Test-Path $sidecarRoot)) {
|
||||
throw "sidecar not installed: run .\\scripts\\weixin_install.ps1 first"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $stateDir | Out-Null
|
||||
|
||||
Push-Location $sidecarRoot
|
||||
try {
|
||||
$env:OCLAW_STATE_DIR = $stateDir
|
||||
if (-not (Test-Path (Join-Path $sidecarRoot "login.ts"))) {
|
||||
throw "missing login.ts"
|
||||
}
|
||||
npm.cmd exec -- tsx login.ts
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
39
runtime/operations/scripts/weixin_start.ps1
Normal file
39
runtime/operations/scripts/weixin_start.ps1
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
param(
|
||||
[string]$ChannelId = "oclaw-weixin",
|
||||
[string]$GatewayBaseUrl = "http://127.0.0.1:8787"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-RepoRoot {
|
||||
$here = Split-Path -Parent $PSCommandPath
|
||||
return (Resolve-Path (Join-Path $here "..")).Path
|
||||
}
|
||||
|
||||
$oclawRoot = Resolve-RepoRoot
|
||||
$sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
||||
$stateDir = Join-Path $sidecarRoot "state"
|
||||
$logDir = Join-Path $sidecarRoot "logs"
|
||||
$pidFile = Join-Path $sidecarRoot "pid.txt"
|
||||
|
||||
if (-not (Test-Path $sidecarRoot)) {
|
||||
throw "sidecar not installed: run .\\scripts\\weixin_install.ps1 first"
|
||||
}
|
||||
if (-not (Test-Path (Join-Path $sidecarRoot "runner.ts"))) {
|
||||
throw "missing runner.ts (sidecar code). Re-run repo sync or restore file."
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path $stateDir | Out-Null
|
||||
|
||||
$logPath = Join-Path $logDir "weixin_sidecar.log"
|
||||
$errPath = Join-Path $logDir "weixin_sidecar.err.log"
|
||||
$cmd = "cmd.exe"
|
||||
$args = @(
|
||||
"/c",
|
||||
"cd /d $sidecarRoot && set OCLAW_STATE_DIR=$stateDir&& set AIA_GATEWAY_BASE_URL=$GatewayBaseUrl&& npm.cmd exec -- tsx runner.ts"
|
||||
)
|
||||
|
||||
$p = Start-Process -FilePath $cmd -ArgumentList $args -WorkingDirectory $sidecarRoot -PassThru -WindowStyle Hidden -RedirectStandardOutput $logPath -RedirectStandardError $errPath
|
||||
Set-Content -Path $pidFile -Value $p.Id
|
||||
Write-Host "[ok] started weixin sidecar pid=$($p.Id) out=$logPath err=$errPath"
|
||||
|
||||
38
runtime/operations/scripts/weixin_status.ps1
Normal file
38
runtime/operations/scripts/weixin_status.ps1
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
param(
|
||||
[string]$ChannelId = "oclaw-weixin"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-RepoRoot {
|
||||
$here = Split-Path -Parent $PSCommandPath
|
||||
return (Resolve-Path (Join-Path $here "..")).Path
|
||||
}
|
||||
|
||||
$oclawRoot = Resolve-RepoRoot
|
||||
$sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
||||
$pidFile = Join-Path $sidecarRoot "pid.txt"
|
||||
|
||||
if (-not (Test-Path $pidFile)) {
|
||||
Write-Host "status=stopped"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$procId = (Get-Content -Path $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
if (-not $procId) {
|
||||
Write-Host "status=stopped"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$exists = $false
|
||||
try {
|
||||
Get-Process -Id $procId -ErrorAction Stop | Out-Null
|
||||
$exists = $true
|
||||
} catch {}
|
||||
|
||||
if ($exists) {
|
||||
Write-Host "status=running pid=$procId"
|
||||
} else {
|
||||
Write-Host "status=stale_pid pid=$procId"
|
||||
}
|
||||
|
||||
41
runtime/operations/scripts/weixin_stop.ps1
Normal file
41
runtime/operations/scripts/weixin_stop.ps1
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
param(
|
||||
[string]$ChannelId = "oclaw-weixin",
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-RepoRoot {
|
||||
$here = Split-Path -Parent $PSCommandPath
|
||||
return (Resolve-Path (Join-Path $here "..")).Path
|
||||
}
|
||||
|
||||
$oclawRoot = Resolve-RepoRoot
|
||||
$sidecarRoot = Join-Path $oclawRoot "data\\channel_sidecar\\$ChannelId"
|
||||
$pidFile = Join-Path $sidecarRoot "pid.txt"
|
||||
|
||||
if (-not (Test-Path $pidFile)) {
|
||||
Write-Host "[ok] not running (no pid file)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$procId = (Get-Content -Path $pidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
if (-not $procId) {
|
||||
Remove-Item -Force $pidFile -ErrorAction SilentlyContinue
|
||||
Write-Host "[ok] not running (empty pid file)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
try {
|
||||
if ($Force) {
|
||||
taskkill.exe /PID $procId /T /F | Out-Null
|
||||
} else {
|
||||
taskkill.exe /PID $procId /T | Out-Null
|
||||
}
|
||||
} catch {
|
||||
# Ignore if already dead.
|
||||
}
|
||||
|
||||
Remove-Item -Force $pidFile -ErrorAction SilentlyContinue
|
||||
Write-Host "[ok] stopped pid=$procId"
|
||||
|
||||
100
runtime/operations/scripts/wiki_auto_smoke_test.py
Normal file
100
runtime/operations/scripts/wiki_auto_smoke_test.py
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(_REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_REPO_ROOT))
|
||||
|
||||
from oclaw.platform.config.paths import PROJECT_ROOT, db_path
|
||||
from oclaw.platform.persistence.sqlite_store import SqliteStore
|
||||
|
||||
|
||||
def _load_cfg() -> dict:
|
||||
cfg_file = (Path(PROJECT_ROOT) / "oclaw" / "oclaw.json").resolve()
|
||||
if not cfg_file.exists():
|
||||
return {}
|
||||
try:
|
||||
obj = json.loads(cfg_file.read_text(encoding="utf-8"))
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _wiki_root_from_cfg(cfg: dict) -> Path:
|
||||
plugins = cfg.get("plugins") if isinstance(cfg, dict) else {}
|
||||
entries = plugins.get("entries") if isinstance(plugins, dict) else {}
|
||||
mw = entries.get("memory-wiki") if isinstance(entries, dict) else {}
|
||||
root_cfg = str((mw or {}).get("wiki_root") or "oclaw/docs/memory-system/wiki").strip()
|
||||
root = Path(root_cfg)
|
||||
if not root.is_absolute():
|
||||
root = (Path(PROJECT_ROOT) / root).resolve()
|
||||
return root
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Smoke test for wiki auto pipeline.")
|
||||
parser.add_argument("--timeout-s", type=int, default=30, help="Task wait timeout in seconds.")
|
||||
args = parser.parse_args()
|
||||
|
||||
cfg = _load_cfg()
|
||||
wiki_root = _wiki_root_from_cfg(cfg)
|
||||
store = SqliteStore(db_path())
|
||||
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
payload = {
|
||||
"kind": "captureAfterTurn",
|
||||
"session_id": f"smoke-session-{suffix}",
|
||||
"tenant_id": "default",
|
||||
"user_id": "smoke-user",
|
||||
"turn_uuid": f"smoke-turn-{suffix}",
|
||||
"user_text": "smoke router vlan check",
|
||||
"assistant_text": "smoke response for wiki worker",
|
||||
}
|
||||
task = store.oclaw_task_create(
|
||||
tenant_id="default",
|
||||
session_id=payload["session_id"],
|
||||
task_type="wiki_capture",
|
||||
payload=payload,
|
||||
)
|
||||
print(f"[smoke] created task: {task.id}")
|
||||
|
||||
deadline = time.time() + max(5, int(args.timeout_s))
|
||||
final = task
|
||||
while time.time() < deadline:
|
||||
got = store.oclaw_task_get(task_id=task.id)
|
||||
if got is None:
|
||||
print("[smoke] task missing")
|
||||
return 2
|
||||
final = got
|
||||
if final.status in {"done", "failed"}:
|
||||
break
|
||||
time.sleep(1.0)
|
||||
|
||||
print(f"[smoke] final status: {final.status}")
|
||||
if final.status not in {"done", "failed"}:
|
||||
print("[smoke] timeout waiting for worker")
|
||||
return 3
|
||||
|
||||
artifacts = {
|
||||
"merged_turns": wiki_root / "inbox" / "merged-turns.md",
|
||||
"topic_index": wiki_root / ".oclaw" / "topic-index.json",
|
||||
"index": wiki_root / ".oclaw" / "index.json",
|
||||
"lint_report": wiki_root / ".oclaw" / "LINT_REPORT.md",
|
||||
}
|
||||
for name, fp in artifacts.items():
|
||||
print(f"[smoke] {name}: {'ok' if fp.exists() else 'missing'} ({fp})")
|
||||
|
||||
if final.status == "failed":
|
||||
print(f"[smoke] worker error: {final.last_error}")
|
||||
return 4
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
91
runtime/operations/scripts/ws_probe.py
Normal file
91
runtime/operations/scripts/ws_probe.py
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import websockets
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
ws_url = "ws://127.0.0.1:8790/ws"
|
||||
t0 = time.time()
|
||||
async with websockets.connect(ws_url, open_timeout=5) as ws:
|
||||
challenge = json.loads(await ws.recv())
|
||||
print("challenge", challenge.get("event"), challenge.get("payload", {}).get("nonce"))
|
||||
nonce = challenge.get("payload", {}).get("nonce", "")
|
||||
|
||||
req_id = uuid.uuid4().hex
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "req",
|
||||
"id": req_id,
|
||||
"method": "connect",
|
||||
"params": {
|
||||
"minProtocol": 3,
|
||||
"maxProtocol": 3,
|
||||
"client": {"id": "probe", "mode": "cli", "version": "0.0.0", "platform": "cli"},
|
||||
"device": {
|
||||
"id": uuid.uuid4().hex,
|
||||
"publicKey": "dummy",
|
||||
"signature": "dummy",
|
||||
"signedAt": int(time.time() * 1000),
|
||||
"nonce": nonce,
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
hello = json.loads(await ws.recv())
|
||||
print("hello", hello)
|
||||
|
||||
session_key = uuid.uuid4().hex
|
||||
req_id2 = uuid.uuid4().hex
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "req",
|
||||
"id": req_id2,
|
||||
"method": "chat.send",
|
||||
"params": {
|
||||
"sessionKey": session_key,
|
||||
"idempotencyKey": uuid.uuid4().hex,
|
||||
"message": "hi streaming test",
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
got_delta = False
|
||||
first_delta_at: float | None = None
|
||||
while True:
|
||||
msg = json.loads(await ws.recv())
|
||||
if msg.get("type") == "res" and msg.get("id") == req_id2:
|
||||
print("chat.send res", msg)
|
||||
continue
|
||||
if msg.get("type") == "event" and msg.get("event") == "chat":
|
||||
st = (msg.get("payload") or {}).get("state")
|
||||
if st == "delta":
|
||||
if not got_delta:
|
||||
got_delta = True
|
||||
first_delta_at = time.time() - t0
|
||||
if st in ("final", "error"):
|
||||
pl = msg.get("payload") or {}
|
||||
print(
|
||||
"final_state",
|
||||
st,
|
||||
"got_delta",
|
||||
got_delta,
|
||||
"first_delta_at",
|
||||
first_delta_at,
|
||||
"reply_preview",
|
||||
str(pl.get("reply") or "")[:120],
|
||||
)
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
91
runtime/operations/stack.py
Normal file
91
runtime/operations/stack.py
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from .mcp_env import gateway_mcp_env_extras
|
||||
from .runtime import default_python_command, start_service, status_services, stop_all
|
||||
|
||||
|
||||
def cmd_stack_up(args: argparse.Namespace) -> int:
|
||||
started: list[tuple[str, int]] = []
|
||||
gateway_cmd = default_python_command(
|
||||
[
|
||||
"-m",
|
||||
"oclaw.runtime.operations",
|
||||
"gateway",
|
||||
"start",
|
||||
"--host",
|
||||
args.gateway_host,
|
||||
"--port",
|
||||
str(args.gateway_port),
|
||||
]
|
||||
)
|
||||
started.append(("gateway", start_service(name="gateway", command=gateway_cmd, env=gateway_mcp_env_extras())))
|
||||
|
||||
channel_cmd = default_python_command(
|
||||
[
|
||||
"-m",
|
||||
"oclaw.runtime.operations",
|
||||
"channel",
|
||||
args.channel,
|
||||
"start",
|
||||
"--mode",
|
||||
args.channel_mode,
|
||||
"--interval",
|
||||
str(args.channel_interval),
|
||||
"--deliver-outbound" if args.deliver_outbound else "--no-deliver-outbound",
|
||||
]
|
||||
)
|
||||
if args.channel_mode == "pull" and args.pull_url:
|
||||
channel_cmd.extend(["--pull-url", args.pull_url])
|
||||
started.append((f"channel:{args.channel}", start_service(name=f"channel:{args.channel}", command=channel_cmd)))
|
||||
|
||||
if args.with_ui:
|
||||
print(
|
||||
"hint=--with-ui ignored: Streamlit is disabled; use Ops Chat at "
|
||||
f"http://127.0.0.1:{int(args.gateway_port)}/chat",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print("ok=1")
|
||||
for name, pid in started:
|
||||
print(f"{name}_pid={pid}")
|
||||
print("hint=use `python -m oclaw.runtime.operations stack status` to check running services")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_stack_status(_args: argparse.Namespace) -> int:
|
||||
rows = status_services()
|
||||
print("ok=1")
|
||||
print(f"services={len(rows)}")
|
||||
for r in rows:
|
||||
print(f"service={r.name} pid={r.pid} running={1 if r.running else 0}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_stack_down(_args: argparse.Namespace) -> int:
|
||||
stopped = stop_all()
|
||||
print("ok=1")
|
||||
print(f"stopped={','.join(stopped)}")
|
||||
return 0
|
||||
|
||||
|
||||
def register_stack_parser(root_subparsers: Any) -> None:
|
||||
stack = root_subparsers.add_parser("stack", help="Manage local multi-service stack")
|
||||
sub = stack.add_subparsers(dest="stack_cmd", required=True)
|
||||
up = sub.add_parser("up", help="Start gateway + channel worker")
|
||||
up.add_argument("--channel", default="wecom")
|
||||
up.add_argument("--channel-mode", choices=["ws", "pull", "mock"], default="ws")
|
||||
up.add_argument("--channel-interval", type=float, default=3.0)
|
||||
up.add_argument("--deliver-outbound", action=argparse.BooleanOptionalAction, default=True)
|
||||
up.add_argument("--pull-url", default=None)
|
||||
up.add_argument("--gateway-host", default="0.0.0.0")
|
||||
up.add_argument("--gateway-port", type=int, default=8787)
|
||||
up.add_argument("--with-ui", action="store_true", help="Ignored (deprecated): legacy Streamlit; use http://127.0.0.1:<gateway-port>/chat")
|
||||
up.add_argument("--ui-port", type=int, default=8501, help="Unused (reserved for compatibility)")
|
||||
up.set_defaults(func=cmd_stack_up)
|
||||
status = sub.add_parser("status", help="Show stack service status")
|
||||
status.set_defaults(func=cmd_stack_status)
|
||||
down = sub.add_parser("down", help="Stop all stack services started by ops runtime")
|
||||
down.set_defaults(func=cmd_stack_down)
|
||||
Loading…
Add table
Add a link
Reference in a new issue