mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-11-05 16:57:32 +00:00
refactor(plugin): clawhubadapter 迁出为外部插件
## 为什么迁
它是唯一还留在内核仓的「兼容层」插件,而它的全部工作都是对接**外部生态**
(ClawHub/OpenClaw 的包格式),跟内核版本无关。留在仓里有两个实际问题:
· 外部生态的新包格式跟进要走内核发版
· 它必须跟着内核一起重新编译,而它并不依赖内核内部实现
## 迁移改动(逻辑一行没动,只换接口形态)
package clawhubadapter → package main
init()+RegisterFactory → NewPluginFactory(proc 运行时按名调用)
internal/sdk → hologramagentsdk/sdk
internal/safeclose.Safe → 自写 safeClose[T](泛型覆盖 3 种 channel)
InjectInputSync(4 参) → InjectInputSync(3 参, 返回 string)
s.Events().Publish → 删除(外部插件拿不到,也不需要)
## 为什么删掉 Events().Publish 而不是找替代
原实现靠它把纯 SKILL 条目移交 skillmgr。查清后发现**不需要**:
pluginmgr 在安装与每次启动时扫 `<插件目录>/skill/` 自己发 skill_detected
(internal/plugins/pluginmgr/skill_handout.go)。外部插件带 skill 走
工程根 skill/ 目录,与插件能不能发事件是两件事。
链路上没有一行来自插件自身,实测日志:
[pluginmgr] clawhubadapter: handed off skill clawhub-tools to skillmgr
[skillmgr] registered via skill_detected event: clawhub-tools
[plugin] loaded SKILL: clawhub-tools v1.0.0
## 验证
迁移工程 /home/program/clawhubadapter-plugin/clawhubadapter
go vet / gofmt 干净
go test -race ok(20 条原有 + 4 条外部形态判据)
hmapdev build packaged clawhubadapter_bundle.hmap
变异验证 4 条判据全部真红
隔离实例端到端(真实安装路径,非模拟):
registering tool: clawhubadapter_* × 10
[plugin] loaded: clawhubadapter
[plugin] loaded SKILL: clawhub-tools v1.0.0
内核仓:go build / vet / gofmt / go test -race 全绿,62 包
## 生产切换的注意点
本 commit 只删源码,**不改生产**。生产 homed 里仍编着内置版;
要真切换必须先装 .hmap 再重编 homed,否则等于把这个插件弄没了。
This commit is contained in:
@ -37,7 +37,7 @@ package plugins
|
||||
// pluginmgr failback 恢复链必需(webui/pluginmgr/recoverydiag)
|
||||
// seq ToolAPI(工具表直接操作)
|
||||
// remotedevice RegisterChannel(内核 IO 通道注册面)
|
||||
// clawhubadapter InjectInputSync(OC 主动注入)
|
||||
// clawhubadapter 已迁出为外部插件(HologramAgent/clawhubadapter,2026-11-04)
|
||||
// agentcli ★ EventPublish —— 见下
|
||||
// cfgmgr / skillmgr / seemedia (保留)
|
||||
//
|
||||
@ -94,7 +94,6 @@ package plugins
|
||||
import (
|
||||
_ "github.com/JianFeeeee/HologramAgent/internal/plugins/agentcli"
|
||||
_ "github.com/JianFeeeee/HologramAgent/internal/plugins/cfgmgr"
|
||||
_ "github.com/JianFeeeee/HologramAgent/internal/plugins/clawhubadapter"
|
||||
_ "github.com/JianFeeeee/HologramAgent/internal/plugins/cli"
|
||||
_ "github.com/JianFeeeee/HologramAgent/internal/plugins/healthcheck"
|
||||
_ "github.com/JianFeeeee/HologramAgent/internal/plugins/kbtree"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,428 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
OpenClaw Python Sidecar Simulator
|
||||
|
||||
Loads a Python plugin (main.py) from the plugin directory and
|
||||
provides JSON-RPC over stdin/stdout for tool listing and execution.
|
||||
|
||||
Protocol is identical to the Node.js simulator:
|
||||
- ping: returns {"status": "ok"}
|
||||
- tools/list: lists registered tools
|
||||
- tools/call: executes a tool
|
||||
|
||||
Plugin main.py should define:
|
||||
def register(api):
|
||||
api.register_tool(name, description, parameters, execute_fn)
|
||||
"""
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def resolve_entry(plugin_dir):
|
||||
"""Resolve the plugin entry point."""
|
||||
main_py = os.path.join(plugin_dir, 'main.py')
|
||||
if os.path.isfile(main_py):
|
||||
return main_py
|
||||
return None
|
||||
|
||||
|
||||
class PluginAPI:
|
||||
"""API passed to the plugin's register() function."""
|
||||
|
||||
def __init__(self, plugin_dir):
|
||||
self.id = os.path.basename(plugin_dir)
|
||||
self.name = os.path.basename(plugin_dir)
|
||||
self.version = '1.0.0'
|
||||
self.description = ''
|
||||
self.source = plugin_dir
|
||||
self.root_dir = plugin_dir
|
||||
self.config = {}
|
||||
self.plugin_config = {}
|
||||
self.registration_mode = 'full'
|
||||
self._tools = {}
|
||||
|
||||
def register_tool(self, name, description='', parameters=None, execute=None):
|
||||
if parameters is None:
|
||||
parameters = {'type': 'object', 'properties': {}}
|
||||
self._notify('register', {
|
||||
'type': 'tool',
|
||||
'data': {
|
||||
'name': name,
|
||||
'description': description,
|
||||
'parameters': parameters,
|
||||
}
|
||||
})
|
||||
self._tools[name] = {
|
||||
'name': name,
|
||||
'description': description,
|
||||
'parameters': parameters,
|
||||
'execute': execute,
|
||||
}
|
||||
|
||||
def register_provider(self, provider_type, provider):
|
||||
self._notify('register', {
|
||||
'type': 'provider',
|
||||
'data': {'name': provider.name if hasattr(provider, 'name') else str(provider)},
|
||||
})
|
||||
|
||||
def register_channel(self, channel):
|
||||
self._notify('register', {
|
||||
'type': 'channel',
|
||||
'data': {'name': channel.name if hasattr(channel, 'name') else str(channel)},
|
||||
})
|
||||
|
||||
def _notify(self, method, params):
|
||||
line = json.dumps({'jsonrpc': '2.0', 'method': method, 'params': params}, ensure_ascii=False)
|
||||
sys.stdout.write(line + '\n')
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
# ---- Legacy Python Plugin Detection ----
|
||||
|
||||
def _resolve_env_vars(plugin_dir):
|
||||
"""Read env var requirements from skill.json and resolve from OS env."""
|
||||
skill_json = os.path.join(plugin_dir, 'skill.json')
|
||||
if not os.path.isfile(skill_json):
|
||||
return {}
|
||||
try:
|
||||
with open(skill_json, 'r') as f:
|
||||
meta = json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
env_map = {}
|
||||
for key in meta.get('required_env_vars', []):
|
||||
val = os.environ.get(key) or os.environ.get(key.lower())
|
||||
if val:
|
||||
env_map[key.lower()] = val
|
||||
for key in meta.get('optional_env_vars', []):
|
||||
val = os.environ.get(key) or os.environ.get(key.lower())
|
||||
if val:
|
||||
env_map[key.lower()] = val
|
||||
|
||||
return env_map
|
||||
|
||||
|
||||
def _collect_sub_skills(instance):
|
||||
"""Discover sub-module names from a class instance by finding attributes with execute methods.
|
||||
|
||||
Prefer instance __dict__ attributes over properties to avoid triggering side effects.
|
||||
"""
|
||||
skills = []
|
||||
seen = set()
|
||||
|
||||
# First look at instance __dict__ (safe, no property triggers)
|
||||
for attr_name in list(instance.__dict__.keys()):
|
||||
if attr_name.startswith('_'):
|
||||
continue
|
||||
attr = instance.__dict__[attr_name]
|
||||
seen.add(attr_name)
|
||||
if hasattr(attr, 'execute') and callable(attr.execute):
|
||||
try:
|
||||
sig = inspect.signature(attr.execute)
|
||||
params = list(sig.parameters.keys())
|
||||
if 'action' in params and len(params) >= 2:
|
||||
skills.append(attr_name)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
|
||||
# Also check class-level non-property attributes
|
||||
for attr_name in dir(type(instance)):
|
||||
if attr_name.startswith('_') or attr_name in seen:
|
||||
continue
|
||||
try:
|
||||
attr = getattr(type(instance), attr_name, None)
|
||||
except Exception:
|
||||
continue
|
||||
if isinstance(attr, property):
|
||||
continue # skip properties (may raise on access)
|
||||
try:
|
||||
attr = getattr(instance, attr_name, None)
|
||||
except Exception:
|
||||
continue
|
||||
if attr is None:
|
||||
continue
|
||||
seen.add(attr_name)
|
||||
if hasattr(attr, 'execute') and callable(attr.execute):
|
||||
try:
|
||||
sig = inspect.signature(attr.execute)
|
||||
params = list(sig.parameters.keys())
|
||||
if 'action' in params and len(params) >= 2:
|
||||
skills.append(attr_name)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
|
||||
return skills
|
||||
|
||||
|
||||
def _readable_class_name(cls):
|
||||
"""Convert PascalCase to snake_case for readable names."""
|
||||
import re
|
||||
name = cls.__name__
|
||||
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
|
||||
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
||||
|
||||
|
||||
def _make_async_execute(instance, skill_name):
|
||||
"""Wrap an async sub-module execute into a sync callable for JSON-RPC."""
|
||||
def execute(args):
|
||||
action = args.pop('action', '') if isinstance(args, dict) else ''
|
||||
result = asyncio.run(instance.execute(skill_name=skill_name, action=action, **args))
|
||||
return result
|
||||
return execute
|
||||
|
||||
|
||||
def _make_legacy_execute(instance, attr_name):
|
||||
"""Wrap an async legacy execute into a sync callable for JSON-RPC."""
|
||||
def execute(args):
|
||||
action = args.pop('action', '') if isinstance(args, dict) else ''
|
||||
handler = getattr(instance, attr_name)
|
||||
result = asyncio.run(handler.execute(action=action, **args))
|
||||
return result
|
||||
return execute
|
||||
|
||||
|
||||
def detect_legacy_plugin(module, plugin_dir, plugin_name):
|
||||
"""Auto-detect legacy Python plugin patterns and register as OC tools.
|
||||
|
||||
Returns a PluginAPI with discovered tools, or None if no pattern matches.
|
||||
"""
|
||||
api = PluginAPI(plugin_dir)
|
||||
|
||||
# Pattern 1: Module has a main class with execute(skill_name, action, **kwargs)
|
||||
# Look for any class that has an 'execute' method accepting 'skill_name'
|
||||
main_class = None
|
||||
main_class_name = None
|
||||
|
||||
for name in dir(module):
|
||||
obj = getattr(module, name, None)
|
||||
if not isinstance(obj, type):
|
||||
continue
|
||||
if not hasattr(obj, 'execute') or not callable(getattr(obj, 'execute', None)):
|
||||
continue
|
||||
try:
|
||||
sig = inspect.signature(obj.execute)
|
||||
params = list(sig.parameters.keys())
|
||||
if 'skill_name' in params:
|
||||
main_class = obj
|
||||
main_class_name = name
|
||||
break
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
|
||||
if main_class is None:
|
||||
return None
|
||||
|
||||
# Resolve env vars for constructor
|
||||
env_args = _resolve_env_vars(plugin_dir)
|
||||
try:
|
||||
sig = inspect.signature(main_class.__init__)
|
||||
init_params = list(sig.parameters.keys())[1:] # skip self
|
||||
kwargs = {}
|
||||
for p in init_params:
|
||||
lower_p = p.lower()
|
||||
if lower_p in env_args:
|
||||
kwargs[p] = env_args[lower_p]
|
||||
sys.stderr.write(f'[pysimulator] legacy: instantiating {main_class_name} with {kwargs}\n')
|
||||
instance = main_class(**kwargs)
|
||||
except Exception as e:
|
||||
sys.stderr.write(f'[pysimulator] legacy: cannot instantiate {main_class_name}: {e}\n')
|
||||
return None
|
||||
|
||||
# Discover sub-modules
|
||||
sub_skills = _collect_sub_skills(instance)
|
||||
sys.stderr.write(f'[pysimulator] legacy: discovered sub-skills: {sub_skills}\n')
|
||||
|
||||
discovered_actions = {}
|
||||
for attr_name in sub_skills:
|
||||
handler = getattr(instance, attr_name)
|
||||
# Build parameter schema from the execute signature
|
||||
try:
|
||||
sig = inspect.signature(handler.execute)
|
||||
param_props = {}
|
||||
for p_name, p_sig in list(sig.parameters.items())[1:]: # skip 'self'
|
||||
if p_name == 'action':
|
||||
param_props['action'] = {
|
||||
'type': 'string',
|
||||
'description': f'Action to perform in {attr_name}',
|
||||
}
|
||||
continue
|
||||
if p_sig.annotation != inspect.Parameter.empty:
|
||||
p_type = 'string'
|
||||
if p_sig.annotation is int:
|
||||
p_type = 'number'
|
||||
elif p_sig.annotation is bool:
|
||||
p_type = 'boolean'
|
||||
elif p_sig.annotation is float:
|
||||
p_type = 'number'
|
||||
else:
|
||||
anno_str = str(p_sig.annotation)
|
||||
if 'int' in anno_str:
|
||||
p_type = 'number'
|
||||
elif 'bool' in anno_str:
|
||||
p_type = 'boolean'
|
||||
elif 'float' in anno_str:
|
||||
p_type = 'number'
|
||||
param_props[p_name] = {
|
||||
'type': p_type,
|
||||
'description': f'Parameter {p_name}',
|
||||
}
|
||||
else:
|
||||
param_props[p_name] = {
|
||||
'type': 'string',
|
||||
'description': f'Parameter {p_name}',
|
||||
}
|
||||
|
||||
required = ['action']
|
||||
schema = {
|
||||
'type': 'object',
|
||||
'properties': param_props,
|
||||
'required': required,
|
||||
}
|
||||
|
||||
tool_name = attr_name
|
||||
doc = handler.execute.__doc__ or f'{attr_name} operations'
|
||||
first_line = doc.strip().split('\n')[0] if doc else f'{attr_name} module'
|
||||
|
||||
discovered_actions[attr_name] = (tool_name, first_line, schema)
|
||||
except (ValueError, TypeError) as e:
|
||||
sys.stderr.write(f'[pysimulator] legacy: skip {attr_name}: {e}\n')
|
||||
continue
|
||||
|
||||
if discovered_actions:
|
||||
# Register each sub-skill as a separate OC tool
|
||||
for attr_name, (tool_name, desc, schema) in discovered_actions.items():
|
||||
handler = getattr(instance, attr_name)
|
||||
api.register_tool(
|
||||
name=tool_name,
|
||||
description=f'{plugin_name}: {desc}',
|
||||
parameters=schema,
|
||||
execute=_make_legacy_execute(instance, attr_name),
|
||||
)
|
||||
sys.stderr.write(f'[pysimulator] legacy registered tool: {tool_name}\n')
|
||||
else:
|
||||
# Fallback: single tool wrapping the whole plugin
|
||||
try:
|
||||
sig = inspect.signature(main_class.execute)
|
||||
skill_params = [p for p in list(sig.parameters.keys())[1:]] # skip self
|
||||
param_props = {}
|
||||
for p in skill_params:
|
||||
param_props[p] = {'type': 'string', 'description': p}
|
||||
|
||||
api.register_tool(
|
||||
name=plugin_name,
|
||||
description=f'{plugin_name}: unified operations',
|
||||
parameters={
|
||||
'type': 'object',
|
||||
'properties': param_props,
|
||||
'required': skill_params,
|
||||
},
|
||||
execute=_make_async_execute(instance, None),
|
||||
)
|
||||
sys.stderr.write(f'[pysimulator] legacy registered fallback tool: {plugin_name}\n')
|
||||
except Exception as e:
|
||||
sys.stderr.write(f'[pysimulator] legacy: fallback failed: {e}\n')
|
||||
return None
|
||||
|
||||
return api
|
||||
|
||||
|
||||
def load_plugin(plugin_dir):
|
||||
"""Load the plugin from main.py.
|
||||
|
||||
Tries OC-style register(api) first, then auto-detects legacy patterns.
|
||||
"""
|
||||
entry_path = resolve_entry(plugin_dir)
|
||||
if entry_path is None:
|
||||
sys.stderr.write(f'[pysimulator] entry not found in {plugin_dir}\n')
|
||||
sys.exit(1)
|
||||
|
||||
sys.path.insert(0, plugin_dir)
|
||||
spec = importlib.util.spec_from_file_location('plugin_main', entry_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
plugin_name = os.path.basename(plugin_dir)
|
||||
|
||||
# OC-style: register(api)
|
||||
if hasattr(module, 'register'):
|
||||
api = PluginAPI(plugin_dir)
|
||||
module.register(api)
|
||||
return api
|
||||
|
||||
# Legacy auto-detection
|
||||
sys.stderr.write(f'[pysimulator] no register() function, trying legacy detection for {plugin_name}...\n')
|
||||
api = detect_legacy_plugin(module, plugin_dir, plugin_name)
|
||||
if api is not None:
|
||||
return api
|
||||
|
||||
sys.stderr.write(f'[pysimulator] {entry_path} must define a register(api) function\n')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
sys.stderr.write('[pysimulator] usage: python3 main.py <plugin-dir>\n')
|
||||
sys.exit(1)
|
||||
|
||||
plugin_dir = os.path.abspath(sys.argv[1])
|
||||
api = load_plugin(plugin_dir)
|
||||
|
||||
# JSON-RPC loop over stdin
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
req = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
resp = {'jsonrpc': '2.0', 'id': None, 'error': {'code': -32700, 'message': 'Parse error'}}
|
||||
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + '\n')
|
||||
sys.stdout.flush()
|
||||
continue
|
||||
|
||||
req_id = req.get('id')
|
||||
method = req.get('method', '')
|
||||
|
||||
if method == 'ping':
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'result': {'status': 'ok'}}
|
||||
elif method == 'tools/list':
|
||||
tools = [
|
||||
{'name': t['name'], 'description': t['description'], 'inputSchema': t['parameters']}
|
||||
for t in api._tools.values()
|
||||
]
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'result': {'tools': tools}}
|
||||
elif method == 'tools/call':
|
||||
params = req.get('params', {})
|
||||
tool_name = params.get('name', '')
|
||||
arguments = params.get('arguments', {})
|
||||
|
||||
tool = api._tools.get(tool_name)
|
||||
if tool is None:
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': -32601, 'message': f'Tool not found: {tool_name}'}}
|
||||
elif tool.get('execute') is None:
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': -32603, 'message': f'Tool {tool_name} has no execute function'}}
|
||||
else:
|
||||
try:
|
||||
result = tool['execute'](arguments)
|
||||
if isinstance(result, dict) and 'content' in result:
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'result': result}
|
||||
else:
|
||||
text = str(result) if not isinstance(result, str) else result
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'result': {'content': [{'type': 'text', 'text': text}]}}
|
||||
except Exception as e:
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': -32603, 'message': str(e)}}
|
||||
else:
|
||||
resp = {'jsonrpc': '2.0', 'id': req_id, 'error': {'code': -32601, 'message': f'Method not found: {method}'}}
|
||||
|
||||
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + '\n')
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -1,63 +0,0 @@
|
||||
package clawhubadapter
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// ── Python 解释器选择优先级 ──────────────────────────────────
|
||||
//
|
||||
// 背景(2026-10-25 真机事故):bilibili skill 声明 requirements 含 httpx,
|
||||
// 系统 Python 没装 ⇒ 启动即 ModuleNotFoundError。而此前解释器是**硬编码猜**的:
|
||||
// 先 /usr/bin/python3,再 /usr/local/bin/python3。
|
||||
//
|
||||
// 「猜」没有正确解:不同部署的 Python 布局完全不同(发行版 Python、
|
||||
// pyenv、uv、conda、venv…)。所以改为配置显式指定 + venv 探测兜底。
|
||||
|
||||
// 判据:配置了 python_bin 且可用 ⇒ 必须用它,优先于 venv 与系统解释器。
|
||||
//
|
||||
// 这是"配置生效"的唯一证据。没有它,配了却仍走系统解释器也不会被发现
|
||||
// (正是本次事故的形态:静默降级)。
|
||||
func TestPickPython_ConfiguredWins(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// 造一个假的 venv 解释器,确保"配置优先于 venv"被真正验证
|
||||
venvBin := filepath.Join(dir, ".venv", "bin")
|
||||
os.MkdirAll(venvBin, 0755)
|
||||
venvPy := filepath.Join(venvBin, "python")
|
||||
os.WriteFile(venvPy, []byte("#!/bin/sh\n"), 0755)
|
||||
|
||||
cfgPy := filepath.Join(dir, "custom-python")
|
||||
os.WriteFile(cfgPy, []byte("#!/bin/sh\n"), 0755)
|
||||
|
||||
got := pickPythonFor("bilibili", dir, cfgPy)
|
||||
if got != cfgPy {
|
||||
t.Fatalf("配置的 python_bin 应最高优先,期望 %s,实际 %s", cfgPy, got)
|
||||
}
|
||||
}
|
||||
|
||||
// 判据:没配 python_bin 但 skill 有 venv ⇒ 用 venv。
|
||||
func TestPickPython_VenvWhenNotConfigured(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
venvBin := filepath.Join(dir, ".venv", "bin")
|
||||
os.MkdirAll(venvBin, 0755)
|
||||
venvPy := filepath.Join(venvBin, "python")
|
||||
os.WriteFile(venvPy, []byte("#!/bin/sh\n"), 0755)
|
||||
|
||||
if got := pickPythonFor("x", dir, ""); got != venvPy {
|
||||
t.Fatalf("无配置时应优先 skill 自带 venv,期望 %s,实际 %s", venvPy, got)
|
||||
}
|
||||
}
|
||||
|
||||
// 判据:配置了但**不存在** ⇒ 必须报错,不能静默退回系统解释器。
|
||||
//
|
||||
// 静默退回的后果:用户以为配好了,实际跑在缺依赖的 Python 上 ——
|
||||
// 这正是本次要修的「静默降级」那一族。
|
||||
func TestPickPython_MissingConfiguredIsLoud(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
bad := filepath.Join(dir, "no-such-python")
|
||||
_, err := resolvePython("x", dir, bad)
|
||||
if err == nil {
|
||||
t.Fatal("配置的 python_bin 不存在时必须报错(静默退回会让用户以为配置生效)")
|
||||
}
|
||||
}
|
||||
@ -1,326 +0,0 @@
|
||||
package clawhubadapter
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
sdk "github.com/JianFeeeee/HologramAgent/internal/sdk"
|
||||
)
|
||||
|
||||
var (
|
||||
channelInputBuf = map[string][]map[string]interface{}{}
|
||||
channelInputBufMu sync.Mutex
|
||||
channelStatus map[string]map[string]interface{} // 通道运行状态(channel_status 通知)
|
||||
channelStatusMu sync.Mutex
|
||||
)
|
||||
|
||||
type ToolRegistry struct{}
|
||||
|
||||
func (r *ToolRegistry) Dispatch(data json.RawMessage, pluginName string, sp *sidecarProcess, s *sdk.PluginSDK) {
|
||||
var d struct {
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]interface{} `json:"parameters"`
|
||||
Plugin string `json:"plugin"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &d); err != nil || d.Name == "" {
|
||||
return
|
||||
}
|
||||
pn := pluginName
|
||||
if d.Plugin != "" {
|
||||
pn = d.Plugin
|
||||
}
|
||||
toolName := fmt.Sprintf("%s_%s", pn, d.Name)
|
||||
tDef := sdk.ToolDef{
|
||||
Name: toolName,
|
||||
Description: d.Description,
|
||||
Parameters: d.Parameters,
|
||||
}
|
||||
handler := func(sp *sidecarProcess, ocToolName string) sdk.ToolHandler {
|
||||
return func(args map[string]interface{}) (interface{}, error) {
|
||||
return sp.CallTool(ocToolName, args)
|
||||
}
|
||||
}(sp, d.Name)
|
||||
if err := s.RegisterTool(toolName, tDef, handler); err != nil {
|
||||
log.Printf("[clawhubadapter] register tool %s: %v", toolName, err)
|
||||
}
|
||||
}
|
||||
|
||||
type providerDef struct {
|
||||
ocType string
|
||||
toolSuffix string
|
||||
desc string
|
||||
}
|
||||
|
||||
var providerMap = []providerDef{
|
||||
{"image_generation", "generate_image", "根据文本描述生成图片,返回图片 URL"},
|
||||
{"music_generation", "generate_music", "根据描述生成音乐"},
|
||||
{"video_generation", "generate_video", "根据描述生成视频"},
|
||||
{"speech", "synthesize_speech", "将文本合成为语音"},
|
||||
{"web_search", "web_search", "搜索互联网信息"},
|
||||
{"web_fetch", "web_fetch", "获取指定网页的内容"},
|
||||
{"media_understanding", "analyze_media", "分析图片、音频或视频内容"},
|
||||
{"realtime_transcription", "transcribe_audio", "将音频转写为文字"},
|
||||
{"realtime_voice", "voice_io", "实时语音输入输出"},
|
||||
}
|
||||
|
||||
type ProviderRegistry struct{}
|
||||
|
||||
func (r *ProviderRegistry) Dispatch(typeStr string, data json.RawMessage, pluginName string, sp *sidecarProcess, s *sdk.PluginSDK) {
|
||||
var d struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Plugin string `json:"plugin"`
|
||||
}
|
||||
json.Unmarshal(data, &d)
|
||||
|
||||
pn := pluginName
|
||||
if d.Plugin != "" {
|
||||
pn = d.Plugin
|
||||
}
|
||||
|
||||
// Strip _provider suffix: "image_generation_provider" -> "image_generation"
|
||||
lookupType := typeStr
|
||||
if lookupType != "provider" {
|
||||
lookupType = strings.TrimSuffix(lookupType, "_provider")
|
||||
}
|
||||
if lookupType == "" {
|
||||
return
|
||||
}
|
||||
|
||||
for _, p := range providerMap {
|
||||
if p.ocType == lookupType {
|
||||
toolName := fmt.Sprintf("%s_%s", pn, p.toolSuffix)
|
||||
desc := p.desc
|
||||
if d.Name != "" {
|
||||
desc = fmt.Sprintf("[%s] %s", d.Name, desc)
|
||||
}
|
||||
props := map[string]interface{}{
|
||||
"prompt": map[string]interface{}{"type": "string", "description": "Prompt for generation or search query"},
|
||||
}
|
||||
switch p.ocType {
|
||||
case "image_generation":
|
||||
props["prompt"] = map[string]interface{}{"type": "string", "description": "Image description prompt"}
|
||||
props["size"] = map[string]interface{}{"type": "string", "description": "Image size (e.g. 1024x1024)", "enum": []interface{}{"256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"}}
|
||||
case "web_search":
|
||||
props["query"] = map[string]interface{}{"type": "string", "description": "Search query"}
|
||||
delete(props, "prompt")
|
||||
case "web_fetch":
|
||||
props["url"] = map[string]interface{}{"type": "string", "description": "URL to fetch"}
|
||||
delete(props, "prompt")
|
||||
case "media_understanding":
|
||||
props["url"] = map[string]interface{}{"type": "string", "description": "Media URL to analyze"}
|
||||
props["media_type"] = map[string]interface{}{"type": "string", "description": "Media type", "enum": []interface{}{"image", "audio", "video"}}
|
||||
case "speech":
|
||||
props["text"] = map[string]interface{}{"type": "string", "description": "Text to synthesize"}
|
||||
props["voice"] = map[string]interface{}{"type": "string", "description": "Voice identifier"}
|
||||
case "music_generation":
|
||||
props["prompt"] = map[string]interface{}{"type": "string", "description": "Music description prompt"}
|
||||
props["duration"] = map[string]interface{}{"type": "number", "description": "Duration in seconds"}
|
||||
case "video_generation":
|
||||
props["prompt"] = map[string]interface{}{"type": "string", "description": "Video description prompt"}
|
||||
props["duration"] = map[string]interface{}{"type": "number", "description": "Duration in seconds"}
|
||||
case "realtime_transcription":
|
||||
props["audio_url"] = map[string]interface{}{"type": "string", "description": "Audio URL to transcribe"}
|
||||
case "realtime_voice":
|
||||
props["text"] = map[string]interface{}{"type": "string", "description": "Text to speak"}
|
||||
props["voice"] = map[string]interface{}{"type": "string", "description": "Voice identifier"}
|
||||
}
|
||||
tDef := sdk.ToolDef{
|
||||
Name: toolName,
|
||||
Description: desc,
|
||||
Parameters: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": props,
|
||||
},
|
||||
}
|
||||
handler := func(sp *sidecarProcess, ocType string) sdk.ToolHandler {
|
||||
return func(args map[string]interface{}) (interface{}, error) {
|
||||
return sp.CallProvider(ocType, args)
|
||||
}
|
||||
}(sp, lookupType)
|
||||
if err := s.RegisterTool(toolName, tDef, handler); err != nil {
|
||||
log.Printf("[clawhubadapter] register provider tool %s: %v", toolName, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if lookupType != typeStr {
|
||||
log.Printf("[clawhubadapter] provider %s -> lookup %s (plugin: %s)", typeStr, lookupType, pluginName)
|
||||
}
|
||||
switch lookupType {
|
||||
case "provider":
|
||||
log.Printf("[clawhubadapter] generic LLM provider from %s handled natively by HologramAgent", pluginName)
|
||||
case "embedding", "memory_embedding":
|
||||
log.Printf("[clawhubadapter] embedding provider %s from %s ignored (HologramAgent uses native embeddings)", lookupType, pluginName)
|
||||
default:
|
||||
log.Printf("[clawhubadapter] unknown provider type: %s (plugin: %s)", typeStr, pluginName)
|
||||
}
|
||||
}
|
||||
|
||||
type ChannelRegistry struct{}
|
||||
|
||||
func (r *ChannelRegistry) Dispatch(data json.RawMessage, pluginName string, sp *sidecarProcess, s *sdk.PluginSDK) {
|
||||
var d struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Plugin string `json:"plugin"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &d); err != nil || d.Name == "" {
|
||||
return
|
||||
}
|
||||
chName := d.Name
|
||||
pn := pluginName
|
||||
if d.Plugin != "" {
|
||||
pn = d.Plugin
|
||||
}
|
||||
|
||||
var caps int
|
||||
switch d.Type {
|
||||
case "file":
|
||||
caps = 2
|
||||
case "image":
|
||||
caps = 4
|
||||
case "audio":
|
||||
caps = 8
|
||||
default:
|
||||
caps = 1
|
||||
}
|
||||
desc := fmt.Sprintf("OC channel %s (from %s)", chName, pn)
|
||||
// 通道名来自外部 OC 配置(动态):声明处**同时**登记 inputch ——
|
||||
// 该通道既收(InjectInputSync 见 plugin.go)又发(output_send__<通道>)。
|
||||
_ = s.RegisterInputChannel(chName, sdk.ChannelDef{})
|
||||
s.RegisterOutputChannel(chName, caps, desc, sdk.ChannelDef{}, func(args map[string]interface{}) (interface{}, error) {
|
||||
return sp.CallTool(chName, args)
|
||||
})
|
||||
|
||||
readToolName := fmt.Sprintf("%s_read_%s_input", pn, strings.ReplaceAll(chName, "-", "_"))
|
||||
s.RegisterTool(readToolName, sdk.ToolDef{
|
||||
Name: readToolName,
|
||||
Description: fmt.Sprintf("读取 %s 通道的待处理输入消息", chName),
|
||||
Parameters: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{},
|
||||
},
|
||||
}, func(args map[string]interface{}) (interface{}, error) {
|
||||
channelInputBufMu.Lock()
|
||||
buf := channelInputBuf[chName]
|
||||
if len(buf) == 0 {
|
||||
channelInputBufMu.Unlock()
|
||||
return map[string]interface{}{"messages": []interface{}{}}, nil
|
||||
}
|
||||
msgs := make([]interface{}, len(buf))
|
||||
for i, m := range buf {
|
||||
msgs[i] = m
|
||||
}
|
||||
channelInputBuf[chName] = nil
|
||||
channelInputBufMu.Unlock()
|
||||
return map[string]interface{}{"messages": msgs}, nil
|
||||
})
|
||||
}
|
||||
|
||||
type StageRegistry struct{}
|
||||
|
||||
func (r *StageRegistry) Dispatch(data json.RawMessage, pluginName string, sp *sidecarProcess, s *sdk.PluginSDK) {
|
||||
var d struct {
|
||||
Name string `json:"name"`
|
||||
Event string `json:"event"`
|
||||
}
|
||||
json.Unmarshal(data, &d)
|
||||
log.Printf("[clawhubadapter] hook %s/%s (plugin: %s) — stub: OC hooks need bidirectional bridge",
|
||||
d.Name, d.Event, pluginName)
|
||||
}
|
||||
|
||||
type CapRecorder struct {
|
||||
mu sync.Mutex
|
||||
caps []string
|
||||
}
|
||||
|
||||
func (r *CapRecorder) Record(typeStr string, data json.RawMessage, pluginName string) {
|
||||
var d struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
json.Unmarshal(data, &d)
|
||||
capStr := fmt.Sprintf("[%s] capability: %s", pluginName, typeStr)
|
||||
if d.Name != "" {
|
||||
capStr += " (" + d.Name + ")"
|
||||
}
|
||||
if d.Description != "" {
|
||||
capStr += ": " + d.Description
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.caps = append(r.caps, capStr)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *CapRecorder) Snapshot() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := make([]string, len(r.caps))
|
||||
copy(out, r.caps)
|
||||
return out
|
||||
}
|
||||
|
||||
type RegistryDispatcher struct {
|
||||
toolReg *ToolRegistry
|
||||
providerReg *ProviderRegistry
|
||||
channelReg *ChannelRegistry
|
||||
stageReg *StageRegistry
|
||||
capRecorder *CapRecorder
|
||||
}
|
||||
|
||||
func NewDispatcher() *RegistryDispatcher {
|
||||
return &RegistryDispatcher{
|
||||
toolReg: &ToolRegistry{},
|
||||
providerReg: &ProviderRegistry{},
|
||||
channelReg: &ChannelRegistry{},
|
||||
stageReg: &StageRegistry{},
|
||||
capRecorder: &CapRecorder{},
|
||||
}
|
||||
}
|
||||
|
||||
func (d *RegistryDispatcher) Dispatch(typeStr string, data json.RawMessage, pluginName string, sp *sidecarProcess, s *sdk.PluginSDK) {
|
||||
switch typeStr {
|
||||
case "tool":
|
||||
d.toolReg.Dispatch(data, pluginName, sp, s)
|
||||
case "channel":
|
||||
d.channelReg.Dispatch(data, pluginName, sp, s)
|
||||
case "provider", "image_generation_provider", "music_generation_provider",
|
||||
"video_generation_provider", "speech_provider",
|
||||
"realtime_transcription_provider", "realtime_voice_provider",
|
||||
"media_understanding_provider",
|
||||
"web_fetch_provider", "web_search_provider",
|
||||
"embedding_provider", "memory_embedding_provider":
|
||||
d.providerReg.Dispatch(typeStr, data, pluginName, sp, s)
|
||||
d.capRecorder.Record(typeStr, data, pluginName)
|
||||
case "hook", "runtime_lifecycle", "lifecycle",
|
||||
"agent_event_subscription", "agent_harness",
|
||||
"session_event", "conversation_binding_resolved",
|
||||
"interactive_handler",
|
||||
"cli", "cli_backend", "node_cli_feature",
|
||||
"command", "http_route", "service",
|
||||
"gateway_method", "gateway_discovery_service",
|
||||
"trusted_tool_policy", "tool_metadata",
|
||||
"context_engine",
|
||||
"memory_capability", "memory_prompt_section",
|
||||
"memory_flush_plan", "memory_runtime",
|
||||
"memory_prompt_supplement", "memory_corpus_supplement",
|
||||
"session_extension", "session_scheduler_job",
|
||||
"session_action", "control_ui_descriptor",
|
||||
"agent_tool_result_middleware":
|
||||
d.stageReg.Dispatch(data, pluginName, sp, s)
|
||||
d.capRecorder.Record(typeStr, data, pluginName)
|
||||
default:
|
||||
d.capRecorder.Record(typeStr, data, pluginName)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *RegistryDispatcher) Capabilities() []string {
|
||||
return d.capRecorder.Snapshot()
|
||||
}
|
||||
@ -1,420 +0,0 @@
|
||||
package clawhubadapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
safeclose "github.com/JianFeeeee/HologramAgent/internal/safeclose"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type sidecarRequest struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID int `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params interface{} `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type sidecarResponse struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID int `json:"id"`
|
||||
Result *json.RawMessage `json:"result,omitempty"`
|
||||
Error *struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type OCPTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]interface{} `json:"inputSchema"`
|
||||
}
|
||||
|
||||
type OCCallResult struct {
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
} `json:"content"`
|
||||
}
|
||||
|
||||
// OCNotification 是模拟器主动推送的通知
|
||||
type OCNotification struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
// pendingResp 是待应答通道 + 它自己的 close 守卫。
|
||||
//
|
||||
// 为什么需要 once:Close() 可能被多条路径调用(Stop / 重载 / 停机),
|
||||
// 而 `close(ch)` 二次即 panic(本仓 close 纪律,见 internal/safeclose)。
|
||||
// 这些 channel 是**按请求创建**的,不能共用一个全局 Once ⇒ 每个自带一个。
|
||||
type pendingResp struct {
|
||||
ch chan []byte
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (p *pendingResp) closeOnce() { safeclose.Safe(&p.once, p.ch) }
|
||||
|
||||
type sidecarProcess struct {
|
||||
readerReadyOnce sync.Once
|
||||
name string
|
||||
dir string
|
||||
cmd *exec.Cmd
|
||||
stdin *bufio.Writer
|
||||
mu sync.Mutex
|
||||
nextID int
|
||||
closed bool
|
||||
stopped bool
|
||||
|
||||
// 异步 reader
|
||||
pending map[int]*pendingResp
|
||||
notifyCh chan OCNotification
|
||||
readerStop chan struct{}
|
||||
readerWg sync.WaitGroup
|
||||
readerReady chan struct{}
|
||||
}
|
||||
|
||||
func newSidecarProcess(name, dir string, cmd *exec.Cmd, stdin *bufio.Writer, stdout io.Reader) *sidecarProcess {
|
||||
sp := &sidecarProcess{
|
||||
name: name,
|
||||
dir: dir,
|
||||
cmd: cmd,
|
||||
stdin: stdin,
|
||||
pending: make(map[int]*pendingResp),
|
||||
notifyCh: make(chan OCNotification, 1024),
|
||||
readerStop: make(chan struct{}),
|
||||
readerReady: make(chan struct{}),
|
||||
}
|
||||
sp.readerWg.Add(1)
|
||||
go sp.readLoop(stdout)
|
||||
<-sp.readerReady
|
||||
return sp
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) readLoop(r io.Reader) {
|
||||
defer s.readerWg.Done()
|
||||
scanner := bufio.NewScanner(bufio.NewReader(r))
|
||||
// 加大 scanner buffer 防止长行截断
|
||||
scanner.Buffer(make([]byte, 0, 1024*64), 1024*64)
|
||||
safeclose.Safe(&s.readerReadyOnce, s.readerReady)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-s.readerStop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
if !scanner.Scan() {
|
||||
if scanner.Err() != nil {
|
||||
log.Printf("[clawhubadapter] sidecar %s read error: %v", s.name, scanner.Err())
|
||||
}
|
||||
return
|
||||
}
|
||||
line := scanner.Text()
|
||||
|
||||
var base struct {
|
||||
ID *int `json:"id"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Error *json.RawMessage `json:"error,omitempty"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &base); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if base.ID != nil {
|
||||
s.mu.Lock()
|
||||
pr, ok := s.pending[*base.ID]
|
||||
delete(s.pending, *base.ID)
|
||||
s.mu.Unlock()
|
||||
if ok {
|
||||
pr.ch <- []byte(line)
|
||||
}
|
||||
} else if base.Method != "" {
|
||||
var notif OCNotification
|
||||
if err := json.Unmarshal([]byte(line), ¬if); err == nil {
|
||||
select {
|
||||
case s.notifyCh <- notif:
|
||||
default:
|
||||
log.Printf("[clawhubadapter] sidecar %s notify channel full, dropping: %s", s.name, notif.Method)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) NotifyChan() <-chan OCNotification {
|
||||
return s.notifyCh
|
||||
}
|
||||
|
||||
func launchSidecar(dir, name, simDir string) (*sidecarProcess, error) {
|
||||
mainJS := filepath.Join(dir, "main.js")
|
||||
if _, err := os.Stat(mainJS); os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return launchProcess("node", mainJS, dir, name, simDir)
|
||||
}
|
||||
|
||||
// launchProcess 以 dir 作为工作目录拉起子进程(绝大多数调用的形态)。
|
||||
func launchProcess(bin, arg, dir, name, simDir string) (*sidecarProcess, error) {
|
||||
return launchProcessIn(bin, arg, dir, name, simDir, dir)
|
||||
}
|
||||
|
||||
// launchProcessIn 与 launchProcess 相同,但工作目录可单独指定。
|
||||
//
|
||||
// 为什么要单独一个函数而不是给 launchProcess 加参数:那会改动 4 个既有
|
||||
// 调用点(含测试),而它们的语义都是"工作目录 = skill 目录"。只有
|
||||
// skill_workdir 配置这一处需要另给目录,用变体表达的意图更清楚。
|
||||
func launchProcessIn(bin, arg, dir, name, simDir, workDir string) (*sidecarProcess, error) {
|
||||
nodePath := bin
|
||||
if bin == "node" {
|
||||
if p := os.Getenv("NODE_PATH"); p != "" {
|
||||
nodePath = filepath.Join(p, "node")
|
||||
}
|
||||
}
|
||||
|
||||
cmd := exec.Command(nodePath, arg, dir)
|
||||
if workDir == "" {
|
||||
workDir = dir
|
||||
}
|
||||
cmd.Dir = workDir
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
// Add openclaw CLI bin dir to PATH so subprocesses can exec 'openclaw' command
|
||||
if simDir != "" {
|
||||
binDir := filepath.Join(simDir, "bin")
|
||||
if info, err := os.Stat(binDir); err == nil && info.IsDir() {
|
||||
env := os.Environ()
|
||||
binDirPath := binDir + string(os.PathListSeparator)
|
||||
for i, e := range env {
|
||||
if strings.HasPrefix(e, "PATH=") {
|
||||
env[i] = "PATH=" + binDirPath + e[5:]
|
||||
break
|
||||
}
|
||||
}
|
||||
cmd.Env = env
|
||||
}
|
||||
}
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stdin pipe: %w", err)
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stdout pipe: %w", err)
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("start %s: %w", name, err)
|
||||
}
|
||||
|
||||
sp := newSidecarProcess(name, dir, cmd, bufio.NewWriter(stdin), stdout)
|
||||
|
||||
if err := sp.waitReady(); err != nil {
|
||||
sp.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
// sidecarReadyTimeout 是等 sidecar 回第一个 ping 的上限。
|
||||
//
|
||||
// ★ 从固定 5s 放宽到 30s(2026-10-25 修 CI 误报)。
|
||||
//
|
||||
// 原来的 5s 是**按开发机估算**的:node 冷启动 + 模块加载在快盘上空载时
|
||||
// 约 0.2s。而 CI 的共享 runner(以及真实部署里的低配机器)上,一次
|
||||
// fork+exec+node 引导遇到 CPU 争抢就会到 5s 以上,实测 CI 报
|
||||
// `sidecar echoplugin ping timeout` 而本机全绿。
|
||||
//
|
||||
// 这不是"测试环境太慢所以放宽测试"——它是**产品行为**:sidecar 起不来
|
||||
// 等于该 skill 整体不可用。给足时间是正确取舍;判断"真的挂了"应由进程
|
||||
// 退出信号负责(readLoop 会感知),而不是由引导耗时猜。
|
||||
//
|
||||
// 30s 的取法:比 systemd 的 TimeoutStopSec(25s) 宽,比用户可感知的
|
||||
// "卡住"阈值(约 30s)持平——再长就该让用户看到明确失败。
|
||||
const sidecarReadyTimeout = 30 * time.Second
|
||||
|
||||
func (s *sidecarProcess) waitReady() error {
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := s.call("ping", nil)
|
||||
done <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(sidecarReadyTimeout):
|
||||
return fmt.Errorf("sidecar %s ping timeout(%v 内未响应;慢机器上 node 冷启动可能更久,"+
|
||||
"若持续失败请检查 node 是否可用)", s.name, sidecarReadyTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) call(method string, params interface{}) ([]byte, error) {
|
||||
ch := make(chan []byte, 1)
|
||||
|
||||
s.mu.Lock()
|
||||
if s.closed || s.stopped {
|
||||
s.mu.Unlock()
|
||||
return nil, fmt.Errorf("sidecar %s closed", s.name)
|
||||
}
|
||||
s.nextID++
|
||||
id := s.nextID
|
||||
s.pending[id] = &pendingResp{ch: ch}
|
||||
|
||||
req := sidecarRequest{
|
||||
JSONRPC: "2.0",
|
||||
ID: id,
|
||||
Method: method,
|
||||
Params: params,
|
||||
}
|
||||
data, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
delete(s.pending, id)
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.stdin.Write(data); err != nil {
|
||||
delete(s.pending, id)
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.stdin.Write([]byte("\n")); err != nil {
|
||||
delete(s.pending, id)
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if err := s.stdin.Flush(); err != nil {
|
||||
delete(s.pending, id)
|
||||
s.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
select {
|
||||
case raw := <-ch:
|
||||
if raw == nil {
|
||||
return nil, fmt.Errorf("sidecar %s error: nil response", s.name)
|
||||
}
|
||||
var resp sidecarResponse
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return nil, fmt.Errorf("sidecar %s unmarshal: %w", s.name, err)
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return nil, fmt.Errorf("sidecar %s error: %s", s.name, resp.Error.Message)
|
||||
}
|
||||
if resp.Result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return []byte(*resp.Result), nil
|
||||
case <-time.After(30 * time.Second):
|
||||
s.mu.Lock()
|
||||
delete(s.pending, id)
|
||||
s.mu.Unlock()
|
||||
return nil, fmt.Errorf("sidecar %s call %s timeout", s.name, method)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) ListTools() ([]OCPTool, error) {
|
||||
data, err := s.call("tools/list", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var result struct {
|
||||
Tools []OCPTool `json:"tools"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.Tools, nil
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) CallTool(name string, args map[string]interface{}) (string, error) {
|
||||
data, err := s.call("tools/call", map[string]interface{}{
|
||||
"name": name,
|
||||
"arguments": args,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if data == nil {
|
||||
return "", nil
|
||||
}
|
||||
var result OCCallResult
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var sb string
|
||||
for _, c := range result.Content {
|
||||
if c.Type == "text" {
|
||||
sb += c.Text
|
||||
}
|
||||
}
|
||||
return sb, nil
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) CallProvider(providerType string, args map[string]interface{}) (string, error) {
|
||||
data, err := s.call("provider/call", map[string]interface{}{
|
||||
"type": providerType,
|
||||
"action": "execute",
|
||||
"args": args,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if data == nil {
|
||||
return "", nil
|
||||
}
|
||||
var result OCCallResult
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var sb string
|
||||
for _, c := range result.Content {
|
||||
if c.Type == "text" {
|
||||
sb += c.Text
|
||||
}
|
||||
}
|
||||
return sb, nil
|
||||
}
|
||||
|
||||
func (s *sidecarProcess) Close() {
|
||||
s.mu.Lock()
|
||||
if s.closed || s.stopped {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.stopped = true
|
||||
s.mu.Unlock()
|
||||
|
||||
// 先杀进程(关闭 stdout pipe),然后 reader 的 Scan() 会退出
|
||||
if s.cmd != nil && s.cmd.Process != nil {
|
||||
s.cmd.Process.Kill()
|
||||
s.cmd.Wait()
|
||||
}
|
||||
|
||||
// 等 reader 循环结束
|
||||
s.readerWg.Wait()
|
||||
|
||||
s.mu.Lock()
|
||||
for id, pr := range s.pending {
|
||||
pr.closeOnce()
|
||||
delete(s.pending, id)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
log.Printf("[clawhubadapter] sidecar %s stopped", s.name)
|
||||
}
|
||||
@ -1,409 +0,0 @@
|
||||
package clawhubadapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
sdk "github.com/JianFeeeee/HologramAgent/internal/sdk"
|
||||
pubsdk "github.com/JianFeeeee/hologramagentsdk/sdk"
|
||||
)
|
||||
|
||||
// mockSettings implements pubsdk.SettingsAPI for tests
|
||||
type mockSettings struct{}
|
||||
|
||||
func (m *mockSettings) DataDir() string { return "/tmp/mock_data" }
|
||||
|
||||
func (m *mockSettings) Get(key string) (interface{}, error) { return nil, nil }
|
||||
func (m *mockSettings) Set(key string, value interface{}) error { return nil }
|
||||
func (m *mockSettings) SetSecret(key string, value interface{}) error { return nil }
|
||||
func (m *mockSettings) GetSecret(key string) (string, error) { return "", nil }
|
||||
func (m *mockSettings) List(prefix string) ([]string, error) { return nil, nil }
|
||||
func (m *mockSettings) GetCore(key string) (interface{}, error) { return nil, nil }
|
||||
func (m *mockSettings) SetCore(key string, value interface{}) error { return nil }
|
||||
func (m *mockSettings) ListCore(prefix string) ([]string, error) { return nil, nil }
|
||||
func (m *mockSettings) GetPlugin(plugin, key string) (interface{}, error) { return nil, nil }
|
||||
func (m *mockSettings) SetPlugin(plugin, key string, value interface{}) error { return nil }
|
||||
func (m *mockSettings) ListPlugin(plugin, prefix string) ([]string, error) { return nil, nil }
|
||||
|
||||
// IsSecret:E-3 起 SettingsAPI 要求实现(判断某键是否按密文存储)。
|
||||
// 判据实现返回 false(mock 里没有密文语义),够用即可。
|
||||
func (m *mockSettings) IsSecret(key string) bool { return false }
|
||||
func (m *mockSettings) RegisterDef(def pubsdk.ConfigDef) {}
|
||||
func (m *mockSettings) Defs(prefix string) []*pubsdk.ConfigDef { return nil }
|
||||
func (m *mockSettings) Dump() map[string]interface{} { return nil }
|
||||
func (m *mockSettings) Plugins() []string { return nil }
|
||||
func (m *mockSettings) DefsCore(prefix string) []*sdk.ConfigDef { return nil }
|
||||
func (m *mockSettings) DefsPlugin(plugin, prefix string) []*sdk.ConfigDef { return nil }
|
||||
func (m *mockSettings) Remove(key string) error { return nil }
|
||||
func (m *mockSettings) RemoveCore(key string) error { return nil }
|
||||
func (m *mockSettings) RemovePlugin(plugin, key string) error { return nil }
|
||||
|
||||
func TestLaunchSidecarNoMainJS(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
sp, err := launchSidecar(tmpDir, "nonexistent", "")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if sp != nil {
|
||||
t.Fatal("expected nil for dir without main.js")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaunchSidecarAndListTools(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
src := filepath.Join("testdata", "echoplugin", "main.js")
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read test plugin: %v", err)
|
||||
}
|
||||
dst := filepath.Join(tmpDir, "main.js")
|
||||
if err := os.WriteFile(dst, data, 0755); err != nil {
|
||||
t.Fatalf("write test plugin: %v", err)
|
||||
}
|
||||
|
||||
sp, err := launchSidecar(tmpDir, "echoplugin", "")
|
||||
if err != nil {
|
||||
t.Fatalf("launch sidecar: %v", err)
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
tools, err := sp.ListTools()
|
||||
if err != nil {
|
||||
t.Fatalf("list tools: %v", err)
|
||||
}
|
||||
|
||||
if len(tools) == 0 {
|
||||
t.Fatal("expected at least one tool")
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, tool := range tools {
|
||||
if tool.Name == "echo" {
|
||||
found = true
|
||||
if tool.Description == "" {
|
||||
t.Error("expected non-empty description for echo tool")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("expected 'echo' tool in list")
|
||||
}
|
||||
t.Logf("tools: %+v", tools)
|
||||
}
|
||||
|
||||
func TestCallEchoTool(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
src := filepath.Join("testdata", "echoplugin", "main.js")
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read test plugin: %v", err)
|
||||
}
|
||||
dst := filepath.Join(tmpDir, "main.js")
|
||||
if err := os.WriteFile(dst, data, 0755); err != nil {
|
||||
t.Fatalf("write test plugin: %v", err)
|
||||
}
|
||||
|
||||
sp, err := launchSidecar(tmpDir, "echoplugin", "")
|
||||
if err != nil {
|
||||
t.Fatalf("launch sidecar: %v", err)
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
result, err := sp.CallTool("echo", map[string]interface{}{
|
||||
"text": "hello world",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("call echo tool: %v", err)
|
||||
}
|
||||
|
||||
expected := "Echo: hello world"
|
||||
if result != expected {
|
||||
t.Fatalf("expected %q, got %q", expected, result)
|
||||
}
|
||||
t.Logf("echo result: %s", result)
|
||||
}
|
||||
|
||||
func TestCallAddTool(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
src := filepath.Join("testdata", "echoplugin", "main.js")
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read test plugin: %v", err)
|
||||
}
|
||||
dst := filepath.Join(tmpDir, "main.js")
|
||||
if err := os.WriteFile(dst, data, 0755); err != nil {
|
||||
t.Fatalf("write test plugin: %v", err)
|
||||
}
|
||||
|
||||
sp, err := launchSidecar(tmpDir, "echoplugin", "")
|
||||
if err != nil {
|
||||
t.Fatalf("launch sidecar: %v", err)
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
result, err := sp.CallTool("add", map[string]interface{}{
|
||||
"a": 3.0,
|
||||
"b": 4.0,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("call add tool: %v", err)
|
||||
}
|
||||
|
||||
expected := "7"
|
||||
if result != expected {
|
||||
t.Fatalf("expected %q, got %q", expected, result)
|
||||
}
|
||||
t.Logf("add result: %s", result)
|
||||
}
|
||||
|
||||
func TestCallNonexistentTool(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
src := filepath.Join("testdata", "echoplugin", "main.js")
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read test plugin: %v", err)
|
||||
}
|
||||
dst := filepath.Join(tmpDir, "main.js")
|
||||
if err := os.WriteFile(dst, data, 0755); err != nil {
|
||||
t.Fatalf("write test plugin: %v", err)
|
||||
}
|
||||
|
||||
sp, err := launchSidecar(tmpDir, "echoplugin", "")
|
||||
if err != nil {
|
||||
t.Fatalf("launch sidecar: %v", err)
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
_, err = sp.CallTool("nonexistent", nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent tool")
|
||||
}
|
||||
t.Logf("expected error: %v", err)
|
||||
}
|
||||
|
||||
func TestConcurrentCalls(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
src := filepath.Join("testdata", "echoplugin", "main.js")
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read test plugin: %v", err)
|
||||
}
|
||||
dst := filepath.Join(tmpDir, "main.js")
|
||||
if err := os.WriteFile(dst, data, 0755); err != nil {
|
||||
t.Fatalf("write test plugin: %v", err)
|
||||
}
|
||||
|
||||
sp, err := launchSidecar(tmpDir, "echoplugin", "")
|
||||
if err != nil {
|
||||
t.Fatalf("launch sidecar: %v", err)
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
done := make(chan bool, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
go func(n int) {
|
||||
result, err := sp.CallTool("add", map[string]interface{}{
|
||||
"a": float64(n),
|
||||
"b": float64(n * 2),
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("concurrent call %d: %v", n, err)
|
||||
}
|
||||
if result != fmt.Sprintf("%d", n+n*2) {
|
||||
t.Errorf("call %d: expected %d, got %s", n, n+n*2, result)
|
||||
}
|
||||
done <- true
|
||||
}(i)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Simulator + OpenClaw plugin tests ----
|
||||
|
||||
func launchSimulator(t *testing.T, pluginDir, name string) *sidecarProcess {
|
||||
t.Helper()
|
||||
simPath, err := filepath.Abs(filepath.Join("simulator", "main.js"))
|
||||
if err != nil {
|
||||
t.Fatalf("abs simulator path: %v", err)
|
||||
}
|
||||
sp, err := launchProcess("node", simPath, pluginDir, name, "")
|
||||
if err != nil {
|
||||
t.Fatalf("launch simulator for %s: %v", name, err)
|
||||
}
|
||||
return sp
|
||||
}
|
||||
|
||||
func TestSimulatorWithOCSimple(t *testing.T) {
|
||||
pluginDir, err := filepath.Abs(filepath.Join("testdata", "oc-simple"))
|
||||
if err != nil {
|
||||
t.Fatalf("abs testdata: %v", err)
|
||||
}
|
||||
sp := launchSimulator(t, pluginDir, "oc-simple")
|
||||
defer sp.Close()
|
||||
|
||||
tools, err := sp.ListTools()
|
||||
if err != nil {
|
||||
t.Fatalf("list tools: %v", err)
|
||||
}
|
||||
if len(tools) != 2 {
|
||||
t.Fatalf("expected 2 tools, got %d: %+v", len(tools), tools)
|
||||
}
|
||||
|
||||
found := map[string]bool{"greet": false, "ping": false}
|
||||
for _, tool := range tools {
|
||||
found[tool.Name] = true
|
||||
}
|
||||
if !found["greet"] || !found["ping"] {
|
||||
t.Fatalf("expected greet and ping tools, got %+v", tools)
|
||||
}
|
||||
|
||||
result, err := sp.CallTool("greet", map[string]interface{}{"name": "Test"})
|
||||
if err != nil {
|
||||
t.Fatalf("call greet: %v", err)
|
||||
}
|
||||
if result != "Hello, Test!" {
|
||||
t.Fatalf("expected 'Hello, Test!', got %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSimulatorWithOCPackage(t *testing.T) {
|
||||
pluginDir, err := filepath.Abs(filepath.Join("testdata", "oc-pkg"))
|
||||
if err != nil {
|
||||
t.Fatalf("abs testdata: %v", err)
|
||||
}
|
||||
sp := launchSimulator(t, pluginDir, "oc-pkg")
|
||||
defer sp.Close()
|
||||
|
||||
tools, err := sp.ListTools()
|
||||
if err != nil {
|
||||
t.Fatalf("list tools: %v", err)
|
||||
}
|
||||
if len(tools) != 2 {
|
||||
t.Fatalf("expected 2 tools, got %d: %+v", len(tools), tools)
|
||||
}
|
||||
|
||||
found := map[string]bool{"add": false, "info": false}
|
||||
for _, tool := range tools {
|
||||
found[tool.Name] = true
|
||||
if tool.Name == "add" {
|
||||
if tool.InputSchema == nil {
|
||||
t.Error("add tool should have inputSchema")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found["add"] || !found["info"] {
|
||||
t.Fatalf("expected add and info tools, got %+v", tools)
|
||||
}
|
||||
|
||||
result, err := sp.CallTool("add", map[string]interface{}{"a": 10.0, "b": 20.0})
|
||||
if err != nil {
|
||||
t.Fatalf("call add: %v", err)
|
||||
}
|
||||
if result != "30" {
|
||||
t.Fatalf("expected '30', got %q", result)
|
||||
}
|
||||
|
||||
infoResult, err := sp.CallTool("info", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("call info: %v", err)
|
||||
}
|
||||
if infoResult == "" {
|
||||
t.Fatal("expected non-empty info result")
|
||||
}
|
||||
t.Logf("info result: %s", infoResult)
|
||||
}
|
||||
|
||||
func TestLoadOCPluginViaPluginStart(t *testing.T) {
|
||||
skillsDir := t.TempDir()
|
||||
|
||||
ocSimpleDir := filepath.Join(skillsDir, "oc-simple")
|
||||
if err := os.MkdirAll(ocSimpleDir, 0755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
for _, name := range []string{"openclaw.plugin.json", "index.js"} {
|
||||
src := filepath.Join("testdata", "oc-simple", name)
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", name, err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(ocSimpleDir, name), data, 0644); err != nil {
|
||||
t.Fatalf("write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
ocPkgDir := filepath.Join(skillsDir, "oc-pkg")
|
||||
if err := os.MkdirAll(filepath.Join(ocPkgDir, "lib"), 0755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
for _, name := range []string{"package.json", "lib/entry.js"} {
|
||||
src := filepath.Join("testdata", "oc-pkg", name)
|
||||
data, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", name, err)
|
||||
}
|
||||
dst := filepath.Join(ocPkgDir, name)
|
||||
if err := os.WriteFile(dst, data, 0644); err != nil {
|
||||
t.Fatalf("write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
p := New("openclaw", skillsDir)
|
||||
|
||||
var registeredTools []string
|
||||
registeredHandlers := make(map[string]sdk.ToolHandler)
|
||||
sdk := sdk.New("openclaw", sdk.SDKConfig{
|
||||
Settings: &mockSettings{},
|
||||
RegTool: func(name string, def sdk.ToolDef, handler sdk.ToolHandler) error {
|
||||
registeredTools = append(registeredTools, name)
|
||||
registeredHandlers[name] = handler
|
||||
return nil
|
||||
},
|
||||
})
|
||||
|
||||
if err := p.Start(sdk); err != nil {
|
||||
t.Fatalf("start plugin: %v", err)
|
||||
}
|
||||
defer p.Stop()
|
||||
|
||||
expected := []string{"oc-simple_greet", "oc-simple_ping", "oc-pkg_add", "oc-pkg_info"}
|
||||
for _, exp := range expected {
|
||||
found := false
|
||||
for _, name := range registeredTools {
|
||||
if name == exp {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected tool %q not registered. got: %v", exp, registeredTools)
|
||||
}
|
||||
}
|
||||
|
||||
handler, ok := registeredHandlers["oc-simple_greet"]
|
||||
if !ok {
|
||||
t.Fatal("greet handler not registered")
|
||||
}
|
||||
result, err := handler(map[string]interface{}{"name": "OpenClaw"})
|
||||
if err != nil {
|
||||
t.Fatalf("exec greet: %v", err)
|
||||
}
|
||||
if result != "Hello, OpenClaw!" {
|
||||
t.Fatalf("expected 'Hello, OpenClaw!', got %v", result)
|
||||
}
|
||||
|
||||
handler, ok = registeredHandlers["oc-pkg_add"]
|
||||
if !ok {
|
||||
t.Fatal("add handler not registered")
|
||||
}
|
||||
result, err = handler(map[string]interface{}{"a": 7.0, "b": 8.0})
|
||||
if err != nil {
|
||||
t.Fatalf("exec add: %v", err)
|
||||
}
|
||||
if result != "15" {
|
||||
t.Fatalf("expected '15', got %v", result)
|
||||
}
|
||||
}
|
||||
@ -1,422 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// ---- 工具函数 ----
|
||||
function writeJSON(obj) {
|
||||
process.stdout.write(JSON.stringify(obj) + '\n');
|
||||
}
|
||||
|
||||
function sendError(id, code, message) {
|
||||
writeJSON({ jsonrpc: '2.0', id, error: { code, message } });
|
||||
}
|
||||
|
||||
function readJSON(file) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function notify(method, params) {
|
||||
writeJSON({ jsonrpc: '2.0', method, params });
|
||||
}
|
||||
|
||||
// ---- 解析插件入口 ----
|
||||
const pluginDir = path.resolve(process.argv[2]);
|
||||
if (!pluginDir) {
|
||||
process.stderr.write('[simulator] usage: node main.js <plugin-dir>\n');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const pkgPath = path.join(pluginDir, 'package.json');
|
||||
const pkg = readJSON(pkgPath);
|
||||
let entryPath = null;
|
||||
|
||||
if (pkg && pkg.openclaw) {
|
||||
let raw = pkg.openclaw.runtimeExtensions || pkg.openclaw.extensions;
|
||||
if (typeof raw === 'string') raw = [raw];
|
||||
if (Array.isArray(raw) && raw.length > 0) {
|
||||
for (const ext of raw) {
|
||||
let ep = path.resolve(pluginDir, ext);
|
||||
if (ep.endsWith('.ts')) {
|
||||
const jsEp = ep.replace(/\.ts$/, '.js');
|
||||
if (fs.existsSync(jsEp)) { entryPath = jsEp; break; }
|
||||
}
|
||||
if (fs.existsSync(ep)) { entryPath = ep; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!entryPath) {
|
||||
const manifest = readJSON(path.join(pluginDir, 'openclaw.plugin.json'));
|
||||
if (manifest) {
|
||||
const ep = manifest.entry || manifest.main || 'index.js';
|
||||
entryPath = path.join(pluginDir, ep);
|
||||
}
|
||||
}
|
||||
|
||||
if (!entryPath) {
|
||||
entryPath = path.join(pluginDir, 'index.js');
|
||||
}
|
||||
|
||||
if (!fs.existsSync(entryPath)) {
|
||||
process.stderr.write(`[simulator] entry not found: ${entryPath}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ---- 加载插件 ----
|
||||
let pluginEntry;
|
||||
try {
|
||||
pluginEntry = require(entryPath);
|
||||
} catch (e) {
|
||||
process.stderr.write(`[simulator] load plugin: ${e.message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const entry = pluginEntry.default || pluginEntry;
|
||||
|
||||
if (typeof entry !== 'object' || typeof entry.register !== 'function') {
|
||||
process.stderr.write(`[simulator] plugin entry must export {default: {register(api)}}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ---- 注册工具(本地存储,供 tools/list 和 tools/call 用) ----
|
||||
const registeredTools = [];
|
||||
|
||||
// ---- Provider 存储(供 provider/call 用) ----
|
||||
const registeredProviders = {}; // type -> { name, instance }
|
||||
|
||||
// ---- Channel 存储(供 tools/call 中通道输出路由用) ----
|
||||
const registeredChannels = {}; // name -> { output, send, channelPlugin, type }
|
||||
|
||||
function registerTool(defOrFactory, opts) {
|
||||
if (typeof defOrFactory === 'function') {
|
||||
const toolCtx = {
|
||||
id: 'simulator',
|
||||
cwd: pluginDir,
|
||||
env: process.env,
|
||||
allow: ['*'],
|
||||
};
|
||||
const result = defOrFactory(toolCtx);
|
||||
const tools = Array.isArray(result) ? result : [result];
|
||||
for (const t of tools) {
|
||||
if (t && typeof t.execute === 'function') {
|
||||
registeredTools.push(t);
|
||||
notify('register', { type: 'tool', data: { name: t.name, description: t.description, parameters: t.parameters } });
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const def = defOrFactory;
|
||||
if (!def || !def.name) return;
|
||||
|
||||
registeredTools.push({
|
||||
name: def.name,
|
||||
label: def.label || def.name,
|
||||
description: def.description || '',
|
||||
parameters: def.parameters || { type: 'object', properties: {} },
|
||||
execute: typeof def.execute === 'function' ? def.execute : undefined,
|
||||
});
|
||||
notify('register', { type: 'tool', data: { name: def.name, label: def.label, description: def.description, parameters: def.parameters } });
|
||||
}
|
||||
|
||||
// ---- 构造完整的 OpenClawPluginApi ----
|
||||
const api = {
|
||||
id: entry.id || 'unknown',
|
||||
name: entry.name || 'Unknown',
|
||||
version: entry.version,
|
||||
description: entry.description,
|
||||
source: pluginDir,
|
||||
rootDir: pluginDir,
|
||||
config: {},
|
||||
pluginConfig: {},
|
||||
registrationMode: 'full',
|
||||
logger: {
|
||||
debug: (...args) => {},
|
||||
info: (...args) => {},
|
||||
warn: (...args) => {},
|
||||
error: (...args) => process.stderr.write(`[plugin] ${args.join(' ')}\n`),
|
||||
},
|
||||
resolvePath: (p) => path.resolve(pluginDir, p),
|
||||
|
||||
// ---- 工具注册 ----
|
||||
registerTool,
|
||||
|
||||
// ---- Provider 注册(同时存储实例,支持 provider/call) ----
|
||||
registerProvider: (provider) => {
|
||||
if (provider && provider.id) registeredProviders['llm'] = { name: provider.id, instance: provider };
|
||||
notify('register', { type: 'provider', data: { name: provider?.id || provider?.name, description: provider?.description } });
|
||||
},
|
||||
registerEmbeddingProvider: (p) => {
|
||||
if (p) registeredProviders['embedding'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'embedding_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerSpeechProvider: (p) => {
|
||||
if (p) registeredProviders['speech'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'speech_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerRealtimeTranscriptionProvider: (p) => {
|
||||
if (p) registeredProviders['realtime_transcription'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'realtime_transcription_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerRealtimeVoiceProvider: (p) => {
|
||||
if (p) registeredProviders['realtime_voice'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'realtime_voice_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerMediaUnderstandingProvider: (p) => {
|
||||
if (p) registeredProviders['media_understanding'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'media_understanding_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerImageGenerationProvider: (p) => {
|
||||
if (p) registeredProviders['image_generation'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'image_generation_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerMusicGenerationProvider: (p) => {
|
||||
if (p) registeredProviders['music_generation'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'music_generation_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerVideoGenerationProvider: (p) => {
|
||||
if (p) registeredProviders['video_generation'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'video_generation_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerWebFetchProvider: (p) => {
|
||||
if (p) registeredProviders['web_fetch'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'web_fetch_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerWebSearchProvider: (p) => {
|
||||
if (p) registeredProviders['web_search'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'web_search_provider', data: { name: p?.name } });
|
||||
},
|
||||
registerMemoryEmbeddingProvider: (p) => {
|
||||
if (p) registeredProviders['memory_embedding'] = { name: p.name, instance: p };
|
||||
notify('register', { type: 'memory_embedding_provider', data: { name: p?.name } });
|
||||
},
|
||||
|
||||
// ---- Channel 注册 ----
|
||||
registerChannel: (ch) => {
|
||||
let chName = ch.name;
|
||||
let chType = ch.type || 'text';
|
||||
const chPlugin = ch.plugin;
|
||||
if (chPlugin && typeof chPlugin === 'object') {
|
||||
registeredChannels[chName] = { channelPlugin: chPlugin, type: chType };
|
||||
} else {
|
||||
registeredChannels[chName] = { output: ch.output, send: ch.send, type: chType };
|
||||
}
|
||||
notify('register', { type: 'channel', data: { name: chName, type: chType } });
|
||||
},
|
||||
|
||||
// ---- 输入提交(submitInput -> channel_input notification) ----
|
||||
submitInput: (msg) => {
|
||||
notify('channel_input', { channel: api.name, payload: msg });
|
||||
},
|
||||
|
||||
// ---- Hook / 生命周期 ----
|
||||
registerHook: (hook) => notify('register', { type: 'hook', data: { name: hook.name, event: hook.event } }),
|
||||
registerRuntimeLifecycle: (lc) => notify('register', { type: 'runtime_lifecycle', data: { name: lc.name } }),
|
||||
|
||||
// ---- HTTP 路由 ----
|
||||
registerHttpRoute: (route) => notify('register', { type: 'http_route', data: { path: route.path, method: route.method } }),
|
||||
|
||||
// ---- CLI 命令 ----
|
||||
registerCommand: (cmd) => notify('register', { type: 'command', data: { name: cmd.name, description: cmd.description } }),
|
||||
registerCli: (cli) => notify('register', { type: 'cli', data: { name: cli.name } }),
|
||||
registerCliBackend: (cb) => notify('register', { type: 'cli_backend', data: { name: cb.name } }),
|
||||
registerNodeCliFeature: (f) => notify('register', { type: 'node_cli_feature', data: { name: f.name } }),
|
||||
|
||||
// ---- Service ----
|
||||
registerService: (svc) => notify('register', { type: 'service', data: { name: svc.name } }),
|
||||
|
||||
// ---- Agent 相关 ----
|
||||
registerAgentHarness: (h) => notify('register', { type: 'agent_harness', data: { name: h.name } }),
|
||||
registerAgentToolResultMiddleware: (m) => notify('register', { type: 'agent_tool_result_middleware', data: {} }),
|
||||
registerInteractiveHandler: (h) => notify('register', { type: 'interactive_handler', data: { name: h.name } }),
|
||||
|
||||
// ---- Gateway ----
|
||||
registerGatewayMethod: (gm) => notify('register', { type: 'gateway_method', data: { name: gm.name } }),
|
||||
registerGatewayDiscoveryService: (gs) => notify('register', { type: 'gateway_discovery_service', data: { name: gs.name } }),
|
||||
|
||||
// ---- Trust & Metadata ----
|
||||
registerTrustedToolPolicy: (p) => notify('register', { type: 'trusted_tool_policy', data: { name: p.name } }),
|
||||
registerToolMetadata: (m) => notify('register', { type: 'tool_metadata', data: { name: m.name } }),
|
||||
|
||||
// ---- Context Engine ----
|
||||
registerContextEngine: (ce) => notify('register', { type: 'context_engine', data: { name: ce.name } }),
|
||||
|
||||
// ---- Memory 子系统 ----
|
||||
registerMemoryCapability: (mc) => notify('register', { type: 'memory_capability', data: { name: mc.name } }),
|
||||
registerMemoryPromptSection: (ps) => notify('register', { type: 'memory_prompt_section', data: { name: ps.name } }),
|
||||
registerMemoryFlushPlan: (fp) => notify('register', { type: 'memory_flush_plan', data: { name: fp.name } }),
|
||||
registerMemoryRuntime: (mr) => notify('register', { type: 'memory_runtime', data: { name: mr.name } }),
|
||||
registerMemoryPromptSupplement: (ps) => notify('register', { type: 'memory_prompt_supplement', data: { name: ps.name } }),
|
||||
registerMemoryCorpusSupplement: (cs) => notify('register', { type: 'memory_corpus_supplement', data: { name: cs.name } }),
|
||||
|
||||
// ---- 会话相关 ----
|
||||
on: (event, handler) => notify('register', { type: 'session_event', data: { event } }),
|
||||
onConversationBindingResolved: (handler) => notify('register', { type: 'conversation_binding_resolved', data: {} }),
|
||||
|
||||
session: {
|
||||
state: { registerSessionExtension: (se) => notify('register', { type: 'session_extension', data: { name: se.name } }) },
|
||||
workflow: {
|
||||
enqueueNextTurnInjection: () => {},
|
||||
registerSessionSchedulerJob: (job) => notify('register', { type: 'session_scheduler_job', data: { name: job.name } }),
|
||||
sendSessionAttachment: () => {},
|
||||
scheduleSessionTurn: () => {},
|
||||
unscheduleSessionTurnsByTag: () => {},
|
||||
},
|
||||
controls: {
|
||||
registerControlUiDescriptor: (d) => notify('register', { type: 'control_ui_descriptor', data: { name: d.name } }),
|
||||
registerSessionAction: (a) => notify('register', { type: 'session_action', data: { name: a.name } }),
|
||||
},
|
||||
},
|
||||
|
||||
agent: {
|
||||
events: {
|
||||
registerAgentEventSubscription: (sub) => notify('register', { type: 'agent_event_subscription', data: { event: sub.event } }),
|
||||
emitAgentEvent: (event, data) => notify('agent_event', { event, data }),
|
||||
},
|
||||
},
|
||||
|
||||
lifecycle: { registerRuntimeLifecycle: (lc) => notify('register', { type: 'lifecycle', data: { name: lc.name } }) },
|
||||
|
||||
runContext: {
|
||||
setRunContext: () => {},
|
||||
getRunContext: () => ({}),
|
||||
clearRunContext: () => {},
|
||||
},
|
||||
|
||||
runtime: {},
|
||||
};
|
||||
|
||||
// ---- 注册插件 ----
|
||||
entry.register(api);
|
||||
|
||||
// ---- JSON-RPC 协议处理 ----
|
||||
const readline = require('readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: false,
|
||||
});
|
||||
|
||||
rl.on('line', async (line) => {
|
||||
let req;
|
||||
try {
|
||||
req = JSON.parse(line);
|
||||
} catch {
|
||||
sendError(null, -32700, 'Parse error');
|
||||
return;
|
||||
}
|
||||
|
||||
const id = req.id;
|
||||
const method = req.method;
|
||||
|
||||
if (method === 'ping') {
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { status: 'ok' } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'tools/list') {
|
||||
const tools = registeredTools.map(t => ({
|
||||
name: t.name,
|
||||
description: t.description || '',
|
||||
inputSchema: t.parameters || { type: 'object', properties: {} },
|
||||
}));
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { tools } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'tools/call') {
|
||||
const params = req.params || {};
|
||||
const toolName = params.name;
|
||||
const args = params.arguments || {};
|
||||
|
||||
// Channel output routing: if toolName matches a registered channel, use channel's output handler
|
||||
const ch = registeredChannels[toolName];
|
||||
if (ch) {
|
||||
try {
|
||||
const channelPlugin = ch.channelPlugin;
|
||||
if (channelPlugin && channelPlugin.outbound) {
|
||||
const meta = args.meta || '';
|
||||
let metaObj = {};
|
||||
try { metaObj = typeof meta === 'string' ? JSON.parse(meta) : meta; } catch {}
|
||||
const to = metaObj.user_id || metaObj.to || metaObj.group_id || '';
|
||||
const ctx = { to, text: args.payload || '', mediaUrl: metaObj.mediaUrl || '', cfg: {}, accountId: metaObj.accountId || null };
|
||||
let result;
|
||||
if (ctx.mediaUrl && channelPlugin.outbound.sendMedia) {
|
||||
result = await channelPlugin.outbound.sendMedia(ctx);
|
||||
} else if (channelPlugin.outbound.sendText) {
|
||||
result = await channelPlugin.outbound.sendText(ctx);
|
||||
} else {
|
||||
throw new Error(`channel ${toolName} has no sendText/sendMedia handler`);
|
||||
}
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { status: 'sent', result } });
|
||||
} else if (typeof ch.output === 'function') {
|
||||
const result = await ch.output(args.payload, args.type, args.meta);
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { status: 'sent', result } });
|
||||
} else if (typeof ch.send === 'function') {
|
||||
const result = await ch.send(args.payload, args.meta);
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { status: 'sent', result } });
|
||||
} else {
|
||||
sendError(id, -32601, `channel ${toolName} has no output handler`);
|
||||
}
|
||||
} catch (e) { sendError(id, -32603, e.message); }
|
||||
return;
|
||||
}
|
||||
|
||||
const tool = registeredTools.find(t => t.name === toolName);
|
||||
if (!tool) {
|
||||
sendError(id, -32601, `Tool not found: ${toolName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof tool.execute !== 'function') {
|
||||
sendError(id, -32603, `Tool ${toolName} has no execute function`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await tool.execute('sim-call-1', args, undefined, undefined);
|
||||
if (result && typeof result === 'object' && Array.isArray(result.content)) {
|
||||
writeJSON({ jsonrpc: '2.0', id, result });
|
||||
} else {
|
||||
const text = typeof result === 'string' ? result : JSON.stringify(result);
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }] } });
|
||||
}
|
||||
} catch (e) {
|
||||
sendError(id, -32603, e.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- Provider 调用 ----
|
||||
if (method === 'provider/call') {
|
||||
const { type, action, args } = req.params || {};
|
||||
if (!type) { sendError(id, -32602, 'type required'); return; }
|
||||
|
||||
const provider = registeredProviders[type];
|
||||
if (!provider) { sendError(id, -32601, `Provider not found: ${type}`); return; }
|
||||
|
||||
const methodName = action || 'execute';
|
||||
if (typeof provider.instance[methodName] !== 'function') {
|
||||
sendError(id, -32603, `Provider ${type} has no method ${methodName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await provider.instance[methodName](args);
|
||||
if (result && typeof result === 'object' && Array.isArray(result.content)) {
|
||||
writeJSON({ jsonrpc: '2.0', id, result });
|
||||
} else {
|
||||
const text = typeof result === 'string' ? result : JSON.stringify(result);
|
||||
writeJSON({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }] } });
|
||||
}
|
||||
} catch (e) {
|
||||
sendError(id, -32603, e.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
sendError(id, -32601, `Method not found: ${method}`);
|
||||
});
|
||||
@ -1,216 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { fork, execSync } = require('child_process');
|
||||
|
||||
const binDir = __dirname;
|
||||
const simDir = path.resolve(binDir, '..');
|
||||
|
||||
function readJSON(file) {
|
||||
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
|
||||
}
|
||||
|
||||
// ---- Resolve skills directory ----
|
||||
function resolveSkillsDir() {
|
||||
const skillsdirPath = path.join(simDir, '.skillsdir');
|
||||
if (fs.existsSync(skillsdirPath)) {
|
||||
return fs.readFileSync(skillsdirPath, 'utf8').trim();
|
||||
}
|
||||
const envDir = process.env.OPENCLAW_SKILLS_DIR;
|
||||
if (envDir) return path.resolve(envDir);
|
||||
const defaultDir = path.resolve(simDir, '..', 'skills');
|
||||
if (fs.existsSync(defaultDir)) return defaultDir;
|
||||
return null;
|
||||
}
|
||||
|
||||
const skillsDir = resolveSkillsDir();
|
||||
|
||||
// ---- Detect system openclaw conflict ----
|
||||
if (process.env.OPENCLAW_CLI !== '1') {
|
||||
const PATH = process.env.PATH || '';
|
||||
const pathEntries = PATH.split(path.delimiter);
|
||||
for (const entry of pathEntries) {
|
||||
if (entry === binDir) continue;
|
||||
const otherPath = path.join(entry, 'openclaw');
|
||||
try {
|
||||
if (fs.statSync(otherPath).isFile() && fs.realpathSync(otherPath) !== __filename) {
|
||||
process.stderr.write(`[openclaw] warning: found another openclaw at ${otherPath}\n`);
|
||||
process.stderr.write(`[openclaw] using: ${__filename}\n`);
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Settings helpers ----
|
||||
function getSettings() {
|
||||
return readJSON(path.join(simDir, '.settings.json')) || {};
|
||||
}
|
||||
|
||||
function writePendingSetting(key, value) {
|
||||
const pendingPath = path.join(simDir, '.settings-pending.json');
|
||||
let pending = readJSON(pendingPath) || {};
|
||||
pending[key] = value;
|
||||
fs.writeFileSync(pendingPath, JSON.stringify(pending, null, 2));
|
||||
}
|
||||
|
||||
// ---- Permission check for plugin commands ----
|
||||
function requireSkillsDir() {
|
||||
if (!skillsDir) {
|
||||
process.stderr.write('Error: cannot determine skills directory. Start the manager first or set OPENCLAW_SKILLS_DIR.\n');
|
||||
process.exit(1);
|
||||
}
|
||||
if (!fs.existsSync(skillsDir)) {
|
||||
fs.mkdirSync(skillsDir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Main ----
|
||||
const cmd = process.argv[2];
|
||||
|
||||
if (!cmd || cmd === 'help' || cmd === '--help') {
|
||||
console.log(`HologramAgent OpenClaw Adapter 1.0.0 (openclaw-compatible)
|
||||
Usage: openclaw <command> [args]
|
||||
|
||||
Commands:
|
||||
plugin:install <spec> Install a plugin (npm:xxx, clawhub:xxx, or path)
|
||||
plugin:uninstall <name> Uninstall a plugin
|
||||
plugin:list List installed plugins
|
||||
auth:login [url] Show QR code for login
|
||||
auth:status Check auth status
|
||||
config:get <key> Get config value
|
||||
config:set <key> <val> Set config value
|
||||
config:list List all config
|
||||
doctor Run diagnostics
|
||||
update Check for updates
|
||||
env Show runtime info
|
||||
--version Show version
|
||||
help Show this help`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === '--version' || cmd === 'version') {
|
||||
console.log('HologramAgent OpenClaw Adapter 1.0.0 (openclaw-compatible)');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'env') {
|
||||
requireSkillsDir();
|
||||
const info = {
|
||||
homeAgent: true,
|
||||
openclawVersion: 'compatible',
|
||||
platform: process.platform,
|
||||
nodeVersion: process.version,
|
||||
skillsDir: skillsDir,
|
||||
simulatorDir: simDir,
|
||||
openclawCli: __filename,
|
||||
};
|
||||
console.log(JSON.stringify(info, null, 2));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'doctor') {
|
||||
console.log('OpenClaw Adapter diagnostics:');
|
||||
console.log(` Simulator dir: ${simDir}`);
|
||||
console.log(` Skills dir: ${skillsDir || '(not set)'}`);
|
||||
console.log(` Node: ${process.version}`);
|
||||
console.log(` Platform: ${process.platform}`);
|
||||
if (skillsDir) {
|
||||
const entries = fs.readdirSync(skillsDir).filter(e => !e.startsWith('.'));
|
||||
console.log(` Installed plugins: ${entries.length}`);
|
||||
}
|
||||
console.log(' Status: OK');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'update') {
|
||||
console.log('Update check: HologramAgent OpenClaw Adapter is bundled with HologramAgent.');
|
||||
console.log('To update, update HologramAgent itself.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'config:get') {
|
||||
const key = process.argv[3];
|
||||
if (!key) { process.stderr.write('Usage: openclaw config:get <key>\n'); process.exit(1); }
|
||||
const settings = getSettings();
|
||||
if (key in settings) {
|
||||
console.log(settings[key]);
|
||||
} else {
|
||||
process.stderr.write(`(not set: ${key})\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'config:set') {
|
||||
const key = process.argv[3];
|
||||
const value = process.argv[4];
|
||||
if (!key || value === undefined) { process.stderr.write('Usage: openclaw config:set <key> <value>\n'); process.exit(1); }
|
||||
writePendingSetting(key, value);
|
||||
console.log(`Set: ${key}=${value} (will apply on next sync)`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'config:list') {
|
||||
const settings = getSettings();
|
||||
const keys = Object.keys(settings);
|
||||
if (keys.length === 0) {
|
||||
console.log('(no settings)');
|
||||
} else {
|
||||
for (const k of keys) {
|
||||
console.log(` ${k}=${settings[k]}`);
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'auth:login' || cmd === 'auth:qrcode') {
|
||||
const url = process.argv[3] || 'openclaw://auth';
|
||||
try {
|
||||
const qrcode = require('qrcode');
|
||||
qrcode.generate(url, { small: true }, (qr) => process.stdout.write(qr + '\n'));
|
||||
} catch {
|
||||
console.log('QR not available (install qrcode package). URL:');
|
||||
}
|
||||
console.log(` ${url}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (cmd === 'auth:status') {
|
||||
console.log('Auth status: running in HologramAgent mode (not applicable)');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// ---- Plugin lifecycle commands - needs manager.js fork ----
|
||||
if (cmd === 'plugin:install' || cmd === 'plugin:uninstall' || cmd === 'plugin:list') {
|
||||
requireSkillsDir();
|
||||
const managerPath = path.join(simDir, 'manager.js');
|
||||
if (!fs.existsSync(managerPath)) {
|
||||
process.stderr.write('Error: manager.js not found at ' + managerPath + '\n');
|
||||
process.exit(1);
|
||||
}
|
||||
const proc = fork(managerPath, [skillsDir, ...process.argv.slice(2)], {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, OPENCLAW_CLI: '1' },
|
||||
});
|
||||
proc.on('exit', (code) => {
|
||||
// After plugin:install, notify Go side via .reload-request
|
||||
if (cmd === 'plugin:install' && code === 0) {
|
||||
const spec = process.argv[3] || '';
|
||||
const installLog = path.join(simDir, '.install-result');
|
||||
if (fs.existsSync(installLog)) {
|
||||
const result = readJSON(installLog);
|
||||
if (result && result.name) {
|
||||
fs.writeFileSync(path.join(simDir, '.reload-request'), result.name);
|
||||
console.log(`[openclaw] queued reload for plugin: ${result.name}`);
|
||||
}
|
||||
fs.rmSync(installLog, { force: true });
|
||||
}
|
||||
}
|
||||
process.exit(code);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
process.stderr.write(`Unknown command: ${cmd}\n`);
|
||||
process.stderr.write("Run 'openclaw help' for usage.\n");
|
||||
process.exit(1);
|
||||
@ -1,106 +0,0 @@
|
||||
const readline = require('readline');
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: false
|
||||
});
|
||||
|
||||
const tools = [
|
||||
{
|
||||
name: 'echo',
|
||||
description: 'Echo back the input text',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: { type: 'string', description: 'Text to echo' }
|
||||
},
|
||||
required: ['text']
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'add',
|
||||
description: 'Add two numbers',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
a: { type: 'number', description: 'First number' },
|
||||
b: { type: 'number', description: 'Second number' }
|
||||
},
|
||||
required: ['a', 'b']
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'ping',
|
||||
description: 'Health check',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {}
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
rl.on('line', (line) => {
|
||||
let req;
|
||||
try {
|
||||
req = JSON.parse(line);
|
||||
} catch (e) {
|
||||
sendError(null, -32700, 'Parse error');
|
||||
return;
|
||||
}
|
||||
|
||||
const id = req.id;
|
||||
const method = req.method;
|
||||
|
||||
if (method === 'ping') {
|
||||
sendResult(id, { status: 'ok' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'tools/list') {
|
||||
sendResult(id, { tools });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'tools/call') {
|
||||
const params = req.params || {};
|
||||
const toolName = params.name;
|
||||
const args = params.arguments || {};
|
||||
|
||||
const tool = tools.find(t => t.name === toolName);
|
||||
if (!tool) {
|
||||
sendError(id, -32601, `Tool not found: ${toolName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
let result;
|
||||
switch (toolName) {
|
||||
case 'echo':
|
||||
result = { content: [{ type: 'text', text: `Echo: ${args.text || ''}` }] };
|
||||
break;
|
||||
case 'add':
|
||||
const sum = (Number(args.a) || 0) + (Number(args.b) || 0);
|
||||
result = { content: [{ type: 'text', text: `${sum}` }] };
|
||||
break;
|
||||
default:
|
||||
sendError(id, -32601, `Not implemented: ${toolName}`);
|
||||
return;
|
||||
}
|
||||
sendResult(id, result);
|
||||
return;
|
||||
}
|
||||
|
||||
sendError(id, -32601, `Method not found: ${method}`);
|
||||
});
|
||||
|
||||
function sendResult(id, result) {
|
||||
const resp = { jsonrpc: '2.0', id, result };
|
||||
process.stdout.write(JSON.stringify(resp) + '\n');
|
||||
}
|
||||
|
||||
function sendError(id, code, message) {
|
||||
const resp = { jsonrpc: '2.0', id, error: { code, message } };
|
||||
process.stdout.write(JSON.stringify(resp) + '\n');
|
||||
}
|
||||
|
||||
// Sidecar is ready - no startup message needed
|
||||
@ -1,33 +0,0 @@
|
||||
module.exports = {
|
||||
default: {
|
||||
id: 'oc-pkg',
|
||||
name: 'OC Package',
|
||||
version: '2.0.0',
|
||||
description: 'Test plugin discovered via package.json extensions',
|
||||
register(api) {
|
||||
api.registerTool({
|
||||
name: 'add',
|
||||
description: 'Add two numbers',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
a: { type: 'number', description: 'First number' },
|
||||
b: { type: 'number', description: 'Second number' },
|
||||
},
|
||||
required: ['a', 'b'],
|
||||
},
|
||||
execute(id, params) {
|
||||
return String(params.a + params.b);
|
||||
},
|
||||
});
|
||||
|
||||
api.registerTool({
|
||||
name: 'info',
|
||||
description: 'Return plugin info',
|
||||
execute(id, params) {
|
||||
return JSON.stringify({ id: this.id, name: this.name, version: this.version });
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
@ -1,8 +0,0 @@
|
||||
{
|
||||
"name": "oc-pkg",
|
||||
"version": "2.0.0",
|
||||
"description": "OC plugin with package.json entry discovery",
|
||||
"openclaw": {
|
||||
"extensions": ["lib/entry.js"]
|
||||
}
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
module.exports = {
|
||||
default: {
|
||||
id: 'oc-simple',
|
||||
name: 'OC Simple',
|
||||
version: '1.0.0',
|
||||
description: 'Simple test plugin for OpenClaw simulator',
|
||||
register(api) {
|
||||
api.registerTool({
|
||||
name: 'greet',
|
||||
description: 'Greet someone',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Name to greet' },
|
||||
},
|
||||
required: ['name'],
|
||||
},
|
||||
execute(id, params) {
|
||||
return `Hello, ${params.name}!`;
|
||||
},
|
||||
});
|
||||
api.registerTool({
|
||||
name: 'ping',
|
||||
description: 'Health check ping',
|
||||
execute(id, params) {
|
||||
return 'pong';
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "oc-simple",
|
||||
"version": "1.0.0",
|
||||
"entry": "index.js",
|
||||
"description": "Simple OpenClaw test plugin"
|
||||
}
|
||||
Reference in New Issue
Block a user