Files
dify-plugin-daemon/cmd/commandline/plugin/module.go
T
Yeuoly 888ad788bc refactor: plugin lifecycle control panel (#499)
* refactor: introduce local plugin control panel and cleanup environment setup process

* fix: args

* refactor: new local runtime

* temp: stash work for refactor on RemotePluginServer

* refactor: unify local runtime lifetime and sperate init environment process

* chore: add missing files

* stash

* refactor: local plugin lifetime control

* refactor: complete installation process of control panel

* refactor: adapt service layer to new controlpanel

* refactor: pluginManager.Install

* fix: add routine wrap to InstallServerless, avoid blocking main thread

* feat: reinstall serverless runtime

* chore: add comments to Reinstall and update confusing naming

* refactor: unify install plugin service

* refactor: add labels to debugging runtime

* refactor: add getters to plugin manager

* refactor: split install service to decode/install_task/install service

* ???

* refactor: adapt controllers

* refactor: session write

* refactor: session runtime

* Refine install task orchestration (#501)

* refactor: installing task

* refactor cluster management, decouple lifetime management and cluster

* fix cli test command

* fix: cleanup TODO comments and implement GracefulStop for instance

* feat: add logger to control panel

* fix: multiple nil references

* refactor: better lifetime control

* refactor: better cycle interval

* fix(LocalPluginRuntime): prevent returning err when it's not  error

* fix: avoid adding empty PipExtraArgs

* fix: missing errors in Environment init

* fix: add truncateMessage to avoid db explosion

* cleanup: better lifecycle management

* fix: init status at the beginning of installation

* optimize: GracefulStop for pluginInstance

* refactor: tests

* refactor: centralize routine labels (#504)

* cleanup: RoutineKey

* fix: init routine pool

* fix: correctly handle cluster register error

* fix: memory leak

* fix: add \n to instance write

* fix(installer.go): set success to true after succeed for defer func

* refactor

* fix: missing cwd in testutils

* fix: scaleup default runtime nums to 1 when testing

* fix: localruntime appconfig in testing module

* Update internal/core/local_runtime/load_balancing.go

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* fix: more efficiency implement in installer_local.go

* fix: returns after failing in onDebuggingRuntimeDisconnected

* fix: returns after failing in onDebuggingRuntimeDisconnected

* fix: splits tests

* refactor: naming

* refactor: manifest.VersionX

* fix: adapt SetDefault to tests

* fix: enforce use constants in DBType

* fix: generate

* fix: linter

* cleanup tests

* refactor: change  package to

* cleanup: useless codes

* Update internal/cluster/plugin.go

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* cleanup

* refactor: decouple connection_key management from debugging_time

* refactor: confused naming

* feat: recycle resources to adapt to https://github.com/langgenius/dify-plugin-daemon/pull/500

* refactor: confusing redirecting

* fix: support get serverless runtime

* fix: race condition in Launching

* fix: avoid ManifestValidate in first step of debugging handshake

* fix: adding ReleaseAllLocks to finalizers

* wtf: what a beautiful code

* refactor: rename Stream.Async to Stream.Process

* fix: kill process if daed instance was detected

* fix: correctly handle failures

* fix: consistence of difference interfaces

* fix: add stacktrace to panic

* fix: only trigger once  event

* fix: ensure plugin runtime was shutdown

* feat: cleanup install tasks

* fix: add scale logs

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-11-18 17:28:02 +08:00

332 lines
8.3 KiB
Go

package plugin
import (
"fmt"
"html/template"
"os"
"path/filepath"
"github.com/langgenius/dify-plugin-daemon/pkg/entities/constants"
"github.com/langgenius/dify-plugin-daemon/pkg/plugin_packager/decoder"
"github.com/langgenius/dify-plugin-daemon/pkg/utils/log"
)
const TOOL_MODULE_TEMPLATE = `
========== {{.Identity.Name}} ==========
Author: {{.Identity.Author}}
Label: {{.Identity.Label.EnUS}}
Description: {{.Description.Human.EnUS}}
Parameters:
{{- range .Parameters}}
- Name: {{.Name}}
Type: {{.Type}}
Required: {{.Required}}
Description: {{.HumanDescription.EnUS}}
{{- if .Default}}
Default: {{.Default}}
{{- end}}
{{- if .Options}}
Options:
{{- range .Options}}
- Value: {{.Value}}
Label: {{.Label.EnUS}}
{{- end}}
{{- end}}
{{- end}}
`
const AGENT_MODULE_TEMPLATE = `
========== {{.Identity.Name}} ==========
Author: {{.Identity.Author}}
Label: {{.Identity.Label.EnUS}}
Description: {{.Description.EnUS}}
Parameters:
{{- range .Parameters}}
- Name: {{.Name}}
Type: {{.Type}}
Required: {{.Required}}
{{- if .Default}}
Default: {{.Default}}
{{- end}}
{{- end}}
`
const MODEL_MODULE_TEMPLATE = `
========== {{.Model}} ==========
Name: {{.Model}}
Type: {{.ModelType}}
Label: {{.Label.EnUS}}
Parameters:
{{- range .ParameterRules}}
- Name: {{.Name}}
Type: {{.Type}}
Required: {{.Required}}
Description: {{.Help.EnUS}}
{{- if .Default}}
Default: {{.Default}}
{{- end}}
{{- if .Min}}
Min: {{.Min}}
{{- end}}
{{- if .Max}}
Max: {{.Max}}
{{- end}}
{{- if .Options}}
Options: {{range .Options}}{{.}}, {{end}}
{{- end}}
{{- end}}
`
const ENDPOINT_MODULE_TEMPLATE = `
========== Endpoints ==========
Path: {{.Path}}
Method: {{.Method}}
`
const PLUGIN_MODULE_TEMPLATE = `
========== Plugin ==========
Name: {{.Name}}
Version: {{.Version}}
Description: {{.Description.EnUS}}
Author: {{.Author}}
Icon: {{.Icon}}
Tags: {{range .Tags}}{{.}}, {{end}}
Category: {{.Category}}
Resource:
Memory: {{.Resource.Memory}} bytes
Permissions:
{{- if .Resource.Permission.Tool}}
Tool: {{.Resource.Permission.Tool.Enabled}}
{{- end}}
{{- if .Resource.Permission.Model}}
Model:
Enabled: {{.Resource.Permission.Model.Enabled}}
LLM: {{.Resource.Permission.Model.LLM}}
TextEmbedding: {{.Resource.Permission.Model.TextEmbedding}}
Rerank: {{.Resource.Permission.Model.Rerank}}
TTS: {{.Resource.Permission.Model.TTS}}
Speech2text: {{.Resource.Permission.Model.Speech2text}}
Moderation: {{.Resource.Permission.Model.Moderation}}
{{- end}}
{{- if .Resource.Permission.Node}}
Node: {{.Resource.Permission.Node.Enabled}}
{{- end}}
{{- if .Resource.Permission.Endpoint}}
Endpoint: {{.Resource.Permission.Endpoint.Enabled}}
{{- end}}
{{- if .Resource.Permission.App}}
App: {{.Resource.Permission.App.Enabled}}
{{- end}}
{{- if .Resource.Permission.Storage}}
Storage:
Enabled: {{.Resource.Permission.Storage.Enabled}}
Size: {{.Resource.Permission.Storage.Size}} bytes
{{- end}}
`
func ModuleList(pluginPath string) {
var pluginDecoder decoder.PluginDecoder
var err error
stat, err := os.Stat(pluginPath)
if err != nil {
log.Error("failed to get plugin file stat: %s", err)
return
}
if stat.IsDir() {
pluginDecoder, err = decoder.NewFSPluginDecoder(pluginPath)
} else {
fileContent, err := os.ReadFile(pluginPath)
if err != nil {
log.Error("failed to read plugin file: %s", err)
return
}
pluginDecoder, err = decoder.NewZipPluginDecoder(fileContent)
if err != nil {
log.Error("failed to create zip plugin decoder: %s", err)
return
}
}
if err != nil {
log.Error("your plugin is not a valid plugin: %s", err)
return
}
manifest, err := pluginDecoder.Manifest()
if err != nil {
log.Error("failed to get manifest: %s", err)
return
}
if manifest.Tool != nil {
for _, tool := range manifest.Tool.Tools {
tmpl, err := template.New("tool").Parse(TOOL_MODULE_TEMPLATE)
if err != nil {
log.Error("failed to parse template: %s", err)
return
}
err = tmpl.Execute(os.Stdout, tool)
if err != nil {
log.Error("failed to execute template: %s", err)
return
}
}
}
if manifest.AgentStrategy != nil {
for _, strategy := range manifest.AgentStrategy.Strategies {
tmpl, err := template.New("agent").Parse(AGENT_MODULE_TEMPLATE)
if err != nil {
log.Error("failed to parse template: %s", err)
return
}
err = tmpl.Execute(os.Stdout, strategy)
if err != nil {
log.Error("failed to execute template: %s", err)
return
}
}
}
if manifest.Model != nil {
for _, model := range manifest.Model.Models {
tmpl, err := template.New("model").Parse(MODEL_MODULE_TEMPLATE)
if err != nil {
log.Error("failed to parse template: %s", err)
return
}
err = tmpl.Execute(os.Stdout, model)
if err != nil {
log.Error("failed to execute template: %s", err)
return
}
}
}
if manifest.Endpoint != nil {
for _, endpoint := range manifest.Endpoint.Endpoints {
tmpl, err := template.New("endpoint").Parse(ENDPOINT_MODULE_TEMPLATE)
if err != nil {
log.Error("failed to parse template: %s", err)
return
}
err = tmpl.Execute(os.Stdout, endpoint)
if err != nil {
log.Error("failed to execute template: %s", err)
return
}
}
}
}
func ModuleAppendTools(pluginPath string) {
decoder, err := decoder.NewFSPluginDecoder(pluginPath)
if err != nil {
log.Error("your plugin is not a valid plugin: %s", err)
return
}
manifest, err := decoder.Manifest()
if err != nil {
log.Error("failed to get manifest: %s", err)
return
}
if manifest.Tool != nil {
log.Error("you have already declared tools in this plugin, " +
"you can add new tool by modifying the `provider.yaml` file to add new tools, " +
"this command is used to create new module that never been declared in this plugin.")
return
}
if manifest.Model != nil {
log.Error("model plugin dose not support declare tools.")
return
}
if manifest.Plugins.Tools == nil {
manifest.Plugins.Tools = []string{}
}
manifest.Plugins.Tools = append(manifest.Plugins.Tools, fmt.Sprintf("provider/%s.yaml", manifest.Name))
if manifest.Meta.Runner.Language == constants.Python {
if err := createPythonTool(pluginPath, &manifest); err != nil {
log.Error("failed to create python tool: %s", err)
return
}
if err := createPythonToolProvider(pluginPath, &manifest); err != nil {
log.Error("failed to create python tool provider: %s", err)
return
}
}
// save manifest
manifest_file := marshalYamlBytes(manifest.PluginDeclarationWithoutAdvancedFields)
if err := writeFile(filepath.Join(pluginPath, "manifest.yaml"), string(manifest_file)); err != nil {
log.Error("failed to save manifest: %s", err)
return
}
log.Info("created tool module successfully")
}
func ModuleAppendEndpoints(pluginPath string) {
decoder, err := decoder.NewFSPluginDecoder(pluginPath)
if err != nil {
log.Error("your plugin is not a valid plugin: %s", err)
return
}
manifest, err := decoder.Manifest()
if err != nil {
log.Error("failed to get manifest: %s", err)
return
}
if manifest.Endpoint != nil {
log.Error("you have already declared endpoints in this plugin, " +
"you can add new endpoint by modifying the `provider.yaml` file to add new endpoints, " +
"this command is used to create new module that never been declared in this plugin.")
return
}
if manifest.Model != nil {
log.Error("model plugin dose not support declare endpoints.")
return
}
if manifest.Plugins.Endpoints == nil {
manifest.Plugins.Endpoints = []string{}
}
manifest.Plugins.Endpoints = append(manifest.Plugins.Endpoints, fmt.Sprintf("group/%s.yaml", manifest.Name))
if manifest.Meta.Runner.Language == constants.Python {
if err := createPythonEndpoint(pluginPath, &manifest); err != nil {
log.Error("failed to create python endpoint: %s", err)
return
}
if err := createPythonEndpointGroup(pluginPath, &manifest); err != nil {
log.Error("failed to create python group: %s", err)
return
}
}
// save manifest
manifest_file := marshalYamlBytes(manifest.PluginDeclarationWithoutAdvancedFields)
if err := writeFile(filepath.Join(pluginPath, "manifest.yaml"), string(manifest_file)); err != nil {
log.Error("failed to save manifest: %s", err)
return
}
log.Info("created endpoint module successfully")
}