chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
// dumphelp renders the visible cobra command tree into the JSON snapshot at
|
||||
// dify-agent/src/dify_agent/layers/_agent_cli_help.json. The Go CLI is the
|
||||
// single source of truth for both the command surface and its help text; the
|
||||
// Python server loads this JSON and injects the strings into the agent prompt
|
||||
// without executing a shell. Emitting JSON keeps the Go side free of any
|
||||
// Python formatting/encoding concerns.
|
||||
//
|
||||
// It is invoked via the hidden `dify-agent __dump-cli-help` intercept (see
|
||||
// main.go) and driven by `make gen-cli-help` / `go generate`.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// dumpCLIHelp writes the help snapshot as a JSON object mapping each
|
||||
// space-joined command path (e.g. "config note push") to the verbatim
|
||||
// `dify-agent <path> --help` output. json.MarshalIndent sorts object keys, so
|
||||
// the output is deterministic for clean diffs.
|
||||
func dumpCLIHelp(w io.Writer) error {
|
||||
paths := collectHelpPaths(newRootCommand(), nil)
|
||||
help := make(map[string]string, len(paths))
|
||||
for _, path := range paths {
|
||||
help[strings.Join(path, " ")] = captureHelp(path)
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(help, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = w.Write(append(data, '\n'))
|
||||
return err
|
||||
}
|
||||
|
||||
// collectHelpPaths walks the command tree and returns the path of every visible
|
||||
// (non-hidden) command, excluding the root itself. Paths are relative to the
|
||||
// root, e.g. ["config", "note", "push"].
|
||||
func collectHelpPaths(cmd *cobra.Command, prefix []string) [][]string {
|
||||
var paths [][]string
|
||||
for _, child := range cmd.Commands() {
|
||||
if child.Hidden || child.Name() == "help" {
|
||||
continue
|
||||
}
|
||||
childPath := append(append([]string{}, prefix...), child.Name())
|
||||
paths = append(paths, childPath)
|
||||
paths = append(paths, collectHelpPaths(child, childPath)...)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// captureHelp renders one command's `--help` output exactly as the CLI does.
|
||||
// A fresh root per call avoids leaking parsed flag state between commands,
|
||||
// mirroring the executeHelp test helper.
|
||||
func captureHelp(path []string) string {
|
||||
root := newRootCommand()
|
||||
var buf bytes.Buffer
|
||||
root.SetOut(&buf)
|
||||
root.SetErr(&buf)
|
||||
root.SetArgs(append(append([]string{}, path...), "--help"))
|
||||
_ = root.Execute()
|
||||
return strings.TrimRight(buf.String(), "\n")
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// checkedInHelpJSON is the JSON snapshot generated from this command tree,
|
||||
// relative to the package directory (cmd/dify-agent-cli).
|
||||
const checkedInHelpJSON = "../../../dify-agent/src/dify_agent/layers/_agent_cli_help.json"
|
||||
|
||||
// TestDumpCLIHelpMatchesCheckedIn fails when the committed JSON help snapshot
|
||||
// drifts from the current Go command tree. Regenerate with:
|
||||
//
|
||||
// make -C dify-agent-runtime gen-cli-help
|
||||
func TestDumpCLIHelpMatchesCheckedIn(t *testing.T) {
|
||||
want, err := os.ReadFile(checkedInHelpJSON)
|
||||
if err != nil {
|
||||
t.Skipf("checked-in help snapshot not found (%v); run `make gen-cli-help`", err)
|
||||
}
|
||||
|
||||
var got bytes.Buffer
|
||||
if err := dumpCLIHelp(&got); err != nil {
|
||||
t.Fatalf("dumpCLIHelp: %v", err)
|
||||
}
|
||||
|
||||
if got.String() != string(want) {
|
||||
t.Errorf("%s is stale; regenerate with `make -C dify-agent-runtime gen-cli-help`", checkedInHelpJSON)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDumpCLIHelpCoversPromptCommands ensures the generated snapshot includes
|
||||
// every command path the Python config layer injects into the prompt, and that
|
||||
// the output is valid JSON keyed by space-joined command paths.
|
||||
func TestDumpCLIHelpCoversPromptCommands(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
if err := dumpCLIHelp(&buf); err != nil {
|
||||
t.Fatalf("dumpCLIHelp: %v", err)
|
||||
}
|
||||
|
||||
var table map[string]string
|
||||
if err := json.Unmarshal(buf.Bytes(), &table); err != nil {
|
||||
t.Fatalf("generated snapshot is not valid JSON: %v", err)
|
||||
}
|
||||
|
||||
wantKeys := []string{
|
||||
"config",
|
||||
"config manifest",
|
||||
"config skills pull",
|
||||
"config files pull",
|
||||
"config note pull",
|
||||
"config note push",
|
||||
"config prompt pull",
|
||||
"config prompt push",
|
||||
"config env push",
|
||||
"config files push",
|
||||
"config files delete",
|
||||
"config skills push",
|
||||
"config skills delete",
|
||||
"file upload",
|
||||
"file download",
|
||||
"file public-url",
|
||||
}
|
||||
for _, key := range wantKeys {
|
||||
if _, ok := table[key]; !ok {
|
||||
t.Errorf("generated snapshot missing prompt command key %q", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/agentcli"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func newKnowledgeCommand() *cobra.Command {
|
||||
var protocolVersion bool
|
||||
root := &cobra.Command{Use: "knowledge", Short: "Autonomously inspect read-only Agent Knowledge Base evidence. All results are JSON.",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if protocolVersion {
|
||||
_, err := fmt.Fprintln(cmd.OutOrStdout(), "1")
|
||||
return err
|
||||
}
|
||||
return cmd.Help()
|
||||
}, Args: cobra.NoArgs}
|
||||
root.Flags().BoolVar(&protocolVersion, "protocol-version", false, "Print the locally supported knowledge protocol version.")
|
||||
definitions := []struct {
|
||||
name, description string
|
||||
flags []string
|
||||
}{
|
||||
{"spaces", "List only Agent Knowledge Bases bound to this Agent and their current availability.", nil},
|
||||
{"capabilities", "Inspect this Agent Knowledge Base's current capabilities (no model credentials).", []string{"space"}},
|
||||
{"search", "Retrieve evidence using the knowledge base profile; no nested planner or generated answer.", []string{"space", "query", "image-file-id", "limit"}},
|
||||
{"ls", "List a bounded page of /knowledge entries.", []string{"space", "path", "cursor", "limit"}},
|
||||
{"tree", "Browse a bounded /knowledge subtree.", []string{"space", "path", "cursor", "limit", "depth"}},
|
||||
{"find", "Find /knowledge entries whose names contain the query.", []string{"space", "path", "query", "cursor", "limit"}},
|
||||
{"grep", "Search text inside /knowledge with a bounded server timeout.", []string{"space", "path", "query", "cursor", "limit"}},
|
||||
{"cat", "Read a page of text. Raw manifests and binary artifacts are not exposed.", []string{"space", "path", "cursor", "limit"}},
|
||||
{"stat", "Inspect safe metadata for one /knowledge path.", []string{"space", "path"}},
|
||||
{"diff", "Compare two readable paths without an LLM semantic-diff call.", []string{"space", "old-path", "new-path"}},
|
||||
{"open", "Open a node ID or validate/reopen a trusted evidence receipt.", []string{"space", "node-id", "receipt"}},
|
||||
{"images", "List image items and captions from a receipt's immutable document artifact.", []string{"space", "receipt", "cursor", "limit"}},
|
||||
{"image", "Deliver one bounded image to a vision-capable Agent via the trusted runtime channel.", []string{"space", "receipt", "item-id"}},
|
||||
}
|
||||
for _, definition := range definitions {
|
||||
cmd := &cobra.Command{Use: definition.name, Short: definition.description, Args: cobra.NoArgs}
|
||||
cmd.Flags().String("command-id", "", "Logical UUID for this command; generated by default. Reusing it will not repeat retrieval.")
|
||||
cmd.Flags().Bool("json", true, "Emit complete JSON (always enabled).")
|
||||
for _, flag := range definition.flags {
|
||||
switch flag {
|
||||
case "limit":
|
||||
cmd.Flags().Int(flag, 10, "Maximum returned items/segments (1–50); retrieval depth still belongs to the knowledge base profile.")
|
||||
case "depth":
|
||||
cmd.Flags().Int(flag, 2, "Maximum tree depth (1–4).")
|
||||
case "path":
|
||||
cmd.Flags().String(flag, "/knowledge", "Canonical read-only /knowledge path.")
|
||||
case "space":
|
||||
cmd.Flags().String(flag, "", "Agent Knowledge Base bound to this Agent.")
|
||||
case "image-file-id":
|
||||
cmd.Flags().StringArray(flag, nil, "Authorized upload UUID or local_file dify-file-ref from inputs; repeat at most four times, never a URL.")
|
||||
default:
|
||||
cmd.Flags().String(flag, "", "Knowledge command "+flag+".")
|
||||
}
|
||||
}
|
||||
cmd.RunE = func(cmd *cobra.Command, args []string) error {
|
||||
env, err := agentcli.ReadEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id, _ := cmd.Flags().GetString("command-id")
|
||||
if id == "" {
|
||||
id, err = agentcli.NewKnowledgeCommandID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payload := map[string]any{"version": 1, "command": cmd.Name(), "command_id": id}
|
||||
keys := map[string]string{"space": "space", "query": "query", "path": "path", "cursor": "cursor",
|
||||
"old-path": "old_path", "new-path": "new_path", "node-id": "node_id", "receipt": "receipt_id", "item-id": "item_id"}
|
||||
for flag, key := range keys {
|
||||
if cmd.Flags().Lookup(flag) != nil {
|
||||
value, _ := cmd.Flags().GetString(flag)
|
||||
if value != "" {
|
||||
payload[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, flag := range []string{"limit", "depth"} {
|
||||
if cmd.Flags().Lookup(flag) != nil {
|
||||
value, _ := cmd.Flags().GetInt(flag)
|
||||
payload[flag] = value
|
||||
}
|
||||
}
|
||||
if cmd.Flags().Lookup("image-file-id") != nil {
|
||||
images, _ := cmd.Flags().GetStringArray("image-file-id")
|
||||
if len(images) > 4 {
|
||||
return fmt.Errorf("knowledge search accepts at most four query images")
|
||||
}
|
||||
for index, value := range images {
|
||||
images[index], err = agentcli.KnowledgeQueryImageID(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(images) > 0 {
|
||||
payload["image_file_ids"] = images
|
||||
}
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return agentcli.RunKnowledge(ctx, env, payload, cmd.OutOrStdout())
|
||||
}
|
||||
root.AddCommand(cmd)
|
||||
}
|
||||
return root
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/agentcli"
|
||||
)
|
||||
|
||||
func TestKnowledgeProtocolNeedsNoEnvironment(t *testing.T) {
|
||||
t.Setenv(agentcli.EnvAPIBaseURL, "")
|
||||
t.Setenv(agentcli.EnvAuthJWE, "")
|
||||
if output := executeHelp(t, "knowledge", "--protocol-version"); output != "1\n" {
|
||||
t.Fatalf("unexpected protocol: %q", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeCommandsSerializeOnlyAllowedArguments(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload["command"] == "grep" && payload["query"] != "text" {
|
||||
t.Fatal("query lost")
|
||||
}
|
||||
if _, found := payload["url"]; found {
|
||||
t.Fatal("routing authority exposed")
|
||||
}
|
||||
if images, found := payload["image_file_ids"]; found {
|
||||
if values := images.([]any); len(values) != 1 || values[0] != "00000000-0000-4000-8000-000000000001" {
|
||||
t.Fatal("canonical input reference was not translated into an upload identity")
|
||||
}
|
||||
}
|
||||
payload["status"] = "ok"
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv(agentcli.EnvAPIBaseURL, server.URL)
|
||||
t.Setenv(agentcli.EnvAuthJWE, "jwe")
|
||||
for _, args := range [][]string{
|
||||
{"spaces"}, {"capabilities", "--space", "docs"}, {"search", "--space", "docs", "--query", "text"},
|
||||
{"search", "--space", "docs", "--image-file-id", "dify-file-ref:" + base64.URLEncoding.EncodeToString([]byte(`{"record_id":"00000000-0000-4000-8000-000000000001"}`))},
|
||||
{"ls", "--space", "docs"}, {"tree", "--space", "docs"}, {"find", "--space", "docs", "--query", "text"},
|
||||
{"grep", "--space", "docs", "--query", "text"}, {"cat", "--space", "docs", "--path", "/knowledge/a"}, {"stat", "--space", "docs"},
|
||||
{"diff", "--space", "docs", "--old-path", "/knowledge/a", "--new-path", "/knowledge/b"},
|
||||
{"open", "--space", "docs", "--node-id", "00000000-0000-4000-8000-000000000001"},
|
||||
{"images", "--space", "docs", "--receipt", "receipt"}, {"image", "--space", "docs", "--receipt", "receipt", "--item-id", "image"},
|
||||
} {
|
||||
t.Run(args[0], func(t *testing.T) {
|
||||
output := executeHelp(t, append([]string{"knowledge"}, args...)...)
|
||||
if !json.Valid(bytes.TrimSpace([]byte(output))) {
|
||||
t.Fatal(output)
|
||||
}
|
||||
})
|
||||
}
|
||||
root := newRootCommand()
|
||||
root.SetArgs([]string{"knowledge", "search", "--url", "http://other"})
|
||||
if err := root.Execute(); err == nil {
|
||||
t.Fatal("arbitrary URL flag accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
// dify-agent-cli is the Go replacement for the Python dify-agent CLI.
|
||||
// It communicates with the Agent Stub server via HTTP to provide
|
||||
// connect, file, and config operations inside the sandbox container.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/agentcli"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// knownRootCommands mirrors the Python CLI's _KNOWN_ROOT_COMMANDS. Anything else
|
||||
// on the command line is treated as argv forwarded to an implicit connect.
|
||||
var knownRootCommands = map[string]struct{}{
|
||||
"config": {},
|
||||
"connect": {},
|
||||
"file": {},
|
||||
"knowledge": {},
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := runCLI(os.Args[1:]); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "dify-agent: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
//go:generate sh -c "go run . __dump-cli-help > ../../../dify-agent/src/dify_agent/layers/_agent_cli_help.json"
|
||||
|
||||
func runCLI(args []string) error {
|
||||
// Hidden developer intercept: emit the JSON help snapshot from the cobra
|
||||
// tree. It is not registered as a cobra command, so developer-only help
|
||||
// generation stays out of the visible CLI. See dumphelp.go.
|
||||
if len(args) == 1 && args[0] == "__dump-cli-help" {
|
||||
return dumpCLIHelp(os.Stdout)
|
||||
}
|
||||
|
||||
// `connect` forwards its argv verbatim, so bypass flag parsing unless the
|
||||
// user explicitly asked for help (which should render connect's help).
|
||||
if len(args) >= 1 && args[0] == "connect" && !isHelpRequest(args[1:]) {
|
||||
jsonOutput, forwarded := parseConnectArgs(args[1:])
|
||||
return runConnect(forwarded, jsonOutput)
|
||||
}
|
||||
|
||||
jsonOutput, forwarded := extractRootJSONFlag(args)
|
||||
if isUnknownBareCommand(forwarded) {
|
||||
// Match Python: surface root help when the environment is missing, then
|
||||
// still attempt connect so the missing-env error is reported.
|
||||
if !agentcli.HasEnvironment() {
|
||||
_ = newRootCommand().Help()
|
||||
}
|
||||
return runConnect(forwarded, jsonOutput)
|
||||
}
|
||||
|
||||
root := newRootCommand()
|
||||
root.SetArgs(args)
|
||||
return root.Execute()
|
||||
}
|
||||
|
||||
// --- command tree ---
|
||||
|
||||
func newRootCommand() *cobra.Command {
|
||||
root := &cobra.Command{
|
||||
Use: "dify-agent",
|
||||
Short: "Forward shell-visible dify-agent commands to the Dify Agent Stub server.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
}
|
||||
root.CompletionOptions.DisableDefaultCmd = true
|
||||
// The Python CLI exposes no `help` command; hide cobra's auto-added one so
|
||||
// the visible command surface stays identical.
|
||||
root.SetHelpCommand(&cobra.Command{Hidden: true})
|
||||
root.AddCommand(
|
||||
newConnectCommand(),
|
||||
newFileCommand(),
|
||||
newConfigCommand(),
|
||||
newKnowledgeCommand(),
|
||||
)
|
||||
return root
|
||||
}
|
||||
|
||||
func newConnectCommand() *cobra.Command {
|
||||
var jsonOutput bool
|
||||
// connect is normally intercepted in runCLI; this definition exists so
|
||||
// `dify-agent connect --help` renders framework help for the command.
|
||||
cmd := &cobra.Command{
|
||||
Use: "connect [ARGV]...",
|
||||
Short: "Establish one Agent Stub connection using the current environment.",
|
||||
RunE: func(_ *cobra.Command, args []string) error {
|
||||
return runConnect(args, jsonOutput)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&jsonOutput, "json", false, "Emit the connection response as JSON.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newFileCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "file",
|
||||
Short: "Upload or download workflow files through the Agent Stub.",
|
||||
}
|
||||
|
||||
var noDownloadLink bool
|
||||
upload := &cobra.Command{
|
||||
Use: "upload PATH",
|
||||
Short: "Upload one sandbox-local file as a ToolFile output reference.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunFileUpload(env, args[0], noDownloadLink)
|
||||
}),
|
||||
}
|
||||
upload.Flags().BoolVar(
|
||||
&noDownloadLink,
|
||||
"no-download-link",
|
||||
false,
|
||||
"Skip creating a public download link after upload.",
|
||||
)
|
||||
publicURL := &cobra.Command{
|
||||
Use: "public-url REFERENCE",
|
||||
Short: "Create a browser-visible download URL for an existing ToolFile reference.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunFilePublicURL(env, args[0])
|
||||
}),
|
||||
}
|
||||
|
||||
var downloadTo string
|
||||
download := &cobra.Command{
|
||||
Use: "download TRANSFER_METHOD REFERENCE_OR_URL",
|
||||
Short: "Download one workflow file mapping into the local sandbox directory.",
|
||||
Args: cobra.ExactArgs(2),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunFileDownload(env, args[0], args[1], downloadTo)
|
||||
}),
|
||||
}
|
||||
download.Flags().StringVar(&downloadTo, "to", "", "Local directory for the downloaded file.")
|
||||
|
||||
cmd.AddCommand(upload, download, publicURL)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "config",
|
||||
Short: "Inspect or update Agent Soul-backed config assets through the Agent Stub.",
|
||||
}
|
||||
|
||||
manifest := &cobra.Command{
|
||||
Use: "manifest",
|
||||
Short: "Show the current visible Agent config manifest as JSON.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: withEnv(func(env *agentcli.Environment, _ []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigManifest(env)
|
||||
}),
|
||||
}
|
||||
|
||||
cmd.AddCommand(
|
||||
manifest,
|
||||
newConfigSkillsCommand(),
|
||||
newConfigSkillPullAliasCommand(),
|
||||
newConfigFilesCommand(),
|
||||
newConfigFilePullAliasCommand(),
|
||||
newConfigEnvCommand(),
|
||||
newConfigNoteCommand(),
|
||||
newConfigPromptCommand(),
|
||||
)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigSkillsPullCommand() *cobra.Command {
|
||||
var to string
|
||||
var jsonOutput bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "pull [NAME]...",
|
||||
Short: "Pull one or all visible config skills into ./.dify_conf/skills by default.",
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigSkillsPull(env, args, to, jsonOutput)
|
||||
}),
|
||||
}
|
||||
cmd.Flags().StringVar(&to, "to", "", "Local directory for pulled config skills.")
|
||||
cmd.Flags().BoolVar(&jsonOutput, "json", false, "Emit the pull result as JSON.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigSkillsCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "skills",
|
||||
Short: "Pull or update config skills through the Agent Stub.",
|
||||
}
|
||||
|
||||
push := &cobra.Command{
|
||||
Use: "push PATH...",
|
||||
Short: "Upload one or more local skill directories into the current config manifest.",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigSkillsPush(env, args)
|
||||
}),
|
||||
}
|
||||
|
||||
del := &cobra.Command{
|
||||
Use: "delete NAME...",
|
||||
Short: "Delete one or more config skills by name without touching local directories.",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigSkillsDelete(env, args)
|
||||
}),
|
||||
}
|
||||
|
||||
cmd.AddCommand(newConfigSkillsPullCommand(), push, del)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// newConfigSkillPullAliasCommand mirrors the hidden singular `config skill pull`
|
||||
// alias, which is intentionally pull-only.
|
||||
func newConfigSkillPullAliasCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "skill",
|
||||
Short: "Pull config skills through the Agent Stub.",
|
||||
Hidden: true,
|
||||
}
|
||||
cmd.AddCommand(newConfigSkillsPullCommand())
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigFilesPullCommand() *cobra.Command {
|
||||
var to string
|
||||
var jsonOutput bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "pull [NAME]...",
|
||||
Short: "Pull one or all visible config files into ./.dify_conf/files by default.",
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigFilesPull(env, args, to, jsonOutput)
|
||||
}),
|
||||
}
|
||||
cmd.Flags().StringVar(&to, "to", "", "Local directory for pulled config files.")
|
||||
cmd.Flags().BoolVar(&jsonOutput, "json", false, "Emit the pull result as JSON.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigFilesCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "files",
|
||||
Short: "Pull or update config files through the Agent Stub.",
|
||||
}
|
||||
|
||||
push := &cobra.Command{
|
||||
Use: "push PATH...",
|
||||
Short: "Upload one or more local files into the current config manifest.",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigFilesPush(env, args)
|
||||
}),
|
||||
}
|
||||
|
||||
del := &cobra.Command{
|
||||
Use: "delete NAME...",
|
||||
Short: "Delete one or more config files by name without touching local files.",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigFilesDelete(env, args)
|
||||
}),
|
||||
}
|
||||
|
||||
cmd.AddCommand(newConfigFilesPullCommand(), push, del)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// newConfigFilePullAliasCommand mirrors the hidden singular `config file pull`
|
||||
// alias, which is intentionally pull-only.
|
||||
func newConfigFilePullAliasCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "file",
|
||||
Short: "Pull config files through the Agent Stub.",
|
||||
Hidden: true,
|
||||
}
|
||||
cmd.AddCommand(newConfigFilesPullCommand())
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigEnvCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "env",
|
||||
Short: "Update config env variables visible to the current run.",
|
||||
}
|
||||
push := &cobra.Command{
|
||||
Use: "push PATH|-",
|
||||
Short: "Set or delete config env entries from one local dotenv file or stdin.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigEnvPush(env, args[0])
|
||||
}),
|
||||
}
|
||||
cmd.AddCommand(push)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigPromptCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "prompt",
|
||||
Short: "Pull or replace the raw system prompt, including mention markers.",
|
||||
}
|
||||
|
||||
var pullTo string
|
||||
pull := &cobra.Command{
|
||||
Use: "pull",
|
||||
Short: "Export the raw system prompt into ./.dify_conf/prompt.md by default.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: withEnv(func(env *agentcli.Environment, _ []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigPromptPull(env, pullTo)
|
||||
}),
|
||||
}
|
||||
pull.Flags().StringVar(&pullTo, "to", "", "Local UTF-8 text file path.")
|
||||
|
||||
push := &cobra.Command{
|
||||
Use: "push [PATH|-]",
|
||||
Short: "Replace the build-draft prompt from a UTF-8 file or stdin; empty text clears it.",
|
||||
Long: "Replace the build-draft system prompt from a UTF-8 file or stdin (-). " +
|
||||
"Defaults to ./.dify_conf/prompt.md and prints the saved prompt as JSON. " +
|
||||
"Empty text clears the prompt. " +
|
||||
"Only subsequent run requests built from this draft use the saved prompt; " +
|
||||
"already-built run requests keep their prompt.",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
localPath := ""
|
||||
if len(args) > 0 {
|
||||
localPath = args[0]
|
||||
}
|
||||
return agentcli.RunConfigPromptPush(env, localPath)
|
||||
}),
|
||||
}
|
||||
|
||||
cmd.AddCommand(pull, push)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newConfigNoteCommand() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "note",
|
||||
Short: "Pull or update the current config note.",
|
||||
}
|
||||
|
||||
var pullTo string
|
||||
pull := &cobra.Command{
|
||||
Use: "pull",
|
||||
Short: "Export the current config note into ./.dify_conf/note.md by default.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: withEnv(func(env *agentcli.Environment, _ []string, _ *cobra.Command) error {
|
||||
return agentcli.RunConfigNotePull(env, pullTo)
|
||||
}),
|
||||
}
|
||||
pull.Flags().StringVar(&pullTo, "to", "", "Local markdown file path.")
|
||||
|
||||
push := &cobra.Command{
|
||||
Use: "push [PATH|-]",
|
||||
Short: "Replace the current config note from one local text file or stdin.",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: withEnv(func(env *agentcli.Environment, args []string, _ *cobra.Command) error {
|
||||
localPath := ""
|
||||
if len(args) > 0 {
|
||||
localPath = args[0]
|
||||
}
|
||||
return agentcli.RunConfigNotePush(env, localPath)
|
||||
}),
|
||||
}
|
||||
|
||||
cmd.AddCommand(pull, push)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// --- connect dispatch helpers (mirror the Python CLI) ---
|
||||
|
||||
func runConnect(argv []string, jsonOutput bool) error {
|
||||
env, err := agentcli.ReadEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return agentcli.RunConnect(env, argv, jsonOutput)
|
||||
}
|
||||
|
||||
// parseConnectArgs strips a leading `--json` flag and an optional `--`
|
||||
// separator, matching Python's _parse_connect_args.
|
||||
func parseConnectArgs(argv []string) (bool, []string) {
|
||||
jsonOutput := false
|
||||
remaining := append([]string{}, argv...)
|
||||
if len(remaining) >= 1 && remaining[0] == "--json" {
|
||||
jsonOutput = true
|
||||
remaining = remaining[1:]
|
||||
}
|
||||
if len(remaining) >= 1 && remaining[0] == "--" {
|
||||
remaining = remaining[1:]
|
||||
}
|
||||
return jsonOutput, remaining
|
||||
}
|
||||
|
||||
// extractRootJSONFlag consumes a leading root `--json` flag only when it
|
||||
// precedes an unknown bare command, matching Python's _extract_root_json_flag.
|
||||
func extractRootJSONFlag(argv []string) (bool, []string) {
|
||||
if len(argv) >= 2 && argv[0] == "--json" && !isKnownRootCommand(argv[1]) {
|
||||
return true, argv[1:]
|
||||
}
|
||||
return false, argv
|
||||
}
|
||||
|
||||
func isUnknownBareCommand(argv []string) bool {
|
||||
if len(argv) == 0 {
|
||||
return false
|
||||
}
|
||||
first := argv[0]
|
||||
return !isKnownRootCommand(first) && !strings.HasPrefix(first, "-")
|
||||
}
|
||||
|
||||
func isKnownRootCommand(name string) bool {
|
||||
_, ok := knownRootCommands[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
func isHelpRequest(argv []string) bool {
|
||||
for _, v := range argv {
|
||||
if v == "--help" || v == "-h" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// withEnv adapts a command handler that needs a validated Agent Stub
|
||||
// environment into a cobra RunE, resolving the environment before dispatch.
|
||||
func withEnv(fn func(env *agentcli.Environment, args []string, cmd *cobra.Command) error) func(*cobra.Command, []string) error {
|
||||
return func(cmd *cobra.Command, args []string) error {
|
||||
env, err := agentcli.ReadEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(env, args, cmd)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// Tests that `--help` renders correctly for every command and subcommand in
|
||||
// the cobra tree, including the hidden singular `config skill|file` aliases.
|
||||
// These lock the installed command surface: each help output must show the
|
||||
// command's usage path, description, and expected flags/subcommands.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// executeHelp builds a fresh root command, runs it with the given args, and
|
||||
// returns the captured stdout/stderr. A fresh tree per call avoids leaking
|
||||
// parsed flag state between cases.
|
||||
func executeHelp(t *testing.T, args ...string) string {
|
||||
t.Helper()
|
||||
root := newRootCommand()
|
||||
var buf bytes.Buffer
|
||||
root.SetOut(&buf)
|
||||
root.SetErr(&buf)
|
||||
root.SetArgs(args)
|
||||
if err := root.Execute(); err != nil {
|
||||
t.Fatalf("execute %v: %v", args, err)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func TestCommandHelp(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "root",
|
||||
args: []string{"--help"},
|
||||
want: []string{"Usage:", "dify-agent", "config", "connect", "file"},
|
||||
},
|
||||
{
|
||||
name: "connect",
|
||||
args: []string{"connect", "--help"},
|
||||
want: []string{"dify-agent connect", "Establish one Agent Stub connection", "--json"},
|
||||
},
|
||||
{
|
||||
name: "file",
|
||||
args: []string{"file", "--help"},
|
||||
want: []string{"dify-agent file", "upload", "download"},
|
||||
},
|
||||
{
|
||||
name: "file upload",
|
||||
args: []string{"file", "upload", "--help"},
|
||||
want: []string{
|
||||
"dify-agent file upload",
|
||||
"Upload one sandbox-local file",
|
||||
"--no-download-link",
|
||||
"Skip creating a public download link after upload.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "file download",
|
||||
args: []string{"file", "download", "--help"},
|
||||
want: []string{"dify-agent file download", "Download one workflow file", "--to"},
|
||||
},
|
||||
{
|
||||
name: "file public-url",
|
||||
args: []string{"file", "public-url", "--help"},
|
||||
want: []string{"dify-agent file public-url", "Create a browser-visible download URL"},
|
||||
},
|
||||
{
|
||||
name: "config",
|
||||
args: []string{"config", "--help"},
|
||||
want: []string{"dify-agent config", "manifest", "skills", "files", "env", "note", "prompt"},
|
||||
},
|
||||
{
|
||||
name: "config manifest",
|
||||
args: []string{"config", "manifest", "--help"},
|
||||
want: []string{"dify-agent config manifest", "Show the current visible Agent config manifest"},
|
||||
},
|
||||
{
|
||||
name: "config skills",
|
||||
args: []string{"config", "skills", "--help"},
|
||||
want: []string{"dify-agent config skills", "pull", "push", "delete"},
|
||||
},
|
||||
{
|
||||
name: "config skills pull",
|
||||
args: []string{"config", "skills", "pull", "--help"},
|
||||
want: []string{"dify-agent config skills pull", "Pull one or all visible config skills", "--to", "--json"},
|
||||
},
|
||||
{
|
||||
name: "config skills push",
|
||||
args: []string{"config", "skills", "push", "--help"},
|
||||
want: []string{"dify-agent config skills push", "Upload one or more local skill directories"},
|
||||
},
|
||||
{
|
||||
name: "config skills delete",
|
||||
args: []string{"config", "skills", "delete", "--help"},
|
||||
want: []string{"dify-agent config skills delete", "Delete one or more config skills"},
|
||||
},
|
||||
{
|
||||
name: "config files",
|
||||
args: []string{"config", "files", "--help"},
|
||||
want: []string{"dify-agent config files", "pull", "push", "delete"},
|
||||
},
|
||||
{
|
||||
name: "config files pull",
|
||||
args: []string{"config", "files", "pull", "--help"},
|
||||
want: []string{"dify-agent config files pull", "Pull one or all visible config files", "--to", "--json"},
|
||||
},
|
||||
{
|
||||
name: "config files push",
|
||||
args: []string{"config", "files", "push", "--help"},
|
||||
want: []string{"dify-agent config files push", "Upload one or more local files"},
|
||||
},
|
||||
{
|
||||
name: "config files delete",
|
||||
args: []string{"config", "files", "delete", "--help"},
|
||||
want: []string{"dify-agent config files delete", "Delete one or more config files"},
|
||||
},
|
||||
{
|
||||
name: "config env",
|
||||
args: []string{"config", "env", "--help"},
|
||||
want: []string{"dify-agent config env", "push"},
|
||||
},
|
||||
{
|
||||
name: "config env push",
|
||||
args: []string{"config", "env", "push", "--help"},
|
||||
want: []string{"dify-agent config env push", "Set or delete config env entries"},
|
||||
},
|
||||
{
|
||||
name: "config note",
|
||||
args: []string{"config", "note", "--help"},
|
||||
want: []string{"dify-agent config note", "pull", "push"},
|
||||
},
|
||||
{
|
||||
name: "config note pull",
|
||||
args: []string{"config", "note", "pull", "--help"},
|
||||
want: []string{"dify-agent config note pull", "Export the current config note", "--to"},
|
||||
},
|
||||
{
|
||||
name: "config note push",
|
||||
args: []string{"config", "note", "push", "--help"},
|
||||
want: []string{"dify-agent config note push", "Replace the current config note"},
|
||||
},
|
||||
{
|
||||
name: "config prompt",
|
||||
args: []string{"config", "prompt", "--help"},
|
||||
want: []string{"dify-agent config prompt", "pull", "push"},
|
||||
},
|
||||
{
|
||||
name: "config prompt pull",
|
||||
args: []string{"config", "prompt", "pull", "--help"},
|
||||
want: []string{"dify-agent config prompt pull", "./.dify_conf/prompt.md", "--to"},
|
||||
},
|
||||
{
|
||||
name: "config prompt push",
|
||||
args: []string{"config", "prompt", "push", "--help"},
|
||||
want: []string{"dify-agent config prompt push [PATH|-]", "stdin", "already-built run requests keep their prompt"},
|
||||
},
|
||||
{
|
||||
name: "config skill pull (hidden alias)",
|
||||
args: []string{"config", "skill", "pull", "--help"},
|
||||
want: []string{"dify-agent config skill pull", "Pull one or all visible config skills", "--to", "--json"},
|
||||
},
|
||||
{
|
||||
name: "config file pull (hidden alias)",
|
||||
args: []string{"config", "file", "pull", "--help"},
|
||||
want: []string{"dify-agent config file pull", "Pull one or all visible config files", "--to", "--json"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
out := executeHelp(t, tc.args...)
|
||||
for _, want := range tc.want {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("help for %v missing %q\n--- help output ---\n%s", tc.args, want, out)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// findCommand walks the cobra tree by command name (the first word of Use),
|
||||
// returning nil when any path segment is missing.
|
||||
func findCommand(root *cobra.Command, path ...string) *cobra.Command {
|
||||
current := root
|
||||
for _, name := range path {
|
||||
var next *cobra.Command
|
||||
for _, child := range current.Commands() {
|
||||
if child.Name() == name {
|
||||
next = child
|
||||
break
|
||||
}
|
||||
}
|
||||
if next == nil {
|
||||
return nil
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// TestHiddenAliasesRemainHidden verifies the singular `config skill|file`
|
||||
// aliases exist (so their pull help still renders) but stay hidden from the
|
||||
// parent's command listing, matching the Python CLI's hidden aliases.
|
||||
func TestHiddenAliasesRemainHidden(t *testing.T) {
|
||||
root := newRootCommand()
|
||||
for _, alias := range [][]string{{"config", "skill"}, {"config", "file"}} {
|
||||
cmd := findCommand(root, alias...)
|
||||
if cmd == nil {
|
||||
t.Errorf("hidden alias %v not registered", alias)
|
||||
continue
|
||||
}
|
||||
if !cmd.Hidden {
|
||||
t.Errorf("alias %v must be hidden", alias)
|
||||
}
|
||||
if findCommand(cmd, "pull") == nil {
|
||||
t.Errorf("alias %v must expose a pull subcommand", alias)
|
||||
}
|
||||
}
|
||||
|
||||
// The hidden singular aliases must not appear in `config --help`.
|
||||
configHelp := executeHelp(t, "config", "--help")
|
||||
for _, unwanted := range []string{" skill ", " file "} {
|
||||
if strings.Contains(configHelp, unwanted) {
|
||||
t.Errorf("config help unexpectedly lists hidden alias %q\n--- help output ---\n%s", unwanted, configHelp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/agentcli"
|
||||
)
|
||||
|
||||
func runPromptCLI(t *testing.T, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
output, err := os.CreateTemp(t.TempDir(), "stdout-*")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := os.Stdout
|
||||
defer func() { os.Stdout = original }()
|
||||
os.Stdout = output
|
||||
runErr := runCLI(args)
|
||||
if err := output.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(output.Name())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(data), runErr
|
||||
}
|
||||
|
||||
func TestConfigPromptPull(t *testing.T) {
|
||||
for _, prompt := range []string{" 原文 🪷 [§skill:research:Research§]\r\n\n", ""} {
|
||||
for _, customPath := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("custom=%t/%q", customPath, prompt), func(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/agent-stub/config/prompt" {
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL)
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer token" {
|
||||
t.Error("missing Agent Stub authorization")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"prompt": prompt})
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv(agentcli.EnvAPIBaseURL, server.URL)
|
||||
t.Setenv(agentcli.EnvAuthJWE, "token")
|
||||
path := filepath.Join(".dify_conf", "prompt.md")
|
||||
args := []string{"config", "prompt", "pull"}
|
||||
if customPath {
|
||||
path = filepath.Join("custom", "prompt.txt")
|
||||
args = append(args, "--to", path)
|
||||
}
|
||||
output, err := runPromptCLI(t, args...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
absolutePath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if output != absolutePath+"\n" {
|
||||
t.Errorf("output = %q, want path %q", output, absolutePath)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || string(data) != prompt {
|
||||
t.Fatalf("saved prompt = %q, err = %v", data, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigPromptPush(t *testing.T) {
|
||||
for _, source := range []string{"default", "file", "stdin"} {
|
||||
for _, prompt := range []string{" 新提示 🪷 [§file:guide.md:Guide§]\r\n\n", ""} {
|
||||
t.Run(source+prompt, func(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
want := map[string]any{"prompt": prompt}
|
||||
var received map[string]any
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut || r.URL.Path != "/agent-stub/config/prompt" {
|
||||
t.Errorf("unexpected request: %s %s", r.Method, r.URL)
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer token" {
|
||||
t.Error("missing Agent Stub authorization")
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(received)
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv(agentcli.EnvAPIBaseURL, server.URL)
|
||||
t.Setenv(agentcli.EnvAuthJWE, "token")
|
||||
if err := os.MkdirAll(".dify_conf", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(".dify_conf", "prompt.md")
|
||||
if source != "default" {
|
||||
path = "input.txt"
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(prompt), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := []string{"config", "prompt", "push"}
|
||||
switch source {
|
||||
case "file":
|
||||
args = append(args, path)
|
||||
case "stdin":
|
||||
input, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = input.Close() }()
|
||||
original := os.Stdin
|
||||
defer func() { os.Stdin = original }()
|
||||
os.Stdin = input
|
||||
args = append(args, "-")
|
||||
}
|
||||
output, err := runPromptCLI(t, args...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(received, want) {
|
||||
t.Fatalf("request payload = %#v", received)
|
||||
}
|
||||
var response map[string]any
|
||||
if err := json.Unmarshal([]byte(output), &response); err != nil || !reflect.DeepEqual(response, want) {
|
||||
t.Fatalf("output = %q, err = %v", output, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigPromptPullRejectsBadResponsesWithoutOverwritingFile(t *testing.T) {
|
||||
for _, body := range []string{`{}`, `{"prompt":null}`, `{"prompt":123}`, `not-json`} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv(agentcli.EnvAPIBaseURL, server.URL)
|
||||
t.Setenv(agentcli.EnvAuthJWE, "token")
|
||||
path := filepath.Join(t.TempDir(), "prompt.md")
|
||||
if err := os.WriteFile(path, []byte("keep"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, err := runPromptCLI(t, "config", "prompt", "pull", "--to", path)
|
||||
if err == nil || output != "" {
|
||||
t.Fatalf("output = %q, err = %v; want failure without output", output, err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || string(data) != "keep" {
|
||||
t.Fatalf("existing file changed: %q, err = %v", data, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigPromptReportsFailures(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
var requestCount atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount.Add(1)
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(`{"detail":{"code":"config_not_writable","message":"read only"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv(agentcli.EnvAPIBaseURL, server.URL)
|
||||
t.Setenv(agentcli.EnvAuthJWE, "token")
|
||||
if err := os.WriteFile("prompt.md", []byte("keep"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"config", "prompt", "pull", "--to", "prompt.md"},
|
||||
{"config", "prompt", "push", "prompt.md"},
|
||||
} {
|
||||
output, err := runPromptCLI(t, args...)
|
||||
if err == nil || !strings.Contains(err.Error(), "HTTP 403") || output != "" {
|
||||
t.Errorf("%v: output = %q, err = %v", args, output, err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"config", "prompt", "push"}, // Missing default file must not clear the prompt.
|
||||
{"config", "prompt", "pull", "unexpected"},
|
||||
{"config", "prompt", "push", "one", "two"},
|
||||
} {
|
||||
if _, err := runPromptCLI(t, args...); err == nil {
|
||||
t.Errorf("%v: expected error", args)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile("invalid.txt", []byte{0xff}, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := runPromptCLI(t, "config", "prompt", "push", "invalid.txt"); err == nil || !strings.Contains(err.Error(), "UTF-8") {
|
||||
t.Errorf("invalid text error = %v", err)
|
||||
}
|
||||
if requestCount.Load() != 2 {
|
||||
t.Errorf("unexpected requests for invalid input: %d", requestCount.Load())
|
||||
}
|
||||
data, err := os.ReadFile("prompt.md")
|
||||
if err != nil || string(data) != "keep" {
|
||||
t.Fatalf("existing file changed: %q, err = %v", data, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// shellctl-runner-exit persists a drained runner exit into the shellctl SQLite DB.
|
||||
// It runs after the tmux output pipe reaches EOF and output.log is fully flushed.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/cmdutil"
|
||||
runnerexit "github.com/langgenius/dify/dify-agent-runtime/internal/runner_exit"
|
||||
)
|
||||
|
||||
func main() {
|
||||
stateDir := flag.String("state-dir", "", "shellctl state directory")
|
||||
jobID := flag.String("job-id", "", "job identifier")
|
||||
exitCode := flag.Int("exit-code", 0, "runner process exit code")
|
||||
endedAt := flag.String("ended-at", "", "ISO-8601 ended_at timestamp")
|
||||
busyTimeoutMs := flag.Int("sqlite-busy-timeout-ms", 5000, "SQLite busy timeout in milliseconds")
|
||||
flag.Parse()
|
||||
|
||||
if *stateDir == "" || *jobID == "" || *endedAt == "" {
|
||||
cmdutil.HandleError(fmt.Errorf("missing flags"), 1, "--state-dir, --job-id, and --ended-at are required")
|
||||
}
|
||||
|
||||
cmdutil.HandleError(
|
||||
runnerexit.RecordRunnerExit(*stateDir, *jobID, *exitCode, *endedAt, *busyTimeoutMs),
|
||||
1, "record runner exit",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
// shellctl-runner is the Go replacement for the previously generated bash+python
|
||||
// runner script. It is invoked by tmux as:
|
||||
//
|
||||
// shellctl-runner <job_dir> <job_id> <cwd> [pty|stdio]
|
||||
//
|
||||
// The binary operates in two process roles:
|
||||
//
|
||||
// 1. Parent mode (default): waits for start-gate, loads env, forks child,
|
||||
// waits for exit, writes exit artifacts.
|
||||
// 2. Child mode (--exec flag): applies Landlock restrictions, then exec's
|
||||
// the user script.
|
||||
//
|
||||
// This eliminates the bash/python dependency chain and integrates Landlock
|
||||
// directly.
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/cmdutil"
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/envvar"
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/landlock"
|
||||
)
|
||||
|
||||
// startGatePollInterval is how often the parent runner checks for the
|
||||
// start-gate handshake file. It is a cheap local stat on the same path the
|
||||
// server has just written, so a fine interval keeps per-job startup latency
|
||||
// low without meaningful cost.
|
||||
const startGatePollInterval = 5 * time.Millisecond
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "--exec" {
|
||||
childMode()
|
||||
return
|
||||
}
|
||||
parentMode()
|
||||
}
|
||||
|
||||
// parentMode is the entry point when called by tmux.
|
||||
// Args: shellctl-runner <job_dir> <job_id> <cwd> [pty|stdio]
|
||||
func parentMode() {
|
||||
if len(os.Args) < 4 {
|
||||
cmdutil.HandleError(fmt.Errorf("bad args"), 125, "usage: shellctl-runner <job_dir> <job_id> <cwd> [pty|stdio]")
|
||||
}
|
||||
|
||||
jobDir := os.Args[1]
|
||||
// jobID := os.Args[2] // unused in parent but passed for compat
|
||||
cwd := os.Args[3]
|
||||
modeRaw := ""
|
||||
if len(os.Args) >= 5 {
|
||||
modeRaw = os.Args[4]
|
||||
}
|
||||
mode, err := jobmode.Parse(modeRaw)
|
||||
cmdutil.HandleError(err, 125, "parse job mode")
|
||||
|
||||
scriptPath := filepath.Join(jobDir, "script")
|
||||
envPath := filepath.Join(jobDir, ".job-env.json")
|
||||
startGate := filepath.Join(jobDir, "start-gate")
|
||||
|
||||
// Wait for start-gate.
|
||||
for {
|
||||
if _, err := os.Stat(startGate); err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(startGatePollInterval)
|
||||
}
|
||||
|
||||
// Load environment overlay from JSON.
|
||||
env := os.Environ()
|
||||
// Remove internal shellctl vars from inherited env.
|
||||
env = filterEnv(env, []string{
|
||||
"TMUX",
|
||||
"SHELLCTL_STATE_DIR",
|
||||
"SHELLCTL_RUNTIME_DIR",
|
||||
"SHELLCTL_TMUX_SOCKET",
|
||||
"SHELLCTL_RUNNER",
|
||||
"SHELLCTL_AUTH_TOKEN",
|
||||
})
|
||||
|
||||
envOverlay := loadEnvJSON(envPath)
|
||||
env = mergeEnv(env, envOverlay)
|
||||
env = mergeEnv(env, map[string]string{
|
||||
"TMPDIR": cwd,
|
||||
"TMP": cwd,
|
||||
"TEMP": cwd,
|
||||
})
|
||||
|
||||
// Ensure HOME exists.
|
||||
home := envGet(env, "HOME")
|
||||
if home != "" {
|
||||
cmdutil.HandleError(os.MkdirAll(home, 0755), 125, "mkdir HOME %s", home)
|
||||
}
|
||||
|
||||
// Determine if path isolation is enabled.
|
||||
enableIsolation := envvar.PathIsolationEnabled()
|
||||
|
||||
// Build child command: re-exec self in --exec mode.
|
||||
self, _ := os.Executable()
|
||||
childArgs := []string{"--exec", scriptPath, cwd}
|
||||
if enableIsolation {
|
||||
childArgs = append([]string{"--exec", "--landlock"}, childArgs[1:]...)
|
||||
}
|
||||
|
||||
cmd := exec.Command(self, childArgs...)
|
||||
cmd.Env = env
|
||||
cmd.Dir = cwd
|
||||
|
||||
// Forward signals to child.
|
||||
sigCh := make(chan os.Signal, 1)
|
||||
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
|
||||
go func() {
|
||||
for sig := range sigCh {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Signal(sig)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
exitCode := runCommandAndRecordExit(cmd, jobDir, mode)
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
|
||||
// runCommandAndRecordExit publishes the existing runner artifacts after the
|
||||
// child path returns. In stdio mode that return includes both stream drains;
|
||||
// PTY mode still relies on its separate pipe-drain finalizer.
|
||||
func runCommandAndRecordExit(cmd *exec.Cmd, jobDir string, mode jobmode.Mode) int {
|
||||
var exitCode int
|
||||
if mode == jobmode.Stdio {
|
||||
exitCode = runStdio(cmd, jobDir)
|
||||
} else {
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
exitCode = runPTY(cmd)
|
||||
}
|
||||
|
||||
endedAt := time.Now().UTC().Format("2006-01-02T15:04:05Z")
|
||||
|
||||
writeAtomic(filepath.Join(jobDir, "runner-exit-code"), fmt.Sprintf("%d", exitCode))
|
||||
writeAtomic(filepath.Join(jobDir, "runner-ended-at"), endedAt)
|
||||
return exitCode
|
||||
}
|
||||
|
||||
func runPTY(cmd *exec.Cmd) int {
|
||||
return commandExitCode(cmd.Run())
|
||||
}
|
||||
|
||||
// runStdio captures stdout and stderr independently and does not return until
|
||||
// both streams reach EOF and their files are closed.
|
||||
func runStdio(cmd *exec.Cmd, jobDir string) int {
|
||||
outputFile, err := openCaptureFile(filepath.Join(jobDir, "output.log"))
|
||||
if err != nil {
|
||||
return runnerError("open stdout capture", err)
|
||||
}
|
||||
stderrFile, err := openCaptureFile(filepath.Join(jobDir, "stderr.log"))
|
||||
if err != nil {
|
||||
_ = outputFile.Close()
|
||||
return runnerError("open stderr capture", err)
|
||||
}
|
||||
|
||||
stdoutReader, stdoutWriter, err := os.Pipe()
|
||||
if err != nil {
|
||||
_ = outputFile.Close()
|
||||
_ = stderrFile.Close()
|
||||
return runnerError("create stdout pipe", err)
|
||||
}
|
||||
stderrReader, stderrWriter, err := os.Pipe()
|
||||
if err != nil {
|
||||
_ = stdoutReader.Close()
|
||||
_ = stdoutWriter.Close()
|
||||
_ = outputFile.Close()
|
||||
_ = stderrFile.Close()
|
||||
return runnerError("create stderr pipe", err)
|
||||
}
|
||||
stdinFile, err := os.Open(os.DevNull)
|
||||
if err != nil {
|
||||
_ = stdoutReader.Close()
|
||||
_ = stdoutWriter.Close()
|
||||
_ = stderrReader.Close()
|
||||
_ = stderrWriter.Close()
|
||||
_ = outputFile.Close()
|
||||
_ = stderrFile.Close()
|
||||
return runnerError("open stdin", err)
|
||||
}
|
||||
|
||||
cmd.Stdin = stdinFile
|
||||
cmd.Stdout = stdoutWriter
|
||||
cmd.Stderr = stderrWriter
|
||||
|
||||
var captureErrors []error
|
||||
var captureErrorsMu sync.Mutex
|
||||
recordError := func(operation string, err error) {
|
||||
if err != nil {
|
||||
captureErrorsMu.Lock()
|
||||
captureErrors = append(captureErrors, fmt.Errorf("%s: %w", operation, err))
|
||||
captureErrorsMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
var drains sync.WaitGroup
|
||||
drains.Add(2)
|
||||
go func() {
|
||||
defer drains.Done()
|
||||
_, copyErr := io.Copy(outputFile, stdoutReader)
|
||||
recordError("copy stdout", copyErr)
|
||||
recordError("close stdout reader", stdoutReader.Close())
|
||||
}()
|
||||
go func() {
|
||||
defer drains.Done()
|
||||
_, copyErr := io.Copy(stderrFile, stderrReader)
|
||||
recordError("copy stderr", copyErr)
|
||||
recordError("close stderr reader", stderrReader.Close())
|
||||
}()
|
||||
|
||||
startErr := cmd.Start()
|
||||
recordError("close stdout writer", stdoutWriter.Close())
|
||||
recordError("close stderr writer", stderrWriter.Close())
|
||||
recordError("close stdin", stdinFile.Close())
|
||||
|
||||
var waitErr error
|
||||
if startErr != nil {
|
||||
recordError("start child", startErr)
|
||||
} else {
|
||||
waitErr = cmd.Wait()
|
||||
}
|
||||
|
||||
// Descendants may retain either write end after the direct child exits. In
|
||||
// that case the runner intentionally remains alive until both reach EOF.
|
||||
drains.Wait()
|
||||
recordError("close stdout capture", outputFile.Close())
|
||||
recordError("close stderr capture", stderrFile.Close())
|
||||
|
||||
for _, captureErr := range captureErrors {
|
||||
fmt.Fprintf(os.Stderr, "shellctl-runner: %v\n", captureErr)
|
||||
}
|
||||
if len(captureErrors) > 0 {
|
||||
return 125
|
||||
}
|
||||
return commandExitCode(waitErr)
|
||||
}
|
||||
|
||||
func openCaptureFile(path string) (*os.File, error) {
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := file.Chmod(0600); err != nil {
|
||||
_ = file.Close()
|
||||
return nil, err
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func runnerError(operation string, err error) int {
|
||||
fmt.Fprintf(os.Stderr, "shellctl-runner: %s: %v\n", operation, err)
|
||||
return 125
|
||||
}
|
||||
|
||||
func commandExitCode(err error) int {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
return exitErr.ExitCode()
|
||||
}
|
||||
return 125
|
||||
}
|
||||
|
||||
// childMode applies Landlock (if --landlock flag) and exec's the user script.
|
||||
// Args: shellctl-runner --exec [--landlock] <script_path> <cwd>
|
||||
func childMode() {
|
||||
args := os.Args[2:] // skip program name and "--exec"
|
||||
applyLandlockFlag := false
|
||||
|
||||
if len(args) > 0 && args[0] == "--landlock" {
|
||||
applyLandlockFlag = true
|
||||
args = args[1:]
|
||||
}
|
||||
|
||||
if len(args) < 2 {
|
||||
cmdutil.HandleError(fmt.Errorf("bad args"), 125, "--exec: missing script_path and cwd")
|
||||
}
|
||||
|
||||
scriptPath := args[0]
|
||||
cwd := args[1]
|
||||
|
||||
// chdir
|
||||
cmdutil.HandleError(os.Chdir(cwd), 111, "chdir %s", cwd)
|
||||
|
||||
// Determine argv for exec.
|
||||
argv := buildExecArgv(scriptPath)
|
||||
|
||||
// Resolve binary before Landlock (PATH search).
|
||||
binary, err := exec.LookPath(argv[0])
|
||||
cmdutil.HandleError(err, 127, "%s: not found", argv[0])
|
||||
|
||||
// Apply Landlock if requested.
|
||||
if applyLandlockFlag {
|
||||
home := os.Getenv("HOME")
|
||||
jobDir := filepath.Dir(scriptPath)
|
||||
cfg := landlock.ConfigFromEnv(home, cwd, jobDir)
|
||||
cmdutil.HandleError(landlock.Restrict(cfg), 125, "apply Landlock restrictions")
|
||||
}
|
||||
|
||||
// exec replaces the current process.
|
||||
cmdutil.HandleError(syscall.Exec(binary, argv, os.Environ()), 126, "exec %s", binary)
|
||||
}
|
||||
|
||||
// buildExecArgv determines whether the script has a shebang or needs sh.
|
||||
func buildExecArgv(scriptPath string) []string {
|
||||
f, err := os.Open(scriptPath)
|
||||
if err != nil {
|
||||
return []string{"sh", scriptPath}
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
|
||||
buf := make([]byte, 2)
|
||||
n, _ := f.Read(buf)
|
||||
if n == 2 && string(buf) == "#!" {
|
||||
// Has shebang — make executable and run directly.
|
||||
_ = os.Chmod(scriptPath, 0755)
|
||||
return []string{scriptPath}
|
||||
}
|
||||
return []string{"sh", scriptPath}
|
||||
}
|
||||
|
||||
// loadEnvJSON reads a JSON object from path and returns key=value pairs.
|
||||
func loadEnvJSON(path string) map[string]string {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
cmdutil.HandleError(err, 125, "read env json %s", path)
|
||||
}
|
||||
var m map[string]string
|
||||
if err := json.Unmarshal(data, &m); err != nil {
|
||||
cmdutil.HandleError(err, 125, "parse env json %s", path)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// filterEnv removes entries with the given key prefixes from env.
|
||||
func filterEnv(env []string, remove []string) []string {
|
||||
result := env[:0]
|
||||
for _, e := range env {
|
||||
skip := false
|
||||
for _, r := range remove {
|
||||
if strings.HasPrefix(e, r+"=") {
|
||||
skip = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !skip {
|
||||
result = append(result, e)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// mergeEnv applies overlay key=value pairs onto the env slice.
|
||||
func mergeEnv(env []string, overlay map[string]string) []string {
|
||||
for k, v := range overlay {
|
||||
found := false
|
||||
prefix := k + "="
|
||||
for i, e := range env {
|
||||
if strings.HasPrefix(e, prefix) {
|
||||
env[i] = prefix + v
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
env = append(env, prefix+v)
|
||||
}
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// envGet retrieves a value from a []string env slice.
|
||||
func envGet(env []string, key string) string {
|
||||
prefix := key + "="
|
||||
for _, e := range env {
|
||||
if strings.HasPrefix(e, prefix) {
|
||||
return e[len(prefix):]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// writeAtomic writes value to dest via a temp file + rename.
|
||||
func writeAtomic(dest, value string) {
|
||||
tmp := fmt.Sprintf("%s.tmp.%d", dest, os.Getpid())
|
||||
if err := os.WriteFile(tmp, []byte(value+"\n"), 0644); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "shellctl-runner: write %s: %v\n", tmp, err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, dest); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "shellctl-runner: rename %s -> %s: %v\n", tmp, dest, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
|
||||
)
|
||||
|
||||
func TestRunnerLandlockFailureDoesNotExecuteScript(test *testing.T) {
|
||||
runnerPath := filepath.Join(test.TempDir(), "shellctl-runner")
|
||||
build := exec.Command("go", "build", "-o", runnerPath, ".")
|
||||
if output, err := build.CombinedOutput(); err != nil {
|
||||
test.Fatalf("build runner: %v\n%s", err, output)
|
||||
}
|
||||
|
||||
for _, mode := range []string{"pty", "stdio"} {
|
||||
for _, isolation := range []string{"true", "false"} {
|
||||
test.Run(mode+"/isolation="+isolation, func(test *testing.T) {
|
||||
jobDir := test.TempDir()
|
||||
invalidDirectory := filepath.Join(jobDir, "regular-file")
|
||||
for name, content := range map[string]string{
|
||||
"regular-file": "not a directory",
|
||||
"script": "printf executed > script-executed",
|
||||
"start-gate": "",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(jobDir, name), []byte(content), 0600); err != nil {
|
||||
test.Fatal(err)
|
||||
}
|
||||
}
|
||||
cmd := exec.Command(runnerPath, jobDir, "test-job", jobDir, mode)
|
||||
cmd.Env = mergeEnv(os.Environ(), map[string]string{
|
||||
"HOME": jobDir,
|
||||
"SHELLCTL_ENABLE_PATH_ISOLATION": isolation,
|
||||
"SHELLCTL_LANDLOCK_RW_PATHS": invalidDirectory,
|
||||
"SHELLCTL_LANDLOCK_RO_PATHS": "/usr,/bin,/lib,/lib64",
|
||||
"SHELLCTL_LANDLOCK_RW_DEV_PATHS": "/dev/null",
|
||||
})
|
||||
output, err := cmd.CombinedOutput()
|
||||
wantExitCode := 125
|
||||
if isolation == "false" {
|
||||
wantExitCode = 0
|
||||
}
|
||||
if got := commandExitCode(err); got != wantExitCode {
|
||||
test.Fatalf("exit code = %d, want %d: %s", got, wantExitCode, output)
|
||||
}
|
||||
exitArtifact, err := os.ReadFile(filepath.Join(jobDir, "runner-exit-code"))
|
||||
if err != nil || strings.TrimSpace(string(exitArtifact)) != strconv.Itoa(wantExitCode) {
|
||||
test.Fatalf("exit artifact = %q, err = %v", exitArtifact, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(jobDir, "runner-ended-at")); err != nil {
|
||||
test.Fatal(err)
|
||||
}
|
||||
_, markerErr := os.Stat(filepath.Join(jobDir, "script-executed"))
|
||||
if isolation == "true" {
|
||||
if !os.IsNotExist(markerErr) {
|
||||
test.Fatalf("user script side effect exists: %v", markerErr)
|
||||
}
|
||||
if mode == "stdio" {
|
||||
output, err = os.ReadFile(filepath.Join(jobDir, "stderr.log"))
|
||||
if err != nil {
|
||||
test.Fatal(err)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(string(output), "apply Landlock restrictions") {
|
||||
test.Fatalf("missing Landlock diagnostic: %s", output)
|
||||
}
|
||||
} else if markerErr != nil {
|
||||
test.Fatalf("disabled isolation did not execute script: %v", markerErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStdioCapturesCompleteSeparatedStreams(t *testing.T) {
|
||||
jobDir := t.TempDir()
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestStdioHelperProcess$")
|
||||
cmd.Env = append(os.Environ(), "SHELLCTL_STDIO_HELPER=large-output")
|
||||
|
||||
if exitCode := runStdio(cmd, jobDir); exitCode != 0 {
|
||||
t.Fatalf("runStdio exit code = %d, want 0", exitCode)
|
||||
}
|
||||
|
||||
wantStdout := bytes.Repeat([]byte("stdout-payload\n"), 16*1024)
|
||||
wantStderr := bytes.Repeat([]byte("stderr-payload\n"), 16*1024)
|
||||
gotStdout, err := os.ReadFile(filepath.Join(jobDir, "output.log"))
|
||||
if err != nil {
|
||||
t.Fatalf("read output.log: %v", err)
|
||||
}
|
||||
gotStderr, err := os.ReadFile(filepath.Join(jobDir, "stderr.log"))
|
||||
if err != nil {
|
||||
t.Fatalf("read stderr.log: %v", err)
|
||||
}
|
||||
if !bytes.Equal(gotStdout, wantStdout) {
|
||||
t.Errorf("stdout capture length = %d, want %d", len(gotStdout), len(wantStdout))
|
||||
}
|
||||
if !bytes.Equal(gotStderr, wantStderr) {
|
||||
t.Errorf("stderr capture length = %d, want %d", len(gotStderr), len(wantStderr))
|
||||
}
|
||||
for _, name := range []string{"output.log", "stderr.log"} {
|
||||
info, err := os.Stat(filepath.Join(jobDir, name))
|
||||
if err != nil {
|
||||
t.Fatalf("stat %s: %v", name, err)
|
||||
}
|
||||
if got := info.Mode().Perm(); got != 0600 {
|
||||
t.Errorf("%s permissions = %#o, want 0600", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStdioUsesNonTTYStreams(t *testing.T) {
|
||||
jobDir := t.TempDir()
|
||||
cmd := exec.Command("sh", "-c", `if [ -t 0 ] || [ -t 1 ] || [ -t 2 ]; then exit 1; fi; printf 'stdout-only'; printf 'warning' >&2`)
|
||||
|
||||
if exitCode := runStdio(cmd, jobDir); exitCode != 0 {
|
||||
t.Fatalf("runStdio exit code = %d, want 0", exitCode)
|
||||
}
|
||||
stdout, err := os.ReadFile(filepath.Join(jobDir, "output.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stderr, err := os.ReadFile(filepath.Join(jobDir, "stderr.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(stdout) != "stdout-only" {
|
||||
t.Errorf("stdout = %q, want stdout-only", stdout)
|
||||
}
|
||||
if string(stderr) != "warning" {
|
||||
t.Errorf("stderr = %q, want warning", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStdioWaitsForBothDescendantStreamsBeforePublishingExit(t *testing.T) {
|
||||
jobDir := t.TempDir()
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestStdioHelperProcess$")
|
||||
cmd.Env = mergeEnv(os.Environ(), map[string]string{
|
||||
"SHELLCTL_STDIO_HELPER": "spawn-descendants",
|
||||
"SHELLCTL_STDIO_JOB_DIR": jobDir,
|
||||
})
|
||||
done := make(chan struct{})
|
||||
var exitCode int
|
||||
go func() {
|
||||
exitCode = runCommandAndRecordExit(cmd, jobDir, jobmode.Stdio)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
stdoutRelease := filepath.Join(jobDir, "release-stdout")
|
||||
stderrRelease := filepath.Join(jobDir, "release-stderr")
|
||||
t.Cleanup(func() {
|
||||
_ = os.WriteFile(stdoutRelease, nil, 0600)
|
||||
_ = os.WriteFile(stderrRelease, nil, 0600)
|
||||
for _, name := range []string{"stdout-closed", "stderr-closed"} {
|
||||
if !waitForPath(filepath.Join(jobDir, name), 5*time.Second) {
|
||||
t.Errorf("cleanup timed out waiting for %s", name)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("cleanup timed out waiting for runner completion")
|
||||
}
|
||||
})
|
||||
|
||||
waitForTestFile(t, filepath.Join(jobDir, "direct-child-exited"))
|
||||
assertRunnerRemainsIncomplete(t, done)
|
||||
assertExitArtifactsAbsent(t, jobDir)
|
||||
|
||||
if err := os.WriteFile(stdoutRelease, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitForTestFile(t, filepath.Join(jobDir, "stdout-closed"))
|
||||
assertRunnerRemainsIncomplete(t, done)
|
||||
assertExitArtifactsAbsent(t, jobDir)
|
||||
|
||||
if err := os.WriteFile(stderrRelease, nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitForTestFile(t, filepath.Join(jobDir, "stderr-closed"))
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
if exitCode != 0 {
|
||||
t.Fatalf("exit code = %d, want 0", exitCode)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("runner did not complete after both descendant streams reached EOF")
|
||||
}
|
||||
waitForTestFile(t, filepath.Join(jobDir, "runner-exit-code"))
|
||||
waitForTestFile(t, filepath.Join(jobDir, "runner-ended-at"))
|
||||
|
||||
stdout, err := os.ReadFile(filepath.Join(jobDir, "output.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stderr, err := os.ReadFile(filepath.Join(jobDir, "stderr.log"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(stdout) != "stdout-tail" {
|
||||
t.Errorf("stdout = %q, want stdout-tail", stdout)
|
||||
}
|
||||
if string(stderr) != "stderr-tail" {
|
||||
t.Errorf("stderr = %q, want stderr-tail", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStdioPreservesNonZeroExitCode(t *testing.T) {
|
||||
jobDir := t.TempDir()
|
||||
cmd := exec.Command("sh", "-c", "exit 23")
|
||||
|
||||
if exitCode := runCommandAndRecordExit(cmd, jobDir, jobmode.Stdio); exitCode != 23 {
|
||||
t.Fatalf("exit code = %d, want 23", exitCode)
|
||||
}
|
||||
exitCodeArtifact, err := os.ReadFile(filepath.Join(jobDir, "runner-exit-code"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(exitCodeArtifact) != "23\n" {
|
||||
t.Errorf("runner-exit-code = %q, want 23", exitCodeArtifact)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdioHelperProcess(t *testing.T) {
|
||||
switch os.Getenv("SHELLCTL_STDIO_HELPER") {
|
||||
case "":
|
||||
return
|
||||
case "large-output":
|
||||
stdout := bytes.Repeat([]byte("stdout-payload\n"), 16*1024)
|
||||
stderr := bytes.Repeat([]byte("stderr-payload\n"), 16*1024)
|
||||
_, _ = os.Stdout.Write(stdout)
|
||||
_, _ = os.Stderr.Write(stderr)
|
||||
os.Exit(0)
|
||||
case "spawn-descendants":
|
||||
spawnStdioDescendants()
|
||||
case "hold-stdout", "hold-stderr":
|
||||
holdStdioStream(os.Getenv("SHELLCTL_STDIO_HELPER"))
|
||||
default:
|
||||
os.Exit(125)
|
||||
}
|
||||
}
|
||||
|
||||
func spawnStdioDescendants() {
|
||||
jobDir := os.Getenv("SHELLCTL_STDIO_JOB_DIR")
|
||||
parentPID := strconv.Itoa(os.Getpid())
|
||||
stdoutHolder := exec.Command(os.Args[0], "-test.run=^TestStdioHelperProcess$")
|
||||
stdoutHolder.Env = mergeEnv(os.Environ(), map[string]string{
|
||||
"SHELLCTL_STDIO_HELPER": "hold-stdout",
|
||||
"SHELLCTL_STDIO_JOB_DIR": jobDir,
|
||||
"SHELLCTL_STDIO_PARENT_PID": parentPID,
|
||||
})
|
||||
stdoutHolder.Stdout = os.Stdout
|
||||
if err := stdoutHolder.Start(); err != nil {
|
||||
os.Exit(125)
|
||||
}
|
||||
|
||||
stderrHolder := exec.Command(os.Args[0], "-test.run=^TestStdioHelperProcess$")
|
||||
stderrHolder.Env = mergeEnv(os.Environ(), map[string]string{
|
||||
"SHELLCTL_STDIO_HELPER": "hold-stderr",
|
||||
"SHELLCTL_STDIO_JOB_DIR": jobDir,
|
||||
})
|
||||
stderrHolder.Stderr = os.Stderr
|
||||
if err := stderrHolder.Start(); err != nil {
|
||||
os.Exit(125)
|
||||
}
|
||||
|
||||
if !waitForPath(filepath.Join(jobDir, "stdout-ready"), 5*time.Second) ||
|
||||
!waitForPath(filepath.Join(jobDir, "stderr-ready"), 5*time.Second) {
|
||||
os.Exit(125)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func holdStdioStream(mode string) {
|
||||
jobDir := os.Getenv("SHELLCTL_STDIO_JOB_DIR")
|
||||
streamName := mode[len("hold-"):]
|
||||
if err := os.WriteFile(filepath.Join(jobDir, streamName+"-ready"), nil, 0600); err != nil {
|
||||
os.Exit(125)
|
||||
}
|
||||
if mode == "hold-stdout" {
|
||||
parentPID, err := strconv.Atoi(os.Getenv("SHELLCTL_STDIO_PARENT_PID"))
|
||||
if err != nil || !waitForProcessExit(parentPID, 5*time.Second) {
|
||||
os.Exit(125)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(jobDir, "direct-child-exited"), nil, 0600); err != nil {
|
||||
os.Exit(125)
|
||||
}
|
||||
}
|
||||
|
||||
if !waitForPath(filepath.Join(jobDir, "release-"+streamName), 5*time.Second) {
|
||||
os.Exit(125)
|
||||
}
|
||||
if mode == "hold-stdout" {
|
||||
_, _ = os.Stdout.WriteString("stdout-tail")
|
||||
_ = os.Stdout.Close()
|
||||
} else {
|
||||
_, _ = os.Stderr.WriteString("stderr-tail")
|
||||
_ = os.Stderr.Close()
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(jobDir, streamName+"-closed"), nil, 0600); err != nil {
|
||||
os.Exit(125)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func waitForProcessExit(pid int, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if err := syscall.Kill(pid, 0); err == syscall.ESRCH {
|
||||
return true
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func waitForPath(path string, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return true
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func waitForTestFile(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if !waitForPath(path, 5*time.Second) {
|
||||
t.Fatalf("timed out waiting for %s", filepath.Base(path))
|
||||
}
|
||||
}
|
||||
|
||||
func assertRunnerRemainsIncomplete(t *testing.T, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
timer := time.NewTimer(100 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("runner completed before both streams reached EOF")
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
|
||||
func assertExitArtifactsAbsent(t *testing.T, jobDir string) {
|
||||
t.Helper()
|
||||
for _, name := range []string{"runner-exit-code", "runner-ended-at"} {
|
||||
if _, err := os.Stat(filepath.Join(jobDir, name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("%s became visible before both streams reached EOF: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// shellctl-sanitize-pty is a stdin→stdout PTY sanitizer used by tmux pipe-pane.
|
||||
// It strips ANSI escape sequences, normalizes carriage-return progress lines,
|
||||
// and performs incremental UTF-8 decoding.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"os"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/cmdutil"
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/sanitize"
|
||||
)
|
||||
|
||||
func main() {
|
||||
readyFile := flag.String("ready-file", "", "path to touch before reading stdin")
|
||||
flag.Parse()
|
||||
|
||||
cmdutil.HandleError(sanitize.Run(*readyFile, os.Stdin, os.Stdout), 1, "sanitize-pty")
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// shellctl is the main server binary that exposes a REST API for managing
|
||||
// tmux-backed shell jobs inside a sandbox container.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/langgenius/dify/dify-agent-runtime/internal/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "shellctl: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
// Parse CLI flags
|
||||
serveCmd := flag.NewFlagSet("serve", flag.ExitOnError)
|
||||
listen := serveCmd.String("listen", "", "address to listen on (host:port)")
|
||||
stateDir := serveCmd.String("state-dir", "", "state directory path")
|
||||
token := serveCmd.String("token", "", "bearer auth token")
|
||||
requireAuthToken := serveCmd.Bool("require-auth-token", false, "require a nonblank bearer auth token")
|
||||
|
||||
if len(os.Args) < 2 || os.Args[1] != "serve" {
|
||||
fmt.Fprintf(os.Stderr, "Usage: shellctl serve [flags]\n")
|
||||
return nil
|
||||
}
|
||||
if err := serveCmd.Parse(os.Args[2:]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Build config
|
||||
config, err := server.DefaultConfig()
|
||||
if err != nil {
|
||||
return fmt.Errorf("config: %w", err)
|
||||
}
|
||||
if *listen != "" {
|
||||
config.Listen = *listen
|
||||
}
|
||||
if *stateDir != "" {
|
||||
config.StateDir = *stateDir
|
||||
}
|
||||
if *token != "" {
|
||||
config.AuthToken = *token
|
||||
}
|
||||
if *requireAuthToken && strings.TrimSpace(config.AuthToken) == "" {
|
||||
return fmt.Errorf("auth token is required: set SHELLCTL_AUTH_TOKEN or --token")
|
||||
}
|
||||
|
||||
// Initialize service
|
||||
svc := server.NewService(config)
|
||||
if err := svc.Initialize(); err != nil {
|
||||
return fmt.Errorf("initialize: %w", err)
|
||||
}
|
||||
defer svc.Shutdown()
|
||||
|
||||
svc.StartBackgroundGC()
|
||||
svc.StartBackgroundPipeMonitor()
|
||||
|
||||
// Create HTTP server
|
||||
handler := server.Handler(svc, config)
|
||||
srv := &http.Server{
|
||||
Addr: config.Listen,
|
||||
Handler: handler,
|
||||
ReadTimeout: 0, // Long-poll requires no read timeout
|
||||
WriteTimeout: 0,
|
||||
}
|
||||
|
||||
// Graceful shutdown on signal
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
log.Println("shutting down...")
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(shutdownCtx)
|
||||
}()
|
||||
|
||||
log.Printf("shellctl serving on %s", config.Listen)
|
||||
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestServeAuthTokenValidationBeforeInitialization(test *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
envToken *string
|
||||
flags []string
|
||||
wantAuthErr bool
|
||||
}{
|
||||
{name: "unset", flags: []string{"--require-auth-token"}, wantAuthErr: true},
|
||||
{name: "empty", envToken: new(""), flags: []string{"--require-auth-token"}, wantAuthErr: true},
|
||||
{name: "whitespace", envToken: new(" \t\n"), flags: []string{"--require-auth-token"}, wantAuthErr: true},
|
||||
{name: "environment", envToken: new(" env-secret "), flags: []string{"--require-auth-token"}},
|
||||
{name: "cli override", envToken: new(""), flags: []string{"--require-auth-token", "--token", " cli-secret "}},
|
||||
{name: "blank cli override", envToken: new("env-secret"), flags: []string{"--require-auth-token", "--token", " \t"}, wantAuthErr: true},
|
||||
{name: "empty cli preserves environment", envToken: new("env-secret"), flags: []string{"--require-auth-token", "--token", ""}},
|
||||
{name: "default permits unset"},
|
||||
} {
|
||||
test.Run(testCase.name, func(test *testing.T) {
|
||||
if testCase.envToken == nil {
|
||||
test.Setenv("SHELLCTL_AUTH_TOKEN", "")
|
||||
if err := os.Unsetenv("SHELLCTL_AUTH_TOKEN"); err != nil {
|
||||
test.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
test.Setenv("SHELLCTL_AUTH_TOKEN", *testCase.envToken)
|
||||
}
|
||||
test.Setenv("SHELLCTL_SNAPSHOT_TIMEOUT", "")
|
||||
stateDir := filepath.Join(test.TempDir(), "state")
|
||||
if !testCase.wantAuthErr {
|
||||
if err := os.WriteFile(stateDir, nil, 0600); err != nil {
|
||||
test.Fatal(err)
|
||||
}
|
||||
}
|
||||
originalArgs := os.Args
|
||||
test.Cleanup(func() { os.Args = originalArgs })
|
||||
os.Args = append([]string{"shellctl", "serve", "--state-dir", stateDir}, testCase.flags...)
|
||||
err := run()
|
||||
if err == nil {
|
||||
test.Fatal("expected startup error")
|
||||
}
|
||||
if testCase.wantAuthErr {
|
||||
if err.Error() != "auth token is required: set SHELLCTL_AUTH_TOKEN or --token" {
|
||||
test.Fatalf("expected token error before initialization, got %v", err)
|
||||
}
|
||||
if _, statErr := os.Stat(stateDir); !os.IsNotExist(statErr) {
|
||||
test.Fatalf("state directory created before token validation: %v", statErr)
|
||||
}
|
||||
} else if !strings.HasPrefix(err.Error(), "initialize:") {
|
||||
test.Fatalf("expected initialization after accepted token, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user