An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Fix kernel plugin related issues (#17670)
Yingyi / 颖逸c4ae1d44e5b1
diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex 68018a2bfe..e744dfe94e 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -156,6 +156,18 @@ func setBazaar(c *gin.Context) {return}+ if bazaar.PetalDisabled || !bazaar.Trust {+ // disable all kernel plugins+ if model.OnKernelPluginsStop != nil {+ model.OnKernelPluginsStop()+ }+ } else {+ // enable all kernel plugins+ if model.OnKernelPluginsStart != nil {+ model.OnKernelPluginsStart()+ }+ }+model.Conf.Bazaar = bazaarmodel.Conf.Save()diff --git a/kernel/go.mod b/kernel/go.modindex 197a6b6781..49ac2fbe21 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -34,7 +34,7 @@ require (github.com/gabriel-vasile/mimetype v1.4.12github.com/gin-contrib/gzip v1.2.3github.com/gin-contrib/sessions v1.0.4- github.com/gin-contrib/sse v1.1.0+ github.com/gin-contrib/sse v1.1.1github.com/gin-gonic/gin v1.11.0github.com/go-ole/go-ole v1.3.0github.com/gofrs/flock v0.13.0diff --git a/kernel/go.sum b/kernel/go.sumindex b792f198b4..25c5884e19 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -172,8 +172,8 @@ github.com/gin-contrib/gzip v1.2.3 h1:dAhT722RuEG330ce2agAs75z7yB+NKvX/ZM1r8w0u2github.com/gin-contrib/gzip v1.2.3/go.mod h1:ad72i4Bzmaypk8M762gNXa2wkxxjbz0icRNnuLJ9a/c=github.com/gin-contrib/sessions v1.0.4 h1:ha6CNdpYiTOK/hTp05miJLbpTSNfOnFg5Jm2kbcqy8U=github.com/gin-contrib/sessions v1.0.4/go.mod h1:ccmkrb2z6iU2osiAHZG3x3J4suJK+OU27oqzlWOqQgs=-github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=-github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=+github.com/gin-contrib/sse v1.1.1 h1:uGYpNwTacv5R68bSGMapo62iLTRa9l5zxGCps4hK6ko=+github.com/gin-contrib/sse v1.1.1/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.goindex ae83933567..eadadef9fd 100644--- a/kernel/model/bazaar.go+++ b/kernel/model/bazaar.go@@ -337,9 +337,10 @@ func InstallBazaarPackage(pkgType, repoURL, repoHash, packageName string, themeMcase "plugins":if update {// 已启用的插件更新之后需要重载- petals := getPetals()- petal := getPetalByName(packageName, petals)+ petal := GetPetalByName(packageName)if nil != petal && petal.Enabled {+ // reload kernel plugin+ SetPetalEnabled(petal.Name, petal.Enabled)reloadPluginSet := hashset.New(packageName)PushReloadPlugin(nil, nil, reloadPluginSet, nil, "")}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex e2a3cf5995..121513502a 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -747,8 +747,8 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int) {if !force {// Stop kernel plugins early in shutdown- if OnKernelPluginShutdown != nil {- OnKernelPluginShutdown()+ if OnKernelPluginsStop != nil {+ OnKernelPluginsStop()}if Conf.Sync.Enabled && 3 != Conf.Sync.Mode &&diff --git a/kernel/model/plugin.go b/kernel/model/plugin.goindex c1160a98f1..05a35dc509 100644--- a/kernel/model/plugin.go+++ b/kernel/model/plugin.go@@ -55,9 +55,10 @@ type KernelPetal struct {}var (- OnKernelPluginStart func(petal *Petal) // Called when a plugin is enabled (after loading and starting the plugin)- OnKernelPluginStop func(petal *Petal) // Called when a plugin is disabled (before stopping and unloading the plugin)- OnKernelPluginShutdown func() // Called when SiYuan is shutting down, before stopping all plugins+ OnKernelPluginStart func(petal *Petal) // Called when a plugin is enabled (after loading and starting the plugin)+ OnKernelPluginStop func(petal *Petal) // Called when a plugin is disabled (before stopping and unloading the plugin)+ OnKernelPluginsStart func() // Called to start all valid plugins+ OnKernelPluginsStop func() // Called to stopping all valid plugins)func SetPetalEnabled(name string, enabled bool) (ret *Petal, err error) {@@ -119,6 +120,11 @@ func getPetalByName(name string, petals []*Petal) (ret *Petal) {return}+func GetPetalByName(name string) (ret *Petal) {+ petals := getPetals()+ return getPetalByName(name, petals)+}+var loadPetalsFlight singleflight.Group// IsPetalsEnabled returns whether petals are enabled and trusted to be loadeddiff --git a/kernel/plugin/api_storage.go b/kernel/plugin/api_storage.goindex 9927b24baf..9bec63a3ec 100644--- a/kernel/plugin/api_storage.go+++ b/kernel/plugin/api_storage.go@@ -37,16 +37,106 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err}}()- baseDir := filepath.Join(util.DataDir, "storage", "petal", p.Name)-resolvePath := func(relPath string) (abs string, err error) {- abs = filepath.Join(baseDir, filepath.Clean(relPath))- if !(abs == baseDir || strings.HasPrefix(abs, baseDir+string(filepath.Separator))) {+ abs = filepath.Join(p.storageDir, filepath.Clean(relPath))+ if !(abs == p.storageDir || strings.HasPrefix(abs, p.storageDir+string(filepath.Separator))) {err = fmt.Errorf("siyuan.storage: path traversal not allowed")}return}+ watcher := rt.NewObject()++ // siyuan.storage.watcher.add(path) -> Promise<void>+ lo.Must0(watcher.Set("add", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {+ promise, resolve, reject := rt.NewPromise()++ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ var path string+ if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ err = fmt.Errorf("path required")+ return+ }++ abs, resolveErr := resolvePath(path)+ if resolveErr != nil {+ err = resolveErr+ return+ }++ addErr := p.addStorageWatch(abs)+ if addErr != nil {+ err = fmt.Errorf("failed to add storage path to watcher: %v", addErr)+ return+ }++ return+ }, func(rt *goja.Runtime, result any, err error) {+ if lo.IsNil(err) {+ if resolveErr := resolve(result); resolveErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.storage.watcher.add resolve: %v", p.Name, resolveErr)+ }+ } else {+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.storage.watcher.add reject: %v", p.Name, rejectErr)+ }+ }+ })+ if runErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.storage.watcher.add worker run: %v", p.Name, runErr)+ }++ return rt.ToValue(promise)+ })))++ // siyuan.storage.watcher.remove(path) -> void+ lo.Must0(watcher.Set("remove", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {+ promise, resolve, reject := rt.NewPromise()++ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ var path string+ if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ err = fmt.Errorf("path required")+ return+ }++ abs, resolveErr := resolvePath(path)+ if resolveErr != nil {+ err = resolveErr+ return+ }++ addErr := p.removeStorageWatch(abs)+ if addErr != nil {+ err = fmt.Errorf("failed to remove storage path from watcher: %v", addErr)+ return+ }++ return+ }, func(rt *goja.Runtime, result any, err error) {+ if lo.IsNil(err) {+ if resolveErr := resolve(result); resolveErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.storage.watcher.remove resolve: %v", p.Name, resolveErr)+ }+ } else {+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.storage.watcher.remove reject: %v", p.Name, rejectErr)+ }+ }+ })+ if runErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.storage.watcher.remove worker run: %v", p.Name, runErr)+ }++ return rt.ToValue(promise)+ })))++ lo.Must0(ObjectFreeze(rt, watcher))+storage := rt.NewObject()// siyuan.storage.get(path) -> Promise<{text, json, arrayBuffer}>@@ -127,6 +217,11 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errpromise, resolve, reject := rt.NewPromise()runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if util.ReadOnly {+ err = fmt.Errorf("The current kernel is in read-only mode, storage.put is not allowed")+ return+ }+if len(call.Arguments) < 2 {err = fmt.Errorf("path and content required")return@@ -190,6 +285,11 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errpromise, resolve, reject := rt.NewPromise()runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if util.ReadOnly {+ err = fmt.Errorf("The current kernel is in read-only mode, storage.remove is not allowed")+ return+ }+if len(call.Arguments) < 1 {err = fmt.Errorf("path required")return@@ -200,7 +300,7 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errerr = resolveErrreturn}- if abs == baseDir {+ if abs == p.storageDir {err = fmt.Errorf("cannot remove storage root")return}@@ -321,6 +421,9 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errreturn rt.ToValue(promise)})))+ // siyuan.storage.watcher+ lo.Must0(storage.Set("watcher", watcher))+lo.Must0(ObjectFreeze(rt, storage))lo.Must0(siyuan.Set("storage", storage))diff --git a/kernel/plugin/manager.go b/kernel/plugin/manager.goindex 7e657afd45..e04ffe5349 100644--- a/kernel/plugin/manager.go+++ b/kernel/plugin/manager.go@@ -17,20 +17,37 @@package pluginimport (+ "context"+ "path/filepath""sync""sync/atomic"+ "github.com/fsnotify/fsnotify""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type PluginManagerState int64++const (+ PluginManagerStateStopped PluginManagerState = iota+ PluginManagerStateRunning)// PluginManager discovers, loads, starts, and stops kernel plugins.type PluginManager struct {- lifecycleMu sync.Mutex // protects the lifecycle state of the manager (starting/stopping), allowing concurrent start/stop of different plugins while preventing concurrent start/stop of the entire manager+ state PluginManagerState // protected by lifecycleMu+ lifecycleMu sync.RWMutex // protects the lifecycle state of the manager (starting/stopping), allowing concurrent start/stop of different plugins while preventing concurrent start/stop of the entire manager++ pluginsDir string // base directory for plugins (e.g. /path/to/workspace/data/plugins)- plugins sync.Map // map[string]*KernelPlugin+ context context.Context // Context for managing plugin manager lifecycle+ watcher *fsnotify.Watcher // watcher for kernel plugin source file changes, to trigger hot reload++ plugins sync.Map // map[string]*KernelPlugin+ pluginsMu sync.Map // map[string]*sync.Mutex, one per plugin name, to serialize start/stop of the same plugin while allowing concurrent start/stop of different plugins- pluginMu sync.Map // map[string]*sync.Mutex, one per plugin name, to serialize start/stop of the same plugin while allowing concurrent start/stop of different plugins}type PluginInfo struct {@@ -50,7 +67,9 @@ func InitManager() {model.OnKernelPluginStart = func(petal *model.Petal) { GetManager().StartPlugin(petal) }model.OnKernelPluginStop = func(petal *model.Petal) { GetManager().StopPlugin(petal) }- model.OnKernelPluginShutdown = func() { GetManager().Stop() }++ model.OnKernelPluginsStart = func() { GetManager().Start() }+ model.OnKernelPluginsStop = func() { GetManager().Stop() }m.Start()}@@ -58,11 +77,64 @@ func InitManager() {// GetManager returns the singleton PluginManager.func GetManager() *PluginManager {managerOnce.Do(func() {- manager = &PluginManager{}+ context := context.Background()++ watcher, err := fsnotify.NewWatcher()+ if err != nil {+ logging.LogErrorf("failed to create kernel plugin source file watcher: %s", err)+ } else if watcher != nil {+ go func() {+ defer watcher.Close()++ for {+ select {+ case <-context.Done():+ return+ case event, ok := <-watcher.Events:+ if !ok {+ return+ }++ pluginDir, fileName := filepath.Split(event.Name)+ pluginName := filepath.Base(pluginDir)+ if fileName == "kernel.js" {+ switch event.Op {+ case fsnotify.Create, fsnotify.Write:+ petal := model.GetPetalByName(pluginName)+ if petal != nil && petal.Enabled {+ logging.LogInfof("[plugin:%s] source file kernel.js changed, reloading plugin", petal.Name)+ go model.SetPetalEnabled(petal.Name, petal.Enabled)+ }+ }+ }+ case err, ok := <-watcher.Errors:+ if !ok {+ return+ }+ logging.LogErrorf("kernel plugin source file watcher error: %s", err)+ }+ }+ }()+ }++ manager = &PluginManager{+ state: PluginManagerStateStopped,++ pluginsDir: filepath.Join(util.DataDir, "plugins"),++ context: context,+ watcher: watcher,+ }})return manager}+func (m *PluginManager) State() PluginManagerState {+ m.lifecycleMu.RLock()+ defer m.lifecycleMu.RUnlock()+ return m.state+}+// Start loads and starts all kernel-eligible plugins.// Called from main.go after model initialization.func (m *PluginManager) Start() {@@ -72,6 +144,16 @@ func (m *PluginManager) Start() {}}()+ if m.State() == PluginManagerStateRunning {+ logging.LogInfof("kernel plugin manager is already running, skipping start")+ return+ }++ if model.Conf.Bazaar.PetalDisabled || !model.Conf.Bazaar.Trust {+ logging.LogInfof("kernel plugins are disabled by configuration, skipping start")+ return+ }+m.lifecycleMu.Lock()defer m.lifecycleMu.Unlock()@@ -92,6 +174,7 @@ func (m *PluginManager) Start() {}wg.Wait()+ m.state = PluginManagerStateRunninglogging.LogInfof("kernel plugin manager started, %d/%d plugin(s) loaded", counter, all)}@@ -104,6 +187,11 @@ func (m *PluginManager) Stop() {}}()+ if m.State() == PluginManagerStateStopped {+ logging.LogInfof("kernel plugin manager is already stopped, skipping stop")+ return+ }+m.lifecycleMu.Lock()defer m.lifecycleMu.Unlock()@@ -115,20 +203,18 @@ func (m *PluginManager) Stop() {wg := sync.WaitGroup{}m.plugins.Range(func(key, value any) bool {atomic.AddInt64(&all, 1)- p := value.(*KernelPlugin)- wg.Go(func() {- ok, err := p.stop()- if err != nil {- logging.LogErrorf("[plugin:%s] stop failed: %s", p.Name, err)- }- if ok {- atomic.AddInt64(&counter, 1)- }- })+ if p, ok := value.(*KernelPlugin); ok {+ wg.Go(func() {+ if ok := m.StopPlugin(p.Petal); ok {+ atomic.AddInt64(&counter, 1)+ }+ })+ }return true})wg.Wait()+ m.state = PluginManagerStateStoppedlogging.LogInfof("kernel plugin manager stopped, %d/%d plugin(s) unloaded", counter, all)}@@ -142,18 +228,25 @@ func (m *PluginManager) StartPlugin(petal *model.Petal) (ok bool) {}}()+ if model.Conf.Bazaar.PetalDisabled || !model.Conf.Bazaar.Trust {+ ok = false+ return+ }+if petal.Kernel.Incompatible || !petal.Kernel.Existed {ok = falsereturn}+ m.StopPlugin(petal) // stop first in case it's already running, to allow hot reload+pluginMu := m.getPluginMu(petal.Name)pluginMu.Lock()defer pluginMu.Unlock()- m.stopPlugin(petal)+ m.addPluginSourceWatch(petal.Name)- p := NewKernelPlugin(petal)+ p := NewKernelPlugin(m.context, petal)m.plugins.Store(p.Name, p)@@ -169,10 +262,11 @@ func (m *PluginManager) StartPlugin(petal *model.Petal) (ok bool) {// StopPlugin stops a single kernel plugin.// Called when a petal is disabled via SetPetalEnabled.-func (m *PluginManager) StopPlugin(petal *model.Petal) {+func (m *PluginManager) StopPlugin(petal *model.Petal) (ok bool) {defer func() {if r := recover(); r != nil {logging.LogErrorf("[plugin:%s] panic during stop: %v", petal.Name, r)+ ok = false}}()@@ -180,25 +274,27 @@ func (m *PluginManager) StopPlugin(petal *model.Petal) {pluginMu.Lock()defer pluginMu.Unlock()- m.stopPlugin(petal)-}+ m.removePluginSourceWatch(petal.Name)-// stopPlugin removes and stops the plugin without acquiring the per-plugin mutex.-// Callers must hold the per-plugin mutex returned by getPluginMu.-func (m *PluginManager) stopPlugin(petal *model.Petal) {value, loaded := m.plugins.LoadAndDelete(petal.Name)if loaded {p := value.(*KernelPlugin)- if _, err := p.stop(); err != nil {+ if success, err := p.stop(); err != nil {logging.LogErrorf("[plugin:%s] stop failed: %s", p.Name, err)+ ok = false+ } else {+ ok = success}+ } else {+ ok = false}+ return}// getPluginMu returns the per-plugin mutex for the given name, creating it if needed.func (m *PluginManager) getPluginMu(name string) *sync.Mutex {- v, _ := m.pluginMu.LoadOrStore(name, &sync.Mutex{})+ v, _ := m.pluginsMu.LoadOrStore(name, &sync.Mutex{})return v.(*sync.Mutex)}@@ -213,9 +309,8 @@ func (m *PluginManager) GetPlugin(name string) *KernelPlugin {// GetLoadedPlugin returns the plugin info for a loaded KernelPlugin by name, or nil.func (m *PluginManager) GetLoadedPlugin(name string) (plugin *PluginInfo, found bool) {- value, loaded := m.plugins.Load(name)- if loaded {- p := value.(*KernelPlugin)+ p := m.GetPlugin(name)+ if p != nil {return &PluginInfo{Name: p.Name,State: p.State().String(),@@ -238,3 +333,25 @@ func (m *PluginManager) GetLoadedPluginsInfo() (plugins []*PluginInfo) {})return plugins}++// addPluginSourceWatch adds the plugin's base directory to the fsnotify watcher to watch for source file changes for hot reload.+func (m *PluginManager) addPluginSourceWatch(name string) {+ if m.watcher == nil {+ return+ }+ path := filepath.Join(m.pluginsDir, name)+ if err := m.watcher.Add(path); err != nil {+ logging.LogErrorf("failed to add kernel plugin source path [%s] to watcher: %s", path, err)+ }+}++// removePluginSourceWatch removes the plugin's base directory from the fsnotify watcher when the plugin is stopped.+func (m *PluginManager) removePluginSourceWatch(name string) {+ if m.watcher == nil {+ return+ }+ path := filepath.Join(m.pluginsDir, name)+ if err := m.watcher.Remove(path); err != nil {+ logging.LogErrorf("failed to remove kernel plugin source path [%s] from watcher: %s", path, err)+ }+}diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.goindex e002b9dc68..88175b13cd 100644--- a/kernel/plugin/plugin.go+++ b/kernel/plugin/plugin.go@@ -28,6 +28,8 @@ import ("github.com/asaskevich/EventBus""github.com/dop251/goja""github.com/dop251/goja_nodejs/eventloop"+ "github.com/fsnotify/fsnotify"+ "github.com/gin-contrib/sse""github.com/gin-gonic/gin""github.com/google/uuid""github.com/lxzan/gws"@@ -95,8 +97,12 @@ type KernelPlugin struct {token string // JWT for this pluginfile string // kernel.js file path named in js runtime (e.g. "plugin-name/kernel.js")+ pluginDir string // Base directory for this plugin (e.g. /path/to/workspace/data/plugins/plugin-name)+ storageDir string // Base directory for this plugin's storage (e.g. /path/to/workspace/data/storage/petal/plugin-name)+worker Worker // Worker for serializing plugin js-call-go (e.g. logger) and go-call-js (e.g. RPC calls) tasks on a single goroutineruntime *eventloop.EventLoop // goja event loop runtime for this plugin+ watcher *fsnotify.Watcher // watcher for kernel plugin storage file changesstate atomic.Int64 // PluginState@@ -111,17 +117,32 @@ type KernelPlugin struct {sockets map[*gws.Conn]bool // tracked gws WebSocket connections (true: RPC server, false: regular)}-func NewKernelPlugin(petal *model.Petal) *KernelPlugin {+func NewKernelPlugin(ctx context.Context, petal *model.Petal) *KernelPlugin {token, err := model.CreatePluginJWT(petal.Name)if err != nil {logging.LogErrorf("Failed to create plugin JWT for [%s]: %v", petal.Name, err)}+ context, cancel := context.WithCancel(ctx)++ watcher, err := fsnotify.NewWatcher()+ if err != nil {+ logging.LogErrorf("[plugin:%s] failed to create storage watcher: %s", petal.Name, err)+ }+plugin := &KernelPlugin{Petal: petal,token: token,file: fmt.Sprintf("%s/kernel.js", petal.Name),+ pluginDir: filepath.Join(util.DataDir, "plugins", petal.Name),+ storageDir: filepath.Join(util.DataDir, "storage", "petal", petal.Name),++ watcher: watcher,++ context: context,+ cancel: cancel,+bus: EventBus.New(),sockets: make(map[*gws.Conn]bool),@@ -131,6 +152,15 @@ func NewKernelPlugin(petal *model.Petal) *KernelPlugin {return plugin}+// createEventMessage creates a standardized event message with a unique ID, type, and detail payload.+func createEventMessage(eventType string, detail any) R {+ return R{+ "id": uuid.NewString(),+ "type": eventType,+ "detail": detail,+ }+}+// State returns the current plugin state (safe for concurrent reads).func (p *KernelPlugin) State() PluginState {return PluginState(p.state.Load())@@ -209,7 +239,6 @@ func (p *KernelPlugin) start() (err error) {}()p.state.Store(int64(PluginStateLoading))- p.context, p.cancel = context.WithCancel(context.Background())baseDir := filepath.Join(util.DataDir, "storage", "petal", p.Name)if err := os.MkdirAll(baseDir, 0755); err != nil {@@ -226,16 +255,15 @@ func (p *KernelPlugin) start() (err error) {return fmt.Errorf("subscribe plugin events: %v", subscribeErr)}+ go p.startStorageWatch()+p.onLoad()p.state.Store(int64(PluginStateLoaded))p.onLoaded()p.state.Store(int64(PluginStateRunning))p.onRunning()- p.bus.Publish(EventBusTopicRuntime, R{- "id": uuid.NewString(),- "type": "start",- })+ p.bus.Publish(EventBusTopicRuntime, createEventMessage("start", nil))logging.LogDebugf("[plugin:%s] started", p.Name)return@@ -256,10 +284,7 @@ func (p *KernelPlugin) stop() (ok bool, err error) {return}- p.bus.Publish(EventBusTopicRuntime, R{- "id": uuid.NewString(),- "type": "stop",- })+ p.bus.Publish(EventBusTopicRuntime, createEventMessage("stop", nil))p.state.Store(int64(PluginStateStopping))@@ -609,6 +634,66 @@ func (p *KernelPlugin) UntrackRpcSocket(conn *gws.Conn) {delete(p.sockets, conn)}+// startStorageWatch starts a goroutine to watch for file changes in the plugin's storage directory and dispatches events to the plugin.+func (p *KernelPlugin) startStorageWatch() {+ if p.watcher == nil {+ return+ }++ defer p.watcher.Close()++ for {+ select {+ case <-p.context.Done():+ return+ case event, ok := <-p.watcher.Events:+ if !ok {+ return+ }++ switch event.Op {+ case fsnotify.Create, fsnotify.Write, fsnotify.Rename, fsnotify.Remove:+ path, relErr := filepath.Rel(p.storageDir, event.Name)+ if relErr != nil {+ logging.LogErrorf("[plugin:%s] failed to get relative storage path for [%s]: %v", p.Name, event.Name, relErr)+ return+ }+ p.bus.Publish(EventBusTopicRuntime, createEventMessage("fs-notify", R{+ "operation": event.Op.String(),+ "path": path,+ }))+ }+ case err, ok := <-p.watcher.Errors:+ if !ok {+ return+ }+ logging.LogErrorf("[plugin:%s] storage watcher error: %s", p.Name, err)+ }+ }+}++// addStorageWatch adds a path to the fsnotify watcher to watch for storage file/directory changes.+func (p *KernelPlugin) addStorageWatch(path string) (err error) {+ if p.watcher == nil {+ err = fmt.Errorf("fsnotify watcher not initialized")+ return+ }++ err = p.watcher.Add(path)+ return+}++// removeStorageWatch removes a path from the fsnotify watcher to stop watching for storage file/directory changes.+func (p *KernelPlugin) removeStorageWatch(path string) (err error) {+ if p.watcher == nil {+ err = fmt.Errorf("fsnotify watcher not initialized")+ return+ }++ err = p.watcher.Remove(path)+ return+}+// invokeHook calls a lifecycle hook (e.g. onload) if it exists, awaiting if it returns a Promise.func (p *KernelPlugin) invokeHook(name string) {var err error@@ -1092,11 +1177,6 @@ func (p *KernelPlugin) handleWebSocketRequest(c *gin.Context, request *Request,// handleServerSentEventRequest dispatches an SSE request to the plugin's JS handler and streams events until completion or client disconnect.func (p *KernelPlugin) handleServerSentEventRequest(c *gin.Context, request *Request, scope AccessScope) (err error) {- type sseEvent struct {- name string- message any- }-ctx, cancel := context.WithCancel(p.context)var closeOnce sync.Once@@ -1107,7 +1187,7 @@ func (p *KernelPlugin) handleServerSentEventRequest(c *gin.Context, request *Req}defer doClose()- events := chanx.NewUnboundedChan[sseEvent](ctx, 16)+ events := chanx.NewUnboundedChan[sse.Event](ctx, 16)done := make(chan error, 1) // using to receive handler error or close signalrunErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {@@ -1141,10 +1221,33 @@ func (p *KernelPlugin) handleServerSentEventRequest(c *gin.Context, request *Req}port_send := rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {- name := call.Argument(0).String()- message := call.Argument(1).Export()- events.In <- sseEvent{name, message}- return goja.Undefined()+ if eventJs := call.Argument(0); isJsValueNotNull(eventJs) {+ if eventObj := eventJs.ToObject(rt); eventObj != nil {+ e := sse.Event{}++ if data := eventObj.Get("data"); isJsValueNotUndefined(data) {+ e.Data = data.Export()+ } else {+ panic(rt.NewGoError(fmt.Errorf("event.data is required")))+ }++ if event := eventObj.Get("event"); goja.IsString(event) {+ e.Event = event.String()+ }++ if id := eventObj.Get("id"); goja.IsString(id) {+ e.Id = id.String()+ }++ if retry := eventObj.Get("retry"); goja.IsNumber(retry) {+ e.Retry = uint(retry.ToInteger())+ }++ events.In <- e+ return goja.Undefined()+ }+ }+ panic(rt.NewGoError(fmt.Errorf("invalid event object")))})port_close := rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {@@ -1216,7 +1319,8 @@ func (p *KernelPlugin) handleServerSentEventRequest(c *gin.Context, request *Reqfor {select {case e := <-events.Out:- c.SSEvent(e.name, e.message)+ // c.SSEvent(e.Event, e.Data)+ c.Render(-1, e)c.Writer.Flush()case <-ctx.Done():return