package pi import ( "encoding/json" "os" "path/filepath" "testing" ) // Pi gates every call in a message before running them together. A file // tool and a shell command in one message must never both run: the shell // could swap a checked path for a link before the file tool opens it. func TestPiBatchSeparatesShellAndFileTools(t *testing.T) { h := newHarness(t, realInstall(t)) work := t.TempDir() for _, name := range []string{"a.txt", "b.txt"} { if err := os.WriteFile(filepath.Join(work, name), []byte("plain\n"), 0600); err != nil { t.Fatal(err) } } r := h.open(work, "implement", []string{"submit_candidate"}, "") batch := func(calls ...map[string]any) []ToolResult { t.Helper() raw, _ := json.Marshal(calls) got := results(r.prompt(t, "BATCH "+string(raw), "allow")) if len(got) != len(calls) { t.Fatalf("batch returned %d results, want %d", len(got), len(calls)) } return got } bash := map[string]any{"name": "bash", "arguments": map[string]string{"command": "echo shell-ran"}} read := func(name string) map[string]any { return map[string]any{"name": "read", "arguments": map[string]string{"path": "/workspace/" + name}} } // Results arrive in completion order; a refused call is an error result // (the files exist, so a read that runs does not error). refused := func(res ToolResult) bool { return res.IsError } byTool := func(rs []ToolResult, tool string) ToolResult { t.Helper() for _, r := range rs { if r.Tool == tool { return r } } t.Fatalf("no %s result in %+v", tool, rs) return ToolResult{} } // Positive control: file tools alone, and a shell command alone, run. for _, res := range batch(read("a.txt"), read("b.txt")) { if refused(res) { t.Fatal("two file reads in one message were refused") } } if res := batch(bash); refused(res[0]) { t.Fatal("a lone shell command was refused") } // Shell first: the read must not run beside it. if res := batch(bash, read("a.txt")); refused(byTool(res, "bash")) || !refused(byTool(res, "read")) { t.Fatalf("shell then read: %+v", res) } // File tool first: the shell command must not run beside it. if res := batch(read("a.txt"), bash); refused(byTool(res, "read")) || !refused(byTool(res, "bash")) { t.Fatalf("read then shell: %+v", res) } // Separate messages still work in turn. if res := batch(read("a.txt")); refused(res[0]) { t.Fatal("a read after a mixed batch was refused") } } func TestPiShellInheritedDescriptors(t *testing.T) { h := newHarness(t, realInstall(t)) r := h.open(t.TempDir(), "implement", []string{"submit_candidate"}, "") shellOK(t, h, r, `python3 - <<'PY' import os fds=[] for name in os.listdir('/proc/self/fd'): try: os.fstat(int(name)) except OSError: continue fds.append(int(name)) assert sorted(fds)==[0,1,2],sorted(fds) print('stdio-only') PY`, "stdio-only") }