yao/cmd/run.go
Max d21f9c3769 Enhance Logging Functionality in RequestLogger
- Added a `noop` check in multiple logging methods (`LLMComplete`, `ToolStart`, `ToolComplete`, `HookStart`, `HookComplete`, and `HistoryLoad`) to prevent logging when the logger is in no-operation mode.
- Improved command handling in `root.go` by removing minimum argument requirements for commands and providing help output when no arguments are given.
- Introduced an `agent` command for better organization of agent-related functionalities in the CLI.
- Implemented automatic detection of the application root directory in `run.go` to streamline the application startup process.
- Cleaned up debug print statements in `config.go` to reduce clutter in the output.
2025-12-17 12:33:34 +08:00

232 lines
5.2 KiB
Go

package cmd
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
jsoniter "github.com/json-iterator/go"
"github.com/spf13/cobra"
"github.com/yaoapp/gou/helper"
"github.com/yaoapp/gou/plugin"
"github.com/yaoapp/gou/process"
"github.com/yaoapp/kun/exception"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/engine"
ischedule "github.com/yaoapp/yao/schedule"
"github.com/yaoapp/yao/share"
itask "github.com/yaoapp/yao/task"
)
var runSilent = false
var runCmd = &cobra.Command{
Use: "run",
Short: L("Execute process"),
Long: L("Execute process"),
Run: func(cmd *cobra.Command, args []string) {
defer share.SessionStop()
defer plugin.KillAll()
defer func() {
err := exception.Catch(recover())
if err != nil {
if !runSilent {
color.Red(L("Fatal: %s\n"), err.Error())
return
}
fmt.Printf("%s\n", err.Error())
}
}()
// Auto-detect app root if not specified
if appPath == "" {
cwd, err := os.Getwd()
if err == nil {
if root, err := findAppRootFromPath(cwd); err == nil {
appPath = root
}
}
}
Boot()
// Set Runtime Mode
config.Conf.Runtime.Mode = "standard"
cfg := config.Conf
cfg.Session.IsCLI = true
if len(args) < 1 {
if !runSilent {
color.Red(L("Not enough arguments\n"))
color.White(share.BUILDNAME + " help\n")
return
}
fmt.Print(L("Not enough arguments\n"))
return
}
loadWarnings, err := engine.Load(cfg, engine.LoadOption{Action: "run"})
if err != nil {
if !runSilent {
color.Red(L("Engine: %s\n"), err.Error())
return
}
fmt.Printf("%s\n", err.Error())
return
}
name := args[0]
if !runSilent {
color.Green(L("Run: %s\n"), name)
}
pargs := []interface{}{}
for i, arg := range args {
if i == 0 {
continue
}
// Parse the arguments
if strings.HasPrefix(arg, "::") {
arg := strings.TrimPrefix(arg, "::")
var v interface{}
err := jsoniter.Unmarshal([]byte(arg), &v)
if err != nil {
color.Red(L("Arguments: %s\n"), err.Error())
return
}
pargs = append(pargs, v)
if !runSilent {
color.White("args[%d]: %s\n", i-1, arg)
}
} else if strings.HasPrefix(arg, "\\::") {
arg := "::" + strings.TrimPrefix(arg, "\\::")
pargs = append(pargs, arg)
if !runSilent {
color.White("args[%d]: %s\n", i-1, arg)
}
} else {
pargs = append(pargs, arg)
if !runSilent {
color.White("args[%d]: %s\n", i-1, arg)
}
}
}
// Start Tasks
itask.Start()
defer itask.Stop()
// Start Schedules
ischedule.Start()
defer ischedule.Stop()
process := process.NewWithContext(context.Background(), name, pargs...)
res, err := process.Exec()
if err != nil {
if !runSilent {
color.Red(L("Process: %s\n"), fmt.Sprintf("%s", strings.TrimPrefix(err.Error(), "Exception|404:")))
return
}
fmt.Printf("%s\n", err.Error())
return
}
if !runSilent {
if len(loadWarnings) > 0 {
fmt.Println(color.YellowString("---------------------------------"))
fmt.Println(color.YellowString(L("Warnings")))
fmt.Println(color.YellowString("---------------------------------"))
for _, warning := range loadWarnings {
fmt.Println(color.YellowString("[%s] %s", warning.Widget, warning.Error))
}
fmt.Printf("\n")
}
color.White("--------------------------------------\n")
color.White(L("%s Response\n"), name)
color.White("--------------------------------------\n")
helper.Dump(res)
color.White("--------------------------------------\n")
color.Green(L("✨DONE✨\n"))
return
}
// Silent mode output
switch res.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool:
fmt.Printf("%v\n", res)
return
case string, []byte:
fmt.Printf("%s\n", res)
return
default:
txt, err := jsoniter.Marshal(res)
if err != nil {
fmt.Printf("%s\n", err.Error())
}
fmt.Printf("%s\n", txt)
}
},
}
func init() {
runCmd.PersistentFlags().BoolVarP(&runSilent, "silent", "s", false, L("Silent mode"))
}
// findAppRootFromPath finds the Yao application root directory by looking for app.yao
// It traverses up from the given path until it finds app.yao or reaches the filesystem root
func findAppRootFromPath(startPath string) (string, error) {
// Get absolute path
absPath, err := filepath.Abs(startPath)
if err != nil {
return "", fmt.Errorf("failed to get absolute path: %w", err)
}
// If it's a file, start from its directory
info, err := os.Stat(absPath)
if err != nil {
return "", fmt.Errorf("path not found: %s", absPath)
}
var dir string
if info.IsDir() {
dir = absPath
} else {
dir = filepath.Dir(absPath)
}
// Traverse up to find app.yao
for {
// Check for app.yao, app.json, or app.jsonc
for _, appFile := range []string{"app.yao", "app.json", "app.jsonc"} {
appFilePath := filepath.Join(dir, appFile)
if _, err := os.Stat(appFilePath); err == nil {
return dir, nil
}
}
// Move to parent directory
parent := filepath.Dir(dir)
if parent == dir {
// Reached root, no app.yao found
break
}
dir = parent
}
return "", fmt.Errorf("no app.yao found in path hierarchy of %s", startPath)
}