mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-21 17:38:10 +00:00
feat: C ABI plugin bridge for Linux c-shared plugins
- New internal/plugin/cabi/ package: dlopen + dlsym loader - plugindev: generates z_entry.c + z_bridge_gen.go for c-shared builds - plugindev: replaces -buildmode=plugin with -buildmode=c-shared - Go bridge uses mock SDK during Start(), core discovers registrations - PluginAPI: init/start/stop + invoke_tool/stage/output + get_tool_defs/stages/channels - ha_dispatch: single C function handles all plugin→core calls via method ID - tryLoadSO: tries C ABI first, falls back to Go plugin.Open - All example plugins updated (main.go removed, plg.json targets updated)
This commit is contained in:
262
internal/plugin/cabi/loader.go
Normal file
262
internal/plugin/cabi/loader.go
Normal file
@ -0,0 +1,262 @@
|
||||
package cabi
|
||||
|
||||
/*
|
||||
#cgo LDFLAGS: -ldl
|
||||
#include <dlfcn.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// PluginAPI struct (mirrors plugin ABI)
|
||||
typedef struct {
|
||||
int version;
|
||||
int version_min;
|
||||
int (*init_plugin)(char*, char*, char**);
|
||||
int (*start_plugin)(void*, int, char**);
|
||||
int (*stop_plugin)(char**);
|
||||
int (*invoke_tool)(char*, char*, char**, char**);
|
||||
int (*invoke_stage)(char*, char*, char**);
|
||||
int (*invoke_output)(char*, char*, char*, char**);
|
||||
void (*free_string)(char*);
|
||||
int (*get_tool_defs)(char**);
|
||||
int (*get_stages)(char**);
|
||||
int (*get_channels)(char**);
|
||||
} plugin_api_t;
|
||||
|
||||
// CoreAPI struct (implemented by core, passed to plugin)
|
||||
typedef struct {
|
||||
int version;
|
||||
int version_min;
|
||||
int (*register_tool)(char*, char*, char**);
|
||||
int (*register_stage)(char*, int, char**);
|
||||
int (*register_output_channel)(char*, int, char*, int, char**);
|
||||
int (*register_plugin_api)(char*, char**);
|
||||
int (*inject_text)(char*, char*, char*, char**);
|
||||
int (*inject_interrupt_text)(char*, char*, char*, char**);
|
||||
int (*inject_text_no_memory)(char*, char*, char*, char**);
|
||||
int (*set_auto_restart)(int, char**);
|
||||
int (*memory_recall)(char*, int, char**, char**);
|
||||
int (*memory_commit)(char*, char**);
|
||||
int (*memory_introspect)(char**, char**);
|
||||
int (*memory_merge)(char*, char*, char**);
|
||||
int (*memory_purge)(char*, int, char**);
|
||||
int (*doc_query)(char*, int, char**, char**);
|
||||
int (*knowledge_search)(char*, int, char**, char**);
|
||||
int (*settings_get)(char*, char**, char**);
|
||||
int (*settings_set)(char*, char*, char**);
|
||||
int (*settings_register_def)(char*, char**);
|
||||
int (*llm_list_sources)(char**, char**);
|
||||
int (*llm_set_source)(char*, char**);
|
||||
int (*social_get_person)(char*, char**, char**);
|
||||
int (*social_get_network)(char*, int, char**, char**);
|
||||
int (*subscribe)(char*, int, char**);
|
||||
int (*unsubscribe)(char*, int, char**);
|
||||
void (*free_string)(char*);
|
||||
} core_api_t;
|
||||
|
||||
// libHandle wraps a dlopen handle
|
||||
typedef void* libHandle;
|
||||
|
||||
libHandle lib_open(const char* path) {
|
||||
return dlopen(path, RTLD_NOW | RTLD_LOCAL);
|
||||
}
|
||||
|
||||
plugin_api_t* lib_get_api(libHandle h) {
|
||||
plugin_api_t* (*fn)(void);
|
||||
*(void**)(&fn) = dlsym(h, "plugin_init");
|
||||
if (!fn) return NULL;
|
||||
return fn();
|
||||
}
|
||||
|
||||
void lib_close(libHandle h) {
|
||||
dlclose(h);
|
||||
}
|
||||
|
||||
char* lib_get_error(void) {
|
||||
return dlerror();
|
||||
}
|
||||
|
||||
void api_free_string(plugin_api_t* api, char* ptr) {
|
||||
if (api && api->free_string) api->free_string(ptr);
|
||||
}
|
||||
|
||||
int call_init_plugin(plugin_api_t* api, char* name, char* config, char** err) { return api->init_plugin(name, config, err); }
|
||||
int call_start_plugin(plugin_api_t* api, void* core, int ver, char** err) { return api->start_plugin(core, ver, err); }
|
||||
int call_stop_plugin(plugin_api_t* api, char** err) { return api->stop_plugin(err); }
|
||||
int call_get_tool_defs(plugin_api_t* api, char** r) { return api->get_tool_defs(r); }
|
||||
int call_get_stages(plugin_api_t* api, char** r) { return api->get_stages(r); }
|
||||
int call_get_channels(plugin_api_t* api, char** r) { return api->get_channels(r); }
|
||||
int call_invoke_tool(plugin_api_t* api, char* n, char* a, char** r, char** e) { return api->invoke_tool(n, a, r, e); }
|
||||
int call_invoke_stage(plugin_api_t* api, char* s, char* c, char** e) { return api->invoke_stage(s, c, e); }
|
||||
int call_invoke_output(plugin_api_t* api, char* c, char* m, char* p, char** e) { return api->invoke_output(c, m, p, e); }
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Handle represents a loaded C ABI plugin.
|
||||
type Handle struct {
|
||||
soPath string
|
||||
lib C.libHandle
|
||||
api *C.plugin_api_t
|
||||
}
|
||||
|
||||
// Load opens a .so plugin and initializes it via the C ABI.
|
||||
func Load(soPath, name string, config map[string]interface{}) (*Handle, error) {
|
||||
cPath := C.CString(soPath)
|
||||
defer C.free(unsafe.Pointer(cPath))
|
||||
|
||||
lib := C.lib_open(cPath)
|
||||
if lib == nil {
|
||||
errStr := C.GoString(C.lib_get_error())
|
||||
return nil, fmt.Errorf("dlopen %s: %s", soPath, errStr)
|
||||
}
|
||||
|
||||
api := C.lib_get_api(lib)
|
||||
if api == nil {
|
||||
C.lib_close(lib)
|
||||
errStr := C.GoString(C.lib_get_error())
|
||||
return nil, fmt.Errorf("dlsym plugin_init in %s: %s", soPath, errStr)
|
||||
}
|
||||
|
||||
if int(api.version) < ABIVersionMin {
|
||||
C.lib_close(lib)
|
||||
return nil, fmt.Errorf("plugin %s ABI version %d < minimum %d", name, int(api.version), ABIVersionMin)
|
||||
}
|
||||
|
||||
handle := &Handle{soPath: soPath, lib: lib, api: api}
|
||||
|
||||
// Initialize plugin
|
||||
configJSON, _ := json.Marshal(config)
|
||||
cName := C.CString(name)
|
||||
cConfig := C.CString(string(configJSON))
|
||||
var initErr *C.char
|
||||
defer C.free(unsafe.Pointer(cName))
|
||||
defer C.free(unsafe.Pointer(cConfig))
|
||||
|
||||
if ret := C.int(C.call_init_plugin(api, cName, cConfig, &initErr)); ret != 0 {
|
||||
errMsg := ""
|
||||
if initErr != nil {
|
||||
errMsg = C.GoString(initErr)
|
||||
C.api_free_string(api, initErr)
|
||||
}
|
||||
handle.Close()
|
||||
return nil, fmt.Errorf("init_plugin %s: %s", name, errMsg)
|
||||
}
|
||||
|
||||
return handle, nil
|
||||
}
|
||||
|
||||
// Start calls the plugin's Start with a CoreAPI pointer.
|
||||
func (h *Handle) Start(corePtr unsafe.Pointer) error {
|
||||
if ret := C.int(C.call_start_plugin(h.api, corePtr, C.int(ABIVersion), nil)); ret != 0 {
|
||||
return fmt.Errorf("start_plugin failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop calls the plugin's Stop.
|
||||
func (h *Handle) Stop() error {
|
||||
if ret := C.int(C.call_stop_plugin(h.api, nil)); ret != 0 {
|
||||
return fmt.Errorf("stop_plugin failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetToolDefs returns the tool definitions registered by the plugin during Start.
|
||||
func (h *Handle) GetToolDefs() ([]json.RawMessage, error) {
|
||||
var result *C.char
|
||||
if ret := C.int(C.call_get_tool_defs(h.api, &result)); ret != 0 || result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
defer C.api_free_string(h.api, result)
|
||||
var defs []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &defs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return defs, nil
|
||||
}
|
||||
|
||||
// GetStages returns stage names registered by the plugin.
|
||||
func (h *Handle) GetStages() ([]string, error) {
|
||||
var result *C.char
|
||||
if ret := C.int(C.call_get_stages(h.api, &result)); ret != 0 || result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
defer C.api_free_string(h.api, result)
|
||||
var stages []string
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &stages); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stages, nil
|
||||
}
|
||||
|
||||
// GetChannels returns output channel registrations.
|
||||
func (h *Handle) GetChannels() ([]channelInfo, error) {
|
||||
var result *C.char
|
||||
if ret := C.int(C.call_get_channels(h.api, &result)); ret != 0 || result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
defer C.api_free_string(h.api, result)
|
||||
var channels []channelInfo
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &channels); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return channels, nil
|
||||
}
|
||||
|
||||
type channelInfo struct {
|
||||
Name string `json:"name"`
|
||||
Caps int `json:"caps"`
|
||||
Desc string `json:"desc"`
|
||||
}
|
||||
|
||||
// InvokeTool calls a tool handler in the plugin.
|
||||
func (h *Handle) InvokeTool(name string, args map[string]interface{}) (map[string]interface{}, error) {
|
||||
argsJSON, _ := json.Marshal(args)
|
||||
cName := C.CString(name)
|
||||
cArgs := C.CString(string(argsJSON))
|
||||
var result, cErr *C.char
|
||||
defer C.free(unsafe.Pointer(cName))
|
||||
defer C.free(unsafe.Pointer(cArgs))
|
||||
|
||||
if ret := C.int(C.call_invoke_tool(h.api, cName, cArgs, &result, &cErr)); ret != 0 {
|
||||
errMsg := ""
|
||||
if cErr != nil {
|
||||
errMsg = C.GoString(cErr)
|
||||
C.api_free_string(h.api, cErr)
|
||||
}
|
||||
return nil, fmt.Errorf("invoke_tool %s: %s", name, errMsg)
|
||||
}
|
||||
if result == nil {
|
||||
return nil, nil
|
||||
}
|
||||
defer C.api_free_string(h.api, result)
|
||||
var r map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(C.GoString(result)), &r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// InvokeStage calls a stage handler in the plugin.
|
||||
func (h *Handle) InvokeStage(stage, ctxJSON string) error {
|
||||
cStage := C.CString(stage)
|
||||
cCtx := C.CString(ctxJSON)
|
||||
defer C.free(unsafe.Pointer(cStage))
|
||||
defer C.free(unsafe.Pointer(cCtx))
|
||||
if ret := C.int(C.call_invoke_stage(h.api, cStage, cCtx, nil)); ret != 0 {
|
||||
return fmt.Errorf("invoke_stage %s failed", stage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close unloads the plugin library.
|
||||
func (h *Handle) Close() {
|
||||
if h.lib != nil {
|
||||
C.lib_close(h.lib)
|
||||
h.lib = nil
|
||||
}
|
||||
}
|
||||
36
internal/plugin/cabi/types.go
Normal file
36
internal/plugin/cabi/types.go
Normal file
@ -0,0 +1,36 @@
|
||||
package cabi
|
||||
|
||||
// ABI version constants
|
||||
const (
|
||||
ABIVersion = 1
|
||||
ABIVersionMin = 1
|
||||
)
|
||||
|
||||
// Dispatch method IDs (mirrors the plugin side constants)
|
||||
const (
|
||||
CoreRegisterTool = 1
|
||||
CoreRegisterStage = 2
|
||||
CoreRegisterOutputCh = 3
|
||||
CoreRegisterPluginAPI = 4
|
||||
CoreInjectText = 5
|
||||
CoreInjectInterruptText = 6
|
||||
CoreInjectTextNoMemory = 7
|
||||
CoreSetAutoRestart = 8
|
||||
CoreMemoryRecall = 9
|
||||
CoreMemoryCommit = 10
|
||||
CoreMemoryIntrospect = 11
|
||||
CoreMemoryMerge = 12
|
||||
CoreMemoryPurge = 13
|
||||
CoreDocQuery = 14
|
||||
CoreKnowledgeSearch = 15
|
||||
CoreSettingsGet = 16
|
||||
CoreSettingsSet = 17
|
||||
CoreSettingsRegisterDef = 18
|
||||
CoreLLMListSources = 19
|
||||
CoreLLMSetSource = 20
|
||||
CoreSocialGetPerson = 21
|
||||
CoreSocialGetNetwork = 22
|
||||
CoreSubscribe = 23
|
||||
CoreUnsubscribe = 24
|
||||
CoreFreeString = 25
|
||||
)
|
||||
@ -9,9 +9,12 @@ import (
|
||||
"path/filepath"
|
||||
"plugin"
|
||||
"reflect"
|
||||
"unsafe"
|
||||
|
||||
sdk "gitcode.com/JianFeeeee/HomeAgent/internal/sdk"
|
||||
pubsdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||
|
||||
"gitcode.com/JianFeeeee/HomeAgent/internal/plugin/cabi"
|
||||
)
|
||||
|
||||
// .so 插件必须导出函数 NewPlugin,签名与 NativeFactory 一致:
|
||||
@ -50,15 +53,86 @@ func readManifest(dir string) *PluginManifest {
|
||||
return &m
|
||||
}
|
||||
|
||||
// tryLoadSO 尝试从插件目录加载 plugin.so(Go plugin -buildmode=plugin)。
|
||||
// 返回 nil,nil 表示目录中没有 plugin.so。
|
||||
// cabiPlugin wraps a C ABI loaded plugin (.so via -buildmode=c-shared).
|
||||
type cabiPlugin struct {
|
||||
name string
|
||||
handle *cabi.Handle
|
||||
}
|
||||
|
||||
func (p *cabiPlugin) Name() string { return p.name }
|
||||
func (p *cabiPlugin) Start(s *sdk.PluginSDK) error {
|
||||
// Build CoreAPI from the provided PluginSDK and pass to plugin
|
||||
corePtr := buildCoreAPI(s, p.name)
|
||||
if err := p.handle.Start(corePtr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Discover tools/stages/channels registered by the plugin during Start
|
||||
defs, _ := p.handle.GetToolDefs()
|
||||
for _, d := range defs {
|
||||
var td pubsdk.ToolDef
|
||||
if err := json.Unmarshal(d, &td); err != nil {
|
||||
continue
|
||||
}
|
||||
toolName := td.Name
|
||||
td.Plugin = p.name
|
||||
s.RegisterTool(toolName, sdk.ToolDef{
|
||||
Name: toolName,
|
||||
Description: td.Description,
|
||||
Parameters: td.Parameters,
|
||||
Plugin: p.name,
|
||||
}, makeCABIHandler(p.handle, toolName))
|
||||
}
|
||||
|
||||
stages, _ := p.handle.GetStages()
|
||||
for _, stage := range stages {
|
||||
st := sdk.Stage(stage)
|
||||
s.RegisterStage(st, func(sc *sdk.StageContext) error {
|
||||
ctxJSON, _ := json.Marshal(map[string]interface{}{
|
||||
"raw_message": sc.RawMessage,
|
||||
"user_id": sc.UserID,
|
||||
"phase": string(sc.Phase),
|
||||
})
|
||||
return p.handle.InvokeStage(stage, string(ctxJSON))
|
||||
})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *cabiPlugin) Stop() error {
|
||||
p.handle.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func makeCABIHandler(handle *cabi.Handle, toolName string) sdk.ToolHandler {
|
||||
return func(args map[string]interface{}) (interface{}, error) {
|
||||
return handle.InvokeTool(toolName, args)
|
||||
}
|
||||
}
|
||||
|
||||
// buildCoreAPI creates a C-compatible CoreAPI function table from a PluginSDK.
|
||||
// Returns an unsafe.Pointer to a C-allocated struct.
|
||||
// TODO: implement CoreAPI dispatch that calls back into the Go PluginSDK
|
||||
func buildCoreAPI(s *sdk.PluginSDK, pluginName string) unsafe.Pointer {
|
||||
return unsafe.Pointer(nil) // placeholder - will be implemented in core dispatch
|
||||
}
|
||||
|
||||
// tryLoadSO 尝试从插件目录加载 plugin.so。
|
||||
// 优先尝试 C ABI 加载(-buildmode=c-shared),失败时回退到 Go plugin.Open。
|
||||
func tryLoadSO(dir, name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||
soPath := filepath.Join(dir, soEntry)
|
||||
if _, err := os.Stat(soPath); os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 复制到临时路径以绕过 Go plugin.Open 的路径缓存
|
||||
// Try C ABI first
|
||||
handle, err := cabi.Load(soPath, name, config)
|
||||
if err == nil {
|
||||
return &cabiPlugin{name: name, handle: handle}, nil
|
||||
}
|
||||
|
||||
// Fall back to Go plugin.Open
|
||||
data, err := os.ReadFile(soPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", soPath, err)
|
||||
@ -87,14 +161,7 @@ func tryLoadSO(dir, name string, config map[string]interface{}) (sdk.Plugin, err
|
||||
return nil, fmt.Errorf("NewPlugin in %s is not a function (type=%T)", soPath, sym)
|
||||
}
|
||||
if rv.Type().NumIn() != 2 || rv.Type().NumOut() != 2 {
|
||||
return nil, fmt.Errorf("NewPlugin in %s has wrong arity: type=%s in=%d out=%d", soPath, rv.Type().String(), rv.Type().NumIn(), rv.Type().NumOut())
|
||||
}
|
||||
arg0 := rv.Type().In(0)
|
||||
arg1 := rv.Type().In(1)
|
||||
out0 := rv.Type().Out(0)
|
||||
out1 := rv.Type().Out(1)
|
||||
if arg0.Kind() != reflect.String || arg1.Kind() != reflect.Map || out1.String() != "error" {
|
||||
return nil, fmt.Errorf("NewPlugin in %s signature mismatch: type=%s arg0=%s arg1=%s out0=%s out1=%s", soPath, rv.Type().String(), arg0.String(), arg1.String(), out0.String(), out1.String())
|
||||
return nil, fmt.Errorf("NewPlugin in %s has wrong arity", soPath)
|
||||
}
|
||||
outs := rv.Call([]reflect.Value{reflect.ValueOf(name), reflect.ValueOf(config)})
|
||||
if len(outs) != 2 {
|
||||
@ -108,7 +175,7 @@ func tryLoadSO(dir, name string, config map[string]interface{}) (sdk.Plugin, err
|
||||
}
|
||||
plg, ok := outs[0].Interface().(pubsdk.Plugin)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("NewPlugin in %s returned value that does not implement pubsdk.Plugin", soPath)
|
||||
return nil, fmt.Errorf("NewPlugin in %s does not implement pubsdk.Plugin", soPath)
|
||||
}
|
||||
|
||||
return &dynamicPlugin{name: name, impl: plg}, nil
|
||||
|
||||
Reference in New Issue
Block a user