Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(security): confine agent CLI config writes to home (#209)
crispinhu27b043c2d7f1ae
diff --git a/internal/httpapi/assistant_engine_agentcli.go b/internal/httpapi/assistant_engine_agentcli.goindex d0b4d002..10caf4d1 100644--- a/internal/httpapi/assistant_engine_agentcli.go+++ b/internal/httpapi/assistant_engine_agentcli.go@@ -32,7 +32,7 @@ func prepareAssistantAgentCLIInvocation(kind string, o assistantEngineInvocation}entries[id] = entry}- if err := runtime.WriteAgentCLIMCPConfig(kind, filepath.Join(o.Root, "home"), entries, runtime.AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ if err := runtime.WriteAgentCLIMCPConfig(kind, runtime.AgentCLIHome{Base: o.Root, Rel: "home"}, entries, runtime.AgentCLIMCPOptions{ReadOnly: true}); err != nil {return assistantCLIInvocation{}, err}resume := ""diff --git a/internal/runtime/agent_cli.go b/internal/runtime/agent_cli.goindex 2b7bdbc8..4827f119 100644--- a/internal/runtime/agent_cli.go+++ b/internal/runtime/agent_cli.go@@ -125,7 +125,7 @@ var dshServerNameRe = regexp.MustCompile(`[^A-Za-z0-9_-]`)// WriteAgentCLIMCPConfig renders MCP entries (the mcpConfigEntries shape:// {"type":"http","url","headers"} or {"command","args","cwd","env"}) in the// CLI's own format under home, replacing whatever an earlier invocation left.-func WriteAgentCLIMCPConfig(kind, home string, entries map[string]any, options AgentCLIMCPOptions) error {+func WriteAgentCLIMCPConfig(kind string, home AgentCLIHome, entries map[string]any, options AgentCLIMCPOptions) error {rel, ok := agentCLIMCPPaths[kind]if !ok {return fmt.Errorf("unknown agent CLI %q", kind)@@ -248,12 +248,94 @@ func WriteAgentCLIMCPConfig(kind, home string, entries map[string]any, options A// agyChatPermissions are the Antigravity deny rules of AI 对话.var agyChatPermissions = map[string]any{"allow": []string{"mcp(*)"}, "deny": []string{"command(*)", "write_file(*)", "read_url(*)"}}-func writeAgentCLIFile(home, rel string, data []byte) error {- path := filepath.Join(home, filepath.FromSlash(rel))- if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+func writeAgentCLIFile(home AgentCLIHome, rel string, data []byte) error {+ rel = filepath.Clean(filepath.ToSlash(rel))+ if !filepath.IsLocal(rel) || filepath.IsAbs(rel) || strings.HasPrefix(rel, "..") {+ return fmt.Errorf("invalid agent CLI file path %q", rel)+ }+ root, err := openAgentCLIHome(home)+ if err != nil {return err}- return os.WriteFile(path, data, 0o600)+ defer root.Close()+ dir := filepath.Dir(rel)+ if dir != "." && dir != "" {+ if err := root.MkdirAll(dir, 0o700); err != nil {+ return err+ }+ }+ return root.WriteFile(rel, data, 0o600)+}++// AgentCLIHome locates an agent CLI HOME as a path below a trusted base+// directory. A private HOME lives in the workspace that sandboxed Agents can+// write, so any component below Base may have been replaced with a symlink to+// anywhere on the host; Base itself is owned by the control plane.+type AgentCLIHome struct {+ // Base is trusted and opened as given (it may be reached through+ // symlinks, e.g. a temp directory on macOS).+ Base string+ // Rel is a local path below Base; every component must be a real+ // directory and is created when missing.+ Rel string+}++// HostAgentCLIHome is a HOME the control plane chose itself. Its parent is+// trusted; the HOME itself must still be a real directory.+func HostAgentCLIHome(home string) AgentCLIHome {+ home = filepath.Clean(home)+ return AgentCLIHome{Base: filepath.Dir(home), Rel: filepath.Base(home)}+}++// WorkspaceAgentCLIHome is the private HOME name below+// <workspace>/.agentflow/private-home.+func WorkspaceAgentCLIHome(workspace, name string) AgentCLIHome {+ return AgentCLIHome{Base: workspace, Rel: filepath.Join(".agentflow", "private-home", name)}+}++// Path is the HOME as a host path.+func (h AgentCLIHome) Path() string { return filepath.Join(h.Base, h.Rel) }++// openAgentCLIHome opens home as an os.Root, creating missing directories.+// It starts from the trusted Base and Lstat-checks every component of Rel+// inside that os.Root, so no symlink below Base is ever followed by mkdir or+// open; a component swapped afterwards still cannot leave Base, and the+// opened HOME is re-checked against the validated directory.+func openAgentCLIHome(home AgentCLIHome) (*os.Root, error) {+ rel := filepath.Clean(home.Rel)+ if strings.TrimSpace(home.Base) == "" || rel == "." || !filepath.IsLocal(rel) {+ return nil, fmt.Errorf("invalid agent CLI home: %s", home.Path())+ }+ if err := os.MkdirAll(home.Base, 0o700); err != nil {+ return nil, err+ }+ base, err := os.OpenRoot(home.Base)+ if err != nil {+ return nil, err+ }+ defer base.Close()+ current := ""+ for _, element := range strings.Split(rel, string(filepath.Separator)) {+ current = filepath.Join(current, element)+ if err := ensureRootDirectory(base, current); err != nil {+ return nil, fmt.Errorf("agent CLI home is not a real directory: %s: %w", home.Path(), err)+ }+ }+ info, err := base.Lstat(rel)+ if err != nil {+ return nil, err+ }+ root, err := base.OpenRoot(rel)+ if err != nil {+ return nil, err+ }+ // A component may have been swapped for a symlink after the checks.+ opened, err := root.Stat(".")+ if err != nil || !os.SameFile(info, opened) {+ root.Close()+ return nil, fmt.Errorf("agent CLI home changed while opening: %s", home.Path())+ }+ return root, nil}// ApplyAgentCLICredential writes the credential-dependent model configuration of an@@ -261,7 +343,7 @@ func writeAgentCLIFile(home, rel string, data []byte) error {// process sees it) and returns argv and the environment to run it with. The// key itself stays in the environment; configuration files only name the// variable.-func ApplyAgentCLICredential(kind string, cred ProviderCredential, options AgentCLIOptions, home, homeEnv string, argv []string) ([]string, map[string]string, error) {+func ApplyAgentCLICredential(kind string, cred ProviderCredential, options AgentCLIOptions, home AgentCLIHome, homeEnv string, argv []string) ([]string, map[string]string, error) {key := strings.TrimSpace(cred.APIKey)if key == "" {return nil, nil, fmt.Errorf("需求责任人未配置 %s API Key,请在个人配置中配置", AgentCLILabel(kind))@@ -387,7 +469,13 @@ func ApplyAgentCLICredential(kind string, cred ProviderCredential, options Agentreturn nil, nil, errors.New("invalid DeepSeek Harness invocation")}patches := []string{"--patch", homeEnv + "/.dsh/agentflow-model.json"}- if _, err := os.Stat(filepath.Join(home, ".dsh", "agentflow-mcp.json")); err == nil {+ root, err := openAgentCLIHome(home)+ if err != nil {+ return nil, nil, err+ }+ _, err = root.Stat(filepath.Join(".dsh", "agentflow-mcp.json"))+ root.Close()+ if err == nil {patches = append(patches, "--patch", homeEnv+"/.dsh/agentflow-mcp.json")}head := append([]string{}, argv[:3]...)diff --git a/internal/runtime/agent_cli_test.go b/internal/runtime/agent_cli_test.goindex 087bedac..f83b186b 100644--- a/internal/runtime/agent_cli_test.go+++ b/internal/runtime/agent_cli_test.go@@ -83,18 +83,18 @@ func TestAgentCLICommandAgyEffortSuffix(t *testing.T) {func TestApplyAgentCLICredential(t *testing.T) {home := t.TempDir()- if _, _, err := ApplyAgentCLICredential(AgentCLIOpenCode, ProviderCredential{}, AgentCLIOptions{Model: "m"}, home, home, nil); err == nil || !strings.Contains(err.Error(), "API Key") {+ if _, _, err := ApplyAgentCLICredential(AgentCLIOpenCode, ProviderCredential{}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(home), home, nil); err == nil || !strings.Contains(err.Error(), "API Key") {t.Fatalf("missing key: %v", err)}- if _, _, err := ApplyAgentCLICredential(AgentCLIPi, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, home, home, nil); err == nil || !strings.Contains(err.Error(), "Base URL") {+ if _, _, err := ApplyAgentCLICredential(AgentCLIPi, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(home), home, nil); err == nil || !strings.Contains(err.Error(), "Base URL") {t.Fatalf("pi without Base URL: %v", err)}- if _, _, err := ApplyAgentCLICredential(AgentCLIKimi, ProviderCredential{APIKey: "k"}, AgentCLIOptions{}, home, home, nil); err == nil || !strings.Contains(err.Error(), "模型") {+ if _, _, err := ApplyAgentCLICredential(AgentCLIKimi, ProviderCredential{APIKey: "k"}, AgentCLIOptions{}, HostAgentCLIHome(home), home, nil); err == nil || !strings.Contains(err.Error(), "模型") {t.Fatalf("kimi without model: %v", err)}// The key travels in the environment; config files only name the variable.- _, env, err := ApplyAgentCLICredential(AgentCLIOpenCode, ProviderCredential{APIKey: "secret-key", BaseURL: "https://gw.example/", Protocol: "messages"}, AgentCLIOptions{Model: "m"}, home, home, []string{"opencode", "run", "x"})+ _, env, err := ApplyAgentCLICredential(AgentCLIOpenCode, ProviderCredential{APIKey: "secret-key", BaseURL: "https://gw.example/", Protocol: "messages"}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(home), home, []string{"opencode", "run", "x"})if err != nil {t.Fatal(err)}@@ -102,7 +102,7 @@ func TestApplyAgentCLICredential(t *testing.T) {t.Fatalf("opencode env: %v", env)}- _, env, err = ApplyAgentCLICredential(AgentCLIKimi, ProviderCredential{APIKey: "secret-key", BaseURL: "https://api.example/v1", Protocol: "responses"}, AgentCLIOptions{Model: "m"}, home, "/w/home", nil)+ _, env, err = ApplyAgentCLICredential(AgentCLIKimi, ProviderCredential{APIKey: "secret-key", BaseURL: "https://api.example/v1", Protocol: "responses"}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(home), "/w/home", nil)if err != nil {t.Fatal(err)}@@ -112,7 +112,7 @@ func TestApplyAgentCLICredential(t *testing.T) {}// Chat on Antigravity adds deny rules inline, repeating the provider.- argv, env, err := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "g"}, AgentCLIOptions{ReadOnly: true}, home, home, []string{"agy", "--output-format", "stream-json", "-p", "hi"})+ argv, env, err := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "g"}, AgentCLIOptions{ReadOnly: true}, HostAgentCLIHome(home), home, []string{"agy", "--output-format", "stream-json", "-p", "hi"})if err != nil {t.Fatal(err)}@@ -129,11 +129,11 @@ func TestApplyAgentCLICredential(t *testing.T) {if err := json.Unmarshal([]byte(argv[i+1]), &settings); err != nil || settings.ModelProvider != "gemini" || !slices.Contains(settings.Permissions.Deny, "command(*)") {t.Fatalf("agy inline settings: %s (%v)", argv[i+1], err)}- if argv, _, _ := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "g"}, AgentCLIOptions{}, home, home, []string{"agy", "-p", "hi"}); slices.Contains(argv, "--settings") {+ if argv, _, _ := ApplyAgentCLICredential(AgentCLIAntigravity, ProviderCredential{APIKey: "g"}, AgentCLIOptions{}, HostAgentCLIHome(home), home, []string{"agy", "-p", "hi"}); slices.Contains(argv, "--settings") {t.Fatalf("SOP agy argv carries chat settings: %q", argv)}- argv, _, err = ApplyAgentCLICredential(AgentCLIDeepSeek, ProviderCredential{APIKey: "d"}, AgentCLIOptions{Model: "deepseek-v4-flash"}, home, "/h", []string{"dsh", "--profile", "headless", "--json", "x"})+ argv, _, err = ApplyAgentCLICredential(AgentCLIDeepSeek, ProviderCredential{APIKey: "d"}, AgentCLIOptions{Model: "deepseek-v4-flash"}, HostAgentCLIHome(home), "/h", []string{"dsh", "--profile", "headless", "--json", "x"})if err != nil {t.Fatal(err)}@@ -157,7 +157,7 @@ func TestWriteAgentCLIMCPConfigChat(t *testing.T) {return doc}home := t.TempDir()- if err := WriteAgentCLIMCPConfig(AgentCLICursor, home, entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ if err := WriteAgentCLIMCPConfig(AgentCLICursor, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {t.Fatal(err)}if deny := read(home, ".cursor/cli-config.json")["permissions"].(map[string]any)["deny"].([]any); !slices.Contains(deny, any("Shell(**)")) {@@ -167,13 +167,13 @@ func TestWriteAgentCLIMCPConfigChat(t *testing.T) {t.Fatalf("cursor mcp: %v", server)}// An SOP invocation in the same home lifts the chat rules again.- if err := WriteAgentCLIMCPConfig(AgentCLICursor, home, entries, AgentCLIMCPOptions{}); err != nil {+ if err := WriteAgentCLIMCPConfig(AgentCLICursor, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{}); err != nil {t.Fatal(err)}if deny := read(home, ".cursor/cli-config.json")["permissions"].(map[string]any)["deny"].([]any); len(deny) != 0 {t.Fatalf("cursor SOP deny: %v", deny)}- if err := WriteAgentCLIMCPConfig(AgentCLIOpenCode, home, entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ if err := WriteAgentCLIMCPConfig(AgentCLIOpenCode, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {t.Fatal(err)}doc := read(home, ".config/opencode/opencode.json")@@ -183,7 +183,7 @@ func TestWriteAgentCLIMCPConfigChat(t *testing.T) {if server := doc["mcp"].(map[string]any)["gw"].(map[string]any); server["type"] != "remote" {t.Fatalf("opencode mcp: %v", server)}- if err := WriteAgentCLIMCPConfig(AgentCLIAntigravity, home, entries, AgentCLIMCPOptions{}); err != nil {+ if err := WriteAgentCLIMCPConfig(AgentCLIAntigravity, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{}); err != nil {t.Fatal(err)}if server := read(home, ".gemini/config/mcp_config.json")["mcpServers"].(map[string]any)["gw"].(map[string]any); server["serverUrl"] == nil {@@ -228,3 +228,190 @@ func TestAgentCLIUserCredentials(t *testing.T) {t.Fatal("empty user has agent CLI credentials")}}++func TestWriteAgentCLIFileSecurity(t *testing.T) {+ home := t.TempDir()+ data := []byte(`{"test":true}`)++ // Normal write within home subdirectories+ if err := writeAgentCLIFile(HostAgentCLIHome(home), ".cursor/cli-config.json", data); err != nil {+ t.Fatalf("valid write failed: %v", err)+ }+ readBack, err := os.ReadFile(filepath.Join(home, ".cursor", "cli-config.json"))+ if err != nil || string(readBack) != string(data) {+ t.Fatalf("read back content mismatch: %q, %v", readBack, err)+ }++ // Traversal attacks must be rejected+ for _, invalid := range []string{+ "../escape.json",+ "../../escape.json",+ "sub/../../escape.json",+ "/etc/passwd",+ filepath.Join("..", "foo.json"),+ } {+ if err := writeAgentCLIFile(HostAgentCLIHome(home), invalid, data); err == nil {+ t.Errorf("path %q was accepted, expected error", invalid)+ }+ }+}++func TestWriteAgentCLIFileRejectsSymlinkedHome(t *testing.T) {+ outside := t.TempDir()+ home := filepath.Join(t.TempDir(), "home")+ if err := os.Symlink(outside, home); err != nil {+ t.Fatal(err)+ }+ if err := writeAgentCLIFile(HostAgentCLIHome(home), ".kimi-code/config.toml", []byte("x")); err == nil {+ t.Fatal("write through a symlinked home was accepted")+ }+ if entries, _ := os.ReadDir(outside); len(entries) != 0 {+ t.Fatalf("files written outside home: %v", entries)+ }+}++func TestBindCommandRejectsSymlinkedParentsBeforeWritingCredentials(t *testing.T) {+ for _, kind := range []string{AgentCLIKimi, AgentCLIZCode} {+ for _, component := range []string{".agentflow", "private-home", "tmp", "home"} {+ t.Run(kind+"/"+component, func(t *testing.T) {+ workspace, outside := t.TempDir(), t.TempDir()+ command := AgentCLICommand(kind, AgentCLICommandOptions{Model: "m", Prompt: "p"})+ command.PrivateHome, command.PrivateHomeKey = true, kind+"-agent-1"+ command.CredentialBindings = []CredentialBinding{BindAgentCLI}+ link := filepath.Join(workspace, ".agentflow")+ if component != ".agentflow" {+ link = filepath.Join(link, component)+ if component == "home" {+ link = filepath.Join(workspace, ".agentflow", "private-home", command.PrivateHomeKey)+ }+ }+ if err := os.MkdirAll(filepath.Dir(link), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(outside, link); err != nil {+ t.Fatal(err)+ }+ sb := &localSandbox{workspace: workspace, environment: map[string]string{}}+ credentials := RunCredentials{AgentCLI: map[string]ProviderCredential{+ kind: {APIKey: "fake-test-key", BaseURL: "https://example.test"},+ }}+ if _, err := bindCommand(sb, workspace, command, credentials); err == nil {+ t.Fatal("symlinked private-home component was accepted")+ }+ entries, err := os.ReadDir(outside)+ if err != nil {+ t.Fatal(err)+ }+ if len(entries) != 0 {+ t.Fatalf("credential files written outside the workspace: %v", entries)+ }+ })+ }+ }+}++func TestBindAgentCLICommandRejectsSymlinkedPrivateHome(t *testing.T) {+ for _, kind := range []string{AgentCLIKimi, AgentCLIZCode} {+ t.Run(kind, func(t *testing.T) {+ workspace, outside := t.TempDir(), t.TempDir()+ command := AgentCLICommand(kind, AgentCLICommandOptions{Model: "m", Prompt: "p"})+ command.PrivateHome, command.PrivateHomeKey = true, kind+"-agent-1"+ parent := filepath.Join(workspace, ".agentflow", "private-home")+ if err := os.MkdirAll(parent, 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(outside, filepath.Join(parent, command.PrivateHomeKey)); err != nil {+ t.Fatal(err)+ }+ sb := &localSandbox{workspace: workspace, environment: map[string]string{}}+ if _, _, err := BindAgentCLICommand(sb, workspace, command, ProviderCredential{APIKey: "secret-key", BaseURL: "https://example.test"}, command.Argv); err == nil {+ t.Fatal("symlinked private home was accepted")+ }+ if _, err := bindCommand(sb, workspace, command, RunCredentials{}); err == nil {+ t.Fatal("bindCommand accepted a symlinked private home")+ }+ if entries, _ := os.ReadDir(outside); len(entries) != 0 {+ t.Fatalf("files written outside the workspace: %v", entries)+ }+ })+ }+}++// Every component below the trusted base is checked, not only the HOME+// itself: a symlinked ancestor must not redirect mkdir or the config write.+func TestWriteAgentCLIMCPConfigRejectsSymlinkedAncestors(t *testing.T) {+ entries := map[string]any{"gw": map[string]any{"type": "http", "url": "http://127.0.0.1:1/mcp"}}+ for _, kind := range []string{AgentCLIKimi, AgentCLIZCode, AgentCLICursor} {+ for _, component := range []string{".agentflow", "private-home", "home"} {+ t.Run(kind+"/"+component, func(t *testing.T) {+ workspace, outside := t.TempDir(), t.TempDir()+ name := AgentCLIPrivateHomeKey(kind, "agent-1")+ link := map[string]string{+ ".agentflow": filepath.Join(workspace, ".agentflow"),+ "private-home": filepath.Join(workspace, ".agentflow", "private-home"),+ "home": filepath.Join(workspace, ".agentflow", "private-home", name),+ }[component]+ if err := os.MkdirAll(filepath.Dir(link), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(outside, link); err != nil {+ t.Fatal(err)+ }+ if err := WriteAgentCLIMCPConfig(kind, WorkspaceAgentCLIHome(workspace, name), entries, AgentCLIMCPOptions{}); err == nil {+ t.Fatal("write through a symlinked ancestor was accepted")+ }+ // Cursor's credential lives in the environment only; the others write files.+ if _, _, err := ApplyAgentCLICredential(kind, ProviderCredential{APIKey: "fake-test-key", BaseURL: "https://example.test"}, AgentCLIOptions{Model: "m"}, WorkspaceAgentCLIHome(workspace, name), "/h", []string{kind}); err == nil && kind != AgentCLICursor {+ t.Fatal("credential write through a symlinked ancestor was accepted")+ }+ if got, _ := os.ReadDir(outside); len(got) != 0 {+ t.Fatalf("files written outside the workspace: %v", got)+ }+ })+ }+ }+}++func TestBindAgentCLICommandRejectsSymlinkedPrivateHomeParent(t *testing.T) {+ for _, kind := range []string{AgentCLIKimi, AgentCLIZCode} {+ t.Run(kind, func(t *testing.T) {+ workspace, outside := t.TempDir(), t.TempDir()+ command := AgentCLICommand(kind, AgentCLICommandOptions{Model: "m", Prompt: "p"})+ command.PrivateHome, command.PrivateHomeKey = true, kind+"-agent-1"+ if err := os.MkdirAll(filepath.Join(workspace, ".agentflow"), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(outside, filepath.Join(workspace, ".agentflow", "private-home")); err != nil {+ t.Fatal(err)+ }+ sb := &localSandbox{workspace: workspace, environment: map[string]string{}}+ if _, _, err := BindAgentCLICommand(sb, workspace, command, ProviderCredential{APIKey: "fake-test-key", BaseURL: "https://example.test"}, command.Argv); err == nil {+ t.Fatal("symlinked private-home parent was accepted")+ }+ if got, _ := os.ReadDir(outside); len(got) != 0 {+ t.Fatalf("files written outside the workspace: %v", got)+ }+ })+ }+}++// The trusted base may itself be reached through a symlink (macOS temp+// directories are); only components below it are refused.+func TestOpenAgentCLIHomeTrustsBase(t *testing.T) {+ real := t.TempDir()+ base := filepath.Join(t.TempDir(), "base")+ if err := os.Symlink(real, base); err != nil {+ t.Fatal(err)+ }+ if err := writeAgentCLIFile(AgentCLIHome{Base: base, Rel: "a/home"}, ".kimi-code/config.toml", []byte("x")); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(real, "a", "home", ".kimi-code", "config.toml")); err != nil {+ t.Fatal(err)+ }+ for _, rel := range []string{"", ".", "..", "../x", "/abs"} {+ if _, err := openAgentCLIHome(AgentCLIHome{Base: base, Rel: rel}); err == nil {+ t.Errorf("rel %q was accepted", rel)+ }+ }+}diff --git a/internal/runtime/agent_cli_zcode.go b/internal/runtime/agent_cli_zcode.goindex 65cf1af1..4eee89f5 100644--- a/internal/runtime/agent_cli_zcode.go+++ b/internal/runtime/agent_cli_zcode.go@@ -5,8 +5,6 @@ import ("errors""fmt""io/fs"- "os"- "path/filepath""reflect""strings")@@ -73,7 +71,7 @@ func nonEmpty(value any) bool {// applyZCodeCredential gives ZCode the key as a personal provider file that// exists only until ZCode has read it: ZCode accepts a literal key and// nothing else, and the key must not stay on disk.-func applyZCodeCredential(home, homeEnv, key, baseURL, protocol, model string, argv []string) ([]string, map[string]string, error) {+func applyZCodeCredential(home AgentCLIHome, homeEnv, key, baseURL, protocol, model string, argv []string) ([]string, map[string]string, error) {// The private provider has no model of its own, so "CLI default" (sent as// "default") must name a real one: BigModel's coding model on the default// endpoint, while a custom endpoint has no model we could guess.@@ -118,9 +116,14 @@ func applyZCodeCredential(home, homeEnv, key, baseURL, protocol, model string, a// addZCodeKeyCleanupHook merges a SessionStart hook into ZCode's config,// keeping whatever the MCP configuration put there.-func addZCodeKeyCleanupHook(home string) error {+func addZCodeKeyCleanupHook(home AgentCLIHome) error {document := map[string]any{}- data, err := os.ReadFile(filepath.Join(home, filepath.FromSlash(zcodeConfigPath)))+ root, err := openAgentCLIHome(home)+ if err != nil {+ return err+ }+ data, err := root.ReadFile(zcodeConfigPath)+ root.Close()if err == nil {err = json.Unmarshal(data, &document)}diff --git a/internal/runtime/agent_cli_zcode_test.go b/internal/runtime/agent_cli_zcode_test.goindex 9aa58615..305d3371 100644--- a/internal/runtime/agent_cli_zcode_test.go+++ b/internal/runtime/agent_cli_zcode_test.go@@ -73,11 +73,11 @@ func zcodeKeyFiles(t *testing.T, home string) []string {func TestApplyZCodeCredential(t *testing.T) {home := t.TempDir()- if err := WriteAgentCLIMCPConfig(AgentCLIZCode, home, map[string]any{"gw": map[string]any{"type": "http", "url": "http://127.0.0.1:1/mcp"}}, AgentCLIMCPOptions{}); err != nil {+ if err := WriteAgentCLIMCPConfig(AgentCLIZCode, HostAgentCLIHome(home), map[string]any{"gw": map[string]any{"type": "http", "url": "http://127.0.0.1:1/mcp"}}, AgentCLIMCPOptions{}); err != nil {t.Fatal(err)}argv := []string{"zcode", "--prompt", "it's \"quoted\" $HOME"}- bound, env, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: " secret-key "}, AgentCLIOptions{Model: "glm-5.3"}, home, "/w/home", argv)+ bound, env, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: " secret-key "}, AgentCLIOptions{Model: "glm-5.3"}, HostAgentCLIHome(home), "/w/home", argv)if err != nil {t.Fatal(err)}@@ -129,7 +129,7 @@ func TestApplyZCodeCredential(t *testing.T) {if err := os.WriteFile(filepath.Join(home, zcodeConfigPath), []byte(existing), 0o600); err != nil {t.Fatal(err)}- if _, env2, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "glm-5.3"}, home, "/w/home", argv); err != nil || env2[zcodePersonalFileEnv] == env[zcodePersonalFileEnv] {+ if _, env2, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "glm-5.3"}, HostAgentCLIHome(home), "/w/home", argv); err != nil || env2[zcodePersonalFileEnv] == env[zcodePersonalFileEnv] {t.Fatalf("second call: %v %v", env2, err)}if len(zcodeKeyFiles(t, home)) != 2 {@@ -151,7 +151,7 @@ func TestApplyZCodeCredentialProtocols(t *testing.T) {{"https://gw.example", "", "https://gw.example", "anthropic-messages"},} {home := t.TempDir()- if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k", BaseURL: tc.baseURL, Protocol: tc.protocol}, AgentCLIOptions{Model: "m"}, home, home, []string{"zcode"}); err != nil {+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k", BaseURL: tc.baseURL, Protocol: tc.protocol}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(home), home, []string{"zcode"}); err != nil {t.Fatal(err)}rules := readJSONFile(t, zcodeKeyFiles(t, home)[0])["config"].(map[string]any)["providerConfigRules"].(map[string]any)["providerRules"].([]any)@@ -164,18 +164,18 @@ func TestApplyZCodeCredentialProtocols(t *testing.T) {// to BigModel's coding model, a custom endpoint must name one.for _, model := range []string{"", "default"} {home := t.TempDir()- if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: model}, home, home, []string{"zcode"}); err != nil {+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: model}, HostAgentCLIHome(home), home, []string{"zcode"}); err != nil {t.Fatal(err)}selection := readJSONFile(t, zcodeKeyFiles(t, home)[0])["config"].(map[string]any)["defaultModelSelection"].(map[string]any)if selection["modelId"] != zcodeDefaultModel {t.Errorf("model %q: selection %v", model, selection)}- if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k", BaseURL: "https://gw.example"}, AgentCLIOptions{Model: model}, t.TempDir(), "/h", nil); err == nil || !strings.Contains(err.Error(), "模型") {+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k", BaseURL: "https://gw.example"}, AgentCLIOptions{Model: model}, HostAgentCLIHome(t.TempDir()), "/h", nil); err == nil || !strings.Contains(err.Error(), "模型") {t.Fatalf("custom endpoint without model %q: %v", model, err)}}- if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{}, AgentCLIOptions{Model: "m"}, t.TempDir(), "/h", nil); err == nil || !strings.Contains(err.Error(), "ZCode API Key") {+ if _, _, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(t.TempDir()), "/h", nil); err == nil || !strings.Contains(err.Error(), "ZCode API Key") {t.Fatalf("zcode without key: %v", err)}}@@ -188,7 +188,7 @@ func TestWriteAgentCLIMCPConfigZCode(t *testing.T) {"local": map[string]any{"command": "node", "args": []string(nil), "cwd": "", "env": map[string]string{}},"full": map[string]any{"command": "npx", "args": []string{"-y", "x"}, "cwd": "/w", "env": map[string]string{"A": "1"}},}- if err := WriteAgentCLIMCPConfig(AgentCLIZCode, home, entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {+ if err := WriteAgentCLIMCPConfig(AgentCLIZCode, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{ReadOnly: true}); err != nil {t.Fatal(err)}doc := readJSONFile(t, filepath.Join(home, zcodeConfigPath))@@ -229,7 +229,7 @@ func TestZCodeCleanupScriptRemovesKeyFile(t *testing.T) {if err := os.WriteFile(fake, []byte("#!/bin/sh\nprintf '%s\\n' \"$*\"\nprintf 'base=%s builtin=%s data=%s\\n' \"${ZCODE_BASE_URL-unset}\" \"${ZCODE_BUILTIN_PROVIDER_CONFIG_FILE-unset}\" \"$ZCODE_DATA_BASE_DIR\"\nrm -f \"$ZCODE_PERSONAL_PROVIDER_CONFIG_FILE\"\n: > \"$ZCODE_PERSONAL_PROVIDER_CONFIG_FILE\"\nexit 7\n"), 0o755); err != nil {t.Fatal(err)}- argv, env, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, home, home, []string{fake, "--prompt", "it's \"q\" $HOME"})+ argv, env, err := ApplyAgentCLICredential(AgentCLIZCode, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(home), home, []string{fake, "--prompt", "it's \"q\" $HOME"})if err != nil {t.Fatal(err)}diff --git a/internal/runtime/command_binding.go b/internal/runtime/command_binding.goindex 1cb39399..bc5de3e0 100644--- a/internal/runtime/command_binding.go+++ b/internal/runtime/command_binding.go@@ -4,7 +4,6 @@ import ("agentflow/internal/observability""fmt""net/url"- "os""path/filepath""strconv""strings"@@ -44,6 +43,36 @@ func bindCommand(sandbox Sandbox, workspace string, command CommandSpec, credentfor _, key := range []string{"OPENAI_API_KEY", "CODEX_API_KEY", "OPENAI_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"} {bound.environment[key] = ""}+ // Validate every private-home component before any credential binding can+ // write configuration. The sandbox may have replaced a parent with a symlink.+ if command.PrivateHome {+ provider := PrivateHomeName(command)+ hostHome, err := EnsureControlDirectory(workspace, "private-home", provider)+ if err != nil {+ return CommandSpec{}, fmt.Errorf("create private home: %w", err)+ }+ hostTmp, err := EnsureControlDirectory(workspace, "tmp", provider)+ if err != nil {+ return CommandSpec{}, fmt.Errorf("create private temp: %w", err)+ }+ if sandboxDriver(sandbox) == "docker" {+ bound.environment["HOME"] = filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "private-home", provider))+ bound.environment["TMPDIR"] = filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "tmp", provider))+ } else {+ bound.environment["HOME"] = hostHome+ bound.environment["TMPDIR"] = hostTmp+ }+ if command.Provider == "codex" || command.Provider == "claude-code" {+ dir, key := ".codex", "CODEX_HOME"+ if command.Provider == "claude-code" {+ dir, key = ".claude", "CLAUDE_CONFIG_DIR"+ }+ if _, err := EnsureControlDirectory(workspace, "private-home", provider, dir); err != nil {+ return CommandSpec{}, err+ }+ bound.environment[key] = filepath.ToSlash(filepath.Join(bound.environment["HOME"], dir))+ }+ }for _, binding := range command.CredentialBindings {switch binding {case BindCodeBuddy:@@ -99,13 +128,16 @@ func bindCommand(sandbox Sandbox, workspace string, command CommandSpec, credent}bound.environment["ANTHROPIC_BASE_URL"] = baseURLcase BindAgentCLI:- home, homeEnv := privateHomePaths(sandbox, workspace, command)- if !command.PrivateHome {- home = command.environment["HOME"]- homeEnv = home- }- if strings.TrimSpace(home) == "" {- return CommandSpec{}, fmt.Errorf("%s 需要独立的 HOME 目录", AgentCLILabel(command.Provider))+ var home AgentCLIHome+ homeEnv := bound.environment["HOME"]+ if command.PrivateHome {+ home = WorkspaceAgentCLIHome(workspace, PrivateHomeName(command))+ } else {+ homeEnv = command.environment["HOME"]+ if strings.TrimSpace(homeEnv) == "" {+ return CommandSpec{}, fmt.Errorf("%s 需要独立的 HOME 目录", AgentCLILabel(command.Provider))+ }+ home = HostAgentCLIHome(homeEnv)}argv, env, err := ApplyAgentCLICredential(command.Provider, credentials.AgentCLI[command.Provider], command.AgentCLI, home, homeEnv, bound.Argv)if err != nil {@@ -137,34 +169,6 @@ func bindCommand(sandbox Sandbox, workspace string, command CommandSpec, credentbound.environment["OTEL_LOG_TOOL_DETAILS"] = "1"bound.environment["OTEL_RESOURCE_ATTRIBUTES"] = fmt.Sprintf("agentflow.run_id=%s,agentflow.node_id=%s,service.name=agentflow-codebuddy", runID, nodeID)}- if command.PrivateHome {- provider := PrivateHomeName(command)- hostHome := filepath.Join(workspace, ".agentflow", "private-home", provider)- hostTmp := filepath.Join(workspace, ".agentflow", "tmp", provider)- if err := os.MkdirAll(hostHome, 0o700); err != nil {- return CommandSpec{}, fmt.Errorf("create private home: %w", err)- }- if err := os.MkdirAll(hostTmp, 0o700); err != nil {- return CommandSpec{}, fmt.Errorf("create private temp: %w", err)- }- if sandboxDriver(sandbox) == "docker" {- bound.environment["HOME"] = filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "private-home", provider))- bound.environment["TMPDIR"] = filepath.ToSlash(filepath.Join("/workspace", ".agentflow", "tmp", provider))- } else {- bound.environment["HOME"] = hostHome- bound.environment["TMPDIR"] = hostTmp- }- if command.Provider == "codex" || command.Provider == "claude-code" {- dir, key := ".codex", "CODEX_HOME"- if command.Provider == "claude-code" {- dir, key = ".claude", "CLAUDE_CONFIG_DIR"- }- if err := os.MkdirAll(filepath.Join(hostHome, dir), 0o700); err != nil {- return CommandSpec{}, err- }- bound.environment[key] = filepath.ToSlash(filepath.Join(bound.environment["HOME"], dir))- }- }return bound, nil}@@ -194,14 +198,17 @@ func AgentCLIPrivateHomeKey(kind, agentID string) string {// run in that HOME, sandboxed or not, because their MCP configuration is there.func BindAgentCLICommand(sandbox Sandbox, workspace string, command CommandSpec, cred ProviderCredential, argv []string) ([]string, map[string]string, error) {name := PrivateHomeName(command)- home, homeEnv := privateHomePaths(sandbox, workspace, command)- tmp := filepath.Join(workspace, ".agentflow", "tmp", name)- for _, dir := range []string{home, tmp} {- if err := os.MkdirAll(dir, 0o700); err != nil {- return nil, nil, fmt.Errorf("create private home: %w", err)- }+ _, homeEnv := privateHomePaths(sandbox, workspace, command)+ // Every level is Lstat-checked: the workspace is writable from the sandbox,+ // so .agentflow, private-home or the home itself may have become a symlink.+ if _, err := EnsureControlDirectory(workspace, "private-home", name); err != nil {+ return nil, nil, fmt.Errorf("create private home: %w", err)+ }+ tmp, err := EnsureControlDirectory(workspace, "tmp", name)+ if err != nil {+ return nil, nil, fmt.Errorf("create private temp: %w", err)}- argv, bound, err := ApplyAgentCLICredential(command.Provider, cred, command.AgentCLI, home, homeEnv, argv)+ argv, bound, err := ApplyAgentCLICredential(command.Provider, cred, command.AgentCLI, WorkspaceAgentCLIHome(workspace, name), homeEnv, argv)if err != nil {return nil, nil, err}diff --git a/internal/runtime/provider_agentcli.go b/internal/runtime/provider_agentcli.goindex 6a3d876c..80d0483f 100644--- a/internal/runtime/provider_agentcli.go+++ b/internal/runtime/provider_agentcli.go@@ -25,8 +25,11 @@ func (p agentCLIProvider) Materialize(ctx *providerMaterializeContext) error {if err != nil {return err}- home := filepath.Join(ctx.Workspace, ".agentflow", "private-home", AgentCLIPrivateHomeKey(p.kind, ctx.AgentID))- if err := WriteAgentCLIMCPConfig(p.kind, home, entries, AgentCLIMCPOptions{}); err != nil {+ name := AgentCLIPrivateHomeKey(p.kind, ctx.AgentID)+ if _, err := EnsureControlDirectory(ctx.Workspace, "private-home", name); err != nil {+ return err+ }+ if err := WriteAgentCLIMCPConfig(p.kind, WorkspaceAgentCLIHome(ctx.Workspace, name), entries, AgentCLIMCPOptions{}); err != nil {return err}ctx.Compiled.SystemPrompt = string(ctx.Content)