feat: 新增 Agent CLI — Web 版 AI 运维 Agent(参考 opsxcli 移植)
后端引擎 backend/pkg/agentcli/(纯引擎库,零业务依赖,剥离 CLI/TUI 外壳): - llm: OpenAI 兼容客户端,复用 model.LLMConfig - tools: ssh_execute(复用 pkg/remoteexec)+ analyze_output + 风险评估黑名单 - safety: 三级安全模式 + 五级风险 + WebSocket 异步确认 - prompt: 五层 System Prompt - core: ReAct 16 轮循环 + 自适应检查点 + 循环检测 - evolver: 四层记忆 + 进化循环,data/agentcli/ 文件存储 集成层: - controller/agent_cli.go: WebSocket 控制器(事件流推流 + 高危确认 + 会话持久化) - model/agent_cli.go: agent_cli_sessions/messages 表 + AutoMigrate - 路由 /ws/agent-cli + /api/v1/aiops/agent-cli/sessions - seed 权限 aiops:agent-cli / aiops:llm-config 前端: - AgentCLI.tsx: 对话流 + 工具块 + 高危确认 + 四模块 tips 面板 - LLMConfig.tsx: 大模型设置独立页 - api/agentCli.ts + Sidebar/App 菜单路由 文档: - docs/agent/ 11 篇(opsxcli 同名文档适配改写 + 00-README 映射总览) 其他: - CLAUDE.md 补充 agent-cli 模块说明 - 修正 .gitignore 根级二进制规则(前导 /,避免误伤 frontend/src/components/aiops/) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
f2069fe3f0
commit
92a2247390
37 files changed
+6449
-6
No files matched your search
@@ -0,0 +1,106 @@
|
||||
// builtin.go - 内置只读工具 // Logan.Li
|
||||
// analyze_output:对冗长命令输出做摘要/错误提取,避免 token 爆炸,辅助 LLM 聚焦关键线索。
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AnalyzeOutputTool 输出分析工具(只读,Safe) // Logan.Li
|
||||
type AnalyzeOutputTool struct{}
|
||||
|
||||
// NewAnalyzeOutputTool 创建输出分析工具 // Logan.Li
|
||||
func NewAnalyzeOutputTool() *AnalyzeOutputTool { return &AnalyzeOutputTool{} }
|
||||
|
||||
// Name 工具名 // Logan.Li
|
||||
func (t *AnalyzeOutputTool) Name() string { return "analyze_output" }
|
||||
|
||||
// Description 给 LLM 的说明 // Logan.Li
|
||||
func (t *AnalyzeOutputTool) Description() string {
|
||||
return "分析一段(可能很长的)命令输出文本:统计行数、提取疑似错误/告警行、必要时截断保留首尾。" +
|
||||
"当 ssh_execute 返回内容过长时调用此工具提炼关键信息再继续推理。"
|
||||
}
|
||||
|
||||
// Parameters 参数定义 // Logan.Li
|
||||
func (t *AnalyzeOutputTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"output": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "待分析的文本输出",
|
||||
},
|
||||
"focus": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "可选关注点,如 error、memory、disk",
|
||||
},
|
||||
},
|
||||
"required": []string{"output"},
|
||||
}
|
||||
}
|
||||
|
||||
// RiskLevel 静态风险(只读安全) // Logan.Li
|
||||
func (t *AnalyzeOutputTool) RiskLevel() RiskLevel { return RiskSafe }
|
||||
|
||||
// Execute 执行输出分析 // Logan.Li
|
||||
func (t *AnalyzeOutputTool) Execute(ctx context.Context, args map[string]interface{}) (*Result, error) {
|
||||
output := StringParam(args, "output")
|
||||
focus := strings.ToLower(StringParam(args, "focus"))
|
||||
if output == "" {
|
||||
return &Result{Success: true, Output: "(空输出)"}, nil
|
||||
}
|
||||
|
||||
lines := strings.Split(output, "\n")
|
||||
total := len(lines)
|
||||
|
||||
// 超长截断:保留前 40 + 后 40 行,中间用省略标注
|
||||
truncated := false
|
||||
if total > 120 {
|
||||
head := lines[:40]
|
||||
tail := lines[total-40:]
|
||||
lines = append(append(head, fmt.Sprintf("... [已省略 %d 行] ...", total-80)), tail...)
|
||||
truncated = true
|
||||
}
|
||||
|
||||
// 提取疑似错误/告警行
|
||||
errorKeywords := []string{"error", "fail", "exception", "traceback", "denied",
|
||||
"permission", "timeout", "refused", "unavailable", "critical", "fatal",
|
||||
"错误", "失败", "拒绝", "超时", "无法", "异常"}
|
||||
if focus != "" {
|
||||
errorKeywords = append([]string{focus}, errorKeywords...)
|
||||
}
|
||||
var errorLines []string
|
||||
for _, line := range lines {
|
||||
low := strings.ToLower(line)
|
||||
for _, kw := range errorKeywords {
|
||||
if strings.Contains(low, kw) {
|
||||
errorLines = append(errorLines, strings.TrimSpace(line))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(errorLines) > 20 {
|
||||
errorLines = errorLines[:20]
|
||||
}
|
||||
|
||||
// 组装分析摘要
|
||||
var sb strings.Builder
|
||||
sb.WriteString(fmt.Sprintf("总行数: %d", total))
|
||||
if truncated {
|
||||
sb.WriteString("(已截断保留首尾)")
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
if len(errorLines) > 0 {
|
||||
sb.WriteString(fmt.Sprintf("疑似错误/告警行 (%d):\n", len(errorLines)))
|
||||
for _, l := range errorLines {
|
||||
sb.WriteString(" " + l + "\n")
|
||||
}
|
||||
} else {
|
||||
sb.WriteString("未发现明显错误关键词\n")
|
||||
}
|
||||
sb.WriteString("\n输出片段:\n" + strings.Join(lines, "\n"))
|
||||
|
||||
return &Result{Success: true, Output: sb.String()}, nil
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// Package tools 提供 Agent CLI 引擎的工具注册中心与工具接口。 // Logan.Li
|
||||
// 设计参考 opsxcli/internal/agent/tools,剥离 CLI 专属工具(local_bash 本地执行、scp)。
|
||||
// Web 版聚焦远程运维:ssh_execute(目标主机执行)+ analyze_output(输出分析)。
|
||||
// 风险评估逻辑(黑名单 + AssessBashRisk)置于本包,避免与 safety 包形成循环依赖。
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"ezops/pkg/agentcli/llm"
|
||||
)
|
||||
|
||||
// RiskLevel 工具风险等级 // Logan.Li
|
||||
type RiskLevel int
|
||||
|
||||
const (
|
||||
RiskSafe RiskLevel = iota // 只读操作(cat/grep/df/ps)
|
||||
RiskLow // 低风险(mkdir/touch)
|
||||
RiskMedium // 中风险(chmod/文件修改)
|
||||
RiskHigh // 高风险(远程服务控制/reboot)
|
||||
RiskCritical // 危险操作(rm -rf //mkfs/dd)
|
||||
)
|
||||
|
||||
// String 返回风险等级字符串 // Logan.Li
|
||||
func (r RiskLevel) String() string {
|
||||
switch r {
|
||||
case RiskSafe:
|
||||
return "safe"
|
||||
case RiskLow:
|
||||
return "low"
|
||||
case RiskMedium:
|
||||
return "medium"
|
||||
case RiskHigh:
|
||||
return "high"
|
||||
case RiskCritical:
|
||||
return "critical"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// Display 返回风险等级中文显示 // Logan.Li
|
||||
func (r RiskLevel) Display() string {
|
||||
switch r {
|
||||
case RiskSafe:
|
||||
return "安全"
|
||||
case RiskLow:
|
||||
return "低风险"
|
||||
case RiskMedium:
|
||||
return "中风险"
|
||||
case RiskHigh:
|
||||
return "高风险"
|
||||
case RiskCritical:
|
||||
return "危险"
|
||||
default:
|
||||
return "未知"
|
||||
}
|
||||
}
|
||||
|
||||
// Result 工具执行结果 // Logan.Li
|
||||
type Result struct {
|
||||
Success bool `json:"success"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Tool 核心工具接口(5 方法) // Logan.Li
|
||||
type Tool interface {
|
||||
Name() string // 工具名
|
||||
Description() string // 给 LLM 看的描述
|
||||
Parameters() map[string]interface{} // JSON Schema 参数定义
|
||||
RiskLevel() RiskLevel // 静态风险等级
|
||||
Execute(ctx context.Context, args map[string]interface{}) (*Result, error)
|
||||
}
|
||||
|
||||
// DynamicRiskTool 动态风险评估接口 // Logan.Li
|
||||
// 工具可额外实现此接口,依据运行时参数动态计算风险(如 ssh_execute 看具体命令)。
|
||||
// 安全控制器 Check 时优先调用此接口。
|
||||
type DynamicRiskTool interface {
|
||||
Tool
|
||||
RiskLevelForArgs(args map[string]interface{}) RiskLevel
|
||||
}
|
||||
|
||||
// Registry 工具注册中心(线程安全) // Logan.Li
|
||||
type Registry struct {
|
||||
tools map[string]Tool
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewRegistry 创建空注册中心 // Logan.Li
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{tools: make(map[string]Tool)}
|
||||
}
|
||||
|
||||
// Register 注册工具 // Logan.Li
|
||||
func (r *Registry) Register(tool Tool) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.tools[tool.Name()] = tool
|
||||
}
|
||||
|
||||
// Get 按名获取工具 // Logan.Li
|
||||
func (r *Registry) Get(name string) (Tool, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
t, ok := r.tools[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("工具未找到: %s", name)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// List 列出所有工具 // Logan.Li
|
||||
func (r *Registry) List() []Tool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
list := make([]Tool, 0, len(r.tools))
|
||||
for _, t := range r.tools {
|
||||
list = append(list, t)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// ToLLMTools 转换为 LLM function calling 格式 // Logan.Li
|
||||
func (r *Registry) ToLLMTools() []llm.Tool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
out := make([]llm.Tool, 0, len(r.tools))
|
||||
for _, t := range r.tools {
|
||||
out = append(out, llm.Tool{
|
||||
Type: "function",
|
||||
Function: llm.ToolFunction{
|
||||
Name: t.Name(),
|
||||
Description: t.Description(),
|
||||
Parameters: t.Parameters(),
|
||||
},
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- 参数解析辅助 ---- // Logan.Li
|
||||
|
||||
// StringParam 取字符串参数 // Logan.Li
|
||||
func StringParam(args map[string]interface{}, key string) string {
|
||||
if v, ok := args[key]; ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// IntParam 取整型参数(兼容 int/float64/int64) // Logan.Li
|
||||
func IntParam(args map[string]interface{}, key string) int {
|
||||
if v, ok := args[key]; ok {
|
||||
switch val := v.(type) {
|
||||
case int:
|
||||
return val
|
||||
case float64:
|
||||
return int(val)
|
||||
case int64:
|
||||
return int(val)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// risk.go - 命令风险评估(黑名单 + 动态分级) // Logan.Li
|
||||
// 移植自 opsxcli internal/agent/safety/risk.go,置于 tools 包避免与 safety 循环依赖。
|
||||
// 供 ssh_execute 的 DynamicRiskTool.RiskLevelForArgs 调用,决定是否触发用户确认。
|
||||
package tools
|
||||
|
||||
import "strings"
|
||||
|
||||
// dangerousCommands 危险命令黑名单(系统损坏/数据丢失/服务中断) // Logan.Li
|
||||
var dangerousCommands = []string{
|
||||
"rm -rf /", "rm -rf /*", "rm -rf /bin", "rm -rf /boot", "rm -rf /etc",
|
||||
"rm -rf /home", "rm -rf /lib", "rm -rf /lib64", "rm -rf /proc", "rm -rf /root",
|
||||
"rm -rf /sbin", "rm -rf /sys", "rm -rf /usr", "rm -rf /var",
|
||||
"mkfs", "mkfs.ext", "mkfs.xfs", "mkfs.btrfs", "mkfs.vfat",
|
||||
"dd if=/dev/zero", "dd if=/dev/random", "dd if=/dev/urandom",
|
||||
":(){ :|:& };:", ":() { : | : & }; :",
|
||||
"> /dev/sda", "> /dev/sdb", "> /dev/sdc", "> /dev/hda",
|
||||
"mv / /dev/null", "mv /* /dev/null",
|
||||
"chmod -R 000 /", "chmod -R 777 /",
|
||||
"systemctl stop ssh", "systemctl disable ssh", "kill -9 1",
|
||||
"iptables -F", "iptables --flush",
|
||||
}
|
||||
|
||||
// readOnlyCommands 只读命令(安全) // Logan.Li
|
||||
var readOnlyCommands = []string{
|
||||
"cat", "grep", "egrep", "fgrep", "awk", "sed", "head", "tail", "less", "more",
|
||||
"sort", "uniq", "wc", "ps", "top", "df", "du", "free", "uptime", "uname",
|
||||
"hostname", "ifconfig", "ip addr", "ip link", "ip route", "netstat", "ss",
|
||||
"ls", "ll", "pwd", "who", "w", "last", "vmstat", "iostat", "mpstat", "sar",
|
||||
"lsof", "find", "which", "whereis", "file", "stat", "date", "echo", "id",
|
||||
"whoami", "groups", "getent", "dmesg", "systemctl status", "systemctl list-units",
|
||||
"lsblk", "blkid", "mount", "journalctl",
|
||||
}
|
||||
|
||||
// modificationCommands 文件修改命令(低-中风险) // Logan.Li
|
||||
var modificationCommands = []string{
|
||||
"cp", "mv", "mkdir", "rmdir", "touch", "chmod", "chown", "chgrp", "ln",
|
||||
"tar", "gzip", "gunzip", "zip", "unzip", "rsync", "tee",
|
||||
}
|
||||
|
||||
// highRiskCommands 高风险命令(服务控制/删除/重启) // Logan.Li
|
||||
var highRiskCommands = []string{
|
||||
"rm", "dd", "shutdown", "reboot", "halt", "poweroff", "init",
|
||||
"systemctl restart", "systemctl stop", "systemctl start",
|
||||
"kill", "killall", "pkill", "userdel", "groupdel", "fdisk", "parted", "mkfs",
|
||||
}
|
||||
|
||||
// IsDangerousCommand 检查命令是否命中黑名单 // Logan.Li
|
||||
// 返回 (是否危险, 命中的模式)。
|
||||
func IsDangerousCommand(command string) (bool, string) {
|
||||
trimmed := strings.TrimSpace(command)
|
||||
if trimmed == "" {
|
||||
return false, ""
|
||||
}
|
||||
lower := strings.ToLower(trimmed)
|
||||
for _, d := range dangerousCommands {
|
||||
if strings.Contains(lower, strings.ToLower(d)) {
|
||||
return true, d
|
||||
}
|
||||
}
|
||||
// rm -rf + 根目录路径特殊检测
|
||||
if strings.HasPrefix(lower, "rm") && strings.Contains(lower, "-rf") && containsRootPath(lower) {
|
||||
return true, "rm -rf 包含根目录路径"
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// containsRootPath 检测是否含系统根目录路径 // Logan.Li
|
||||
func containsRootPath(cmd string) bool {
|
||||
paths := []string{" /boot", " /etc", " /usr", " /var", " /lib", " /lib64",
|
||||
" /sbin", " /bin", " /opt", " /home", " /root", " /tmp", " /var/log"}
|
||||
for _, p := range paths {
|
||||
if strings.Contains(cmd, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AssessBashRisk 动态评估命令风险等级 // Logan.Li
|
||||
// 黑名单→Critical;纯只读→Safe;组合命令取最高;sudo 提升。
|
||||
func AssessBashRisk(command string) RiskLevel {
|
||||
trimmed := strings.TrimSpace(command)
|
||||
if trimmed == "" {
|
||||
return RiskSafe
|
||||
}
|
||||
lower := strings.ToLower(trimmed)
|
||||
|
||||
if isDangerous, _ := IsDangerousCommand(command); isDangerous {
|
||||
return RiskCritical
|
||||
}
|
||||
if isReadOnlyCommand(lower) {
|
||||
return RiskSafe
|
||||
}
|
||||
if strings.Contains(lower, "&&") || strings.Contains(lower, "||") ||
|
||||
strings.Contains(lower, "|") || strings.Contains(lower, ";") {
|
||||
return assessCompoundCommand(lower)
|
||||
}
|
||||
isSudo := strings.HasPrefix(lower, "sudo ")
|
||||
return assessSingleCommand(strings.TrimPrefix(lower, "sudo "), isSudo)
|
||||
}
|
||||
|
||||
// isReadOnlyCommand 是否纯只读命令 // Logan.Li
|
||||
func isReadOnlyCommand(cmd string) bool {
|
||||
cmd = strings.TrimPrefix(cmd, "sudo ")
|
||||
cmd = strings.TrimSpace(cmd)
|
||||
for _, ro := range readOnlyCommands {
|
||||
if strings.HasPrefix(cmd, strings.ToLower(ro)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// assessCompoundCommand 组合命令取子命令最高风险 // Logan.Li
|
||||
func assessCompoundCommand(cmd string) RiskLevel {
|
||||
maxRisk := RiskSafe
|
||||
parts := []string{cmd}
|
||||
for _, sep := range []string{"&&", "||", "|", ";"} {
|
||||
var next []string
|
||||
for _, p := range parts {
|
||||
for _, sp := range strings.Split(p, sep) {
|
||||
sp = strings.TrimSpace(sp)
|
||||
if sp != "" {
|
||||
next = append(next, sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
parts = next
|
||||
}
|
||||
for _, p := range parts {
|
||||
if r := assessSingleCommand(strings.TrimPrefix(p, "sudo "), false); r > maxRisk {
|
||||
maxRisk = r
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(cmd, "sudo ") && maxRisk < RiskCritical {
|
||||
maxRisk++
|
||||
}
|
||||
return maxRisk
|
||||
}
|
||||
|
||||
// assessSingleCommand 单命令风险(按前缀分类) // Logan.Li
|
||||
func assessSingleCommand(cmd string, isSudo bool) RiskLevel {
|
||||
cmd = strings.TrimSpace(cmd)
|
||||
fields := strings.Fields(cmd)
|
||||
if len(fields) == 0 {
|
||||
return RiskSafe
|
||||
}
|
||||
main := strings.ToLower(fields[0])
|
||||
|
||||
for _, h := range highRiskCommands {
|
||||
if main == strings.ToLower(h) || strings.HasPrefix(main, strings.ToLower(h)) {
|
||||
if isSudo {
|
||||
return RiskHigh
|
||||
}
|
||||
return RiskMedium
|
||||
}
|
||||
}
|
||||
for _, m := range modificationCommands {
|
||||
if main == strings.ToLower(m) {
|
||||
if isSudo {
|
||||
return RiskMedium
|
||||
}
|
||||
return RiskLow
|
||||
}
|
||||
}
|
||||
if isSudo {
|
||||
return RiskMedium
|
||||
}
|
||||
return RiskLow
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// ssh_execute.go - 远程命令执行工具 // Logan.Li
|
||||
// 复用 aiops 既有 pkg/remoteexec(Go 原生 SSH),凭据由 controller 从 model.Server 构建后注入。
|
||||
// 实现 DynamicRiskTool:依据具体命令动态评估风险,决定是否触发用户确认。
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ezops/pkg/remoteexec"
|
||||
)
|
||||
|
||||
// SSHExecuteTool 远程命令执行工具 // Logan.Li
|
||||
type SSHExecuteTool struct {
|
||||
cfg remoteexec.SSHConfig // 目标主机连接配置(含凭据)
|
||||
timeout time.Duration // 默认命令超时
|
||||
}
|
||||
|
||||
// NewSSHExecuteTool 创建远程执行工具 // Logan.Li
|
||||
func NewSSHExecuteTool(cfg remoteexec.SSHConfig, timeout time.Duration) *SSHExecuteTool {
|
||||
if timeout <= 0 {
|
||||
timeout = 60 * time.Second
|
||||
}
|
||||
return &SSHExecuteTool{cfg: cfg, timeout: timeout}
|
||||
}
|
||||
|
||||
// Name 工具名 // Logan.Li
|
||||
func (t *SSHExecuteTool) Name() string { return "ssh_execute" }
|
||||
|
||||
// Description 给 LLM 的工具说明 // Logan.Li
|
||||
func (t *SSHExecuteTool) Description() string {
|
||||
host := t.cfg.Host
|
||||
if host == "" {
|
||||
host = "目标主机"
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"在远程服务器 %s(用户 %s)上执行 shell 命令并返回合并的 stdout+stderr 输出与退出码。"+
|
||||
"用于排障(查看日志/进程/磁盘/网络)、安装与配置软件、重启服务等。"+
|
||||
"高危命令(rm -rf /、mkfs、reboot 等)需用户确认。", host, t.cfg.User)
|
||||
}
|
||||
|
||||
// Parameters JSON Schema 参数定义 // Logan.Li
|
||||
func (t *SSHExecuteTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"command": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "要执行的 shell 命令,例如 df -h、systemctl status nginx、tail -n 100 /var/log/messages",
|
||||
},
|
||||
"timeout": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "命令超时秒数(默认 60)",
|
||||
},
|
||||
},
|
||||
"required": []string{"command"},
|
||||
}
|
||||
}
|
||||
|
||||
// RiskLevel 静态风险等级(高危) // Logan.Li
|
||||
func (t *SSHExecuteTool) RiskLevel() RiskLevel { return RiskHigh }
|
||||
|
||||
// RiskLevelForArgs 依据命令动态评估风险 // Logan.Li
|
||||
func (t *SSHExecuteTool) RiskLevelForArgs(args map[string]interface{}) RiskLevel {
|
||||
return AssessBashRisk(StringParam(args, "command"))
|
||||
}
|
||||
|
||||
// Execute 执行远程命令 // Logan.Li
|
||||
func (t *SSHExecuteTool) Execute(ctx context.Context, args map[string]interface{}) (*Result, error) {
|
||||
command := strings.TrimSpace(StringParam(args, "command"))
|
||||
if command == "" {
|
||||
return &Result{Success: false, Error: "参数 command 不能为空"}, nil
|
||||
}
|
||||
|
||||
timeout := t.timeout
|
||||
if sec := IntParam(args, "timeout"); sec > 0 {
|
||||
timeout = time.Duration(sec) * time.Second
|
||||
}
|
||||
|
||||
res, err := remoteexec.Exec(t.cfg, command, timeout)
|
||||
if err != nil {
|
||||
// 连接级失败(无法 SSH)
|
||||
return &Result{Success: false, Error: fmt.Sprintf("SSH 连接失败: %v", err)}, nil
|
||||
}
|
||||
|
||||
// 附带退出码,便于 agent 判断命令是否成功(排障关键信号)
|
||||
output := res.Output
|
||||
if !strings.HasSuffix(output, "\n") && output != "" {
|
||||
output += "\n"
|
||||
}
|
||||
output += fmt.Sprintf("[exit_code=%d]", res.ExitCode)
|
||||
|
||||
return &Result{
|
||||
Success: res.Success, // exit_code==0
|
||||
Output: output,
|
||||
Error: res.Error,
|
||||
}, nil
|
||||
}
|
||||
Reference in new issue
Block a user