restart fix + slack commands
This commit is contained in:
1 parent
e90c9f324b
commit
25fcf85855
22 files changed
+1077
-119
No files matched your search
@@ -3,17 +3,22 @@ load("@rules_go//go:def.bzl", "go_library", "go_test")
|
||||
go_library(
|
||||
name = "tools",
|
||||
srcs = [
|
||||
"commands.go",
|
||||
"server.go",
|
||||
"session.go",
|
||||
],
|
||||
importpath = "slackerbot/internal/tools",
|
||||
visibility = ["//slackerbot:__subpackages__"],
|
||||
deps = ["//slackerbot/internal/acp"],
|
||||
deps = [
|
||||
"//slackerbot/internal/acp",
|
||||
"//slackerbot/internal/util",
|
||||
],
|
||||
)
|
||||
|
||||
go_test(
|
||||
name = "tools_test",
|
||||
srcs = [
|
||||
"commands_test.go",
|
||||
"server_test.go",
|
||||
"session_test.go",
|
||||
],
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"slackerbot/internal/acp"
|
||||
"slackerbot/internal/util"
|
||||
)
|
||||
|
||||
// SlackCommand is a Slack command offered to the agent as a tool. Its text is Verb
|
||||
// followed by the call's args, exactly as a user would type it.
|
||||
type SlackCommand struct {
|
||||
Name string
|
||||
Verb string
|
||||
Help string
|
||||
// Describes the args parameter. Empty when the command takes none.
|
||||
Args string
|
||||
Required bool
|
||||
// With no args it only shows a setting.
|
||||
Shows bool
|
||||
}
|
||||
|
||||
const (
|
||||
Stop = "stop"
|
||||
Move = "move"
|
||||
)
|
||||
|
||||
var Commands = []SlackCommand{
|
||||
{Name: "status", Verb: "status", Shows: true,
|
||||
Help: "Show this container's state, size, node, time unused, idle limit, home folder usage and every node."},
|
||||
{Name: "sessions", Verb: "sessions", Shows: true,
|
||||
Help: "List this container's recent sessions (Slack threads), with links."},
|
||||
{Name: "nodes", Verb: "nodes", Shows: true,
|
||||
Help: "List every node with the CPU, RAM and storage free on it, and where this container runs."},
|
||||
{Name: "permissions", Verb: "permissions", Shows: true,
|
||||
Help: "Show who may scale, change storage, move or set the idle limit here, and who the user managers are."},
|
||||
{Name: Stop, Verb: "stop",
|
||||
Help: "Shut this container down once your current reply is finished. The home folder is kept, and the next message starts it again."},
|
||||
{Name: "scale", Verb: "scale", Required: true,
|
||||
Help: "Change this container's RAM and CPU. A running container changes right away; shrinking memory may stop programs.",
|
||||
Args: "`up` or `down` to double or halve, an exact size like `8G 4cpu`, or a change like `+2G` or `-1cpu`"},
|
||||
{Name: "keep", Verb: "keep", Shows: true,
|
||||
Help: "Show or set how long this container may sit unused before it's stopped.",
|
||||
Args: "A time like `24h`, `3d` or `2w`, `indefinite` to never stop it, or `default` to reset. Empty shows the current limit"},
|
||||
{Name: "storage", Verb: "storage", Shows: true,
|
||||
Help: "Show the home folder's usage, or change its guaranteed space and max size.",
|
||||
Args: "A new max like `20G`, a change like `+5G`, or `min 8G` / `min 8G max 20G`. Empty shows usage"},
|
||||
{Name: Move, Verb: "move",
|
||||
Help: "Move this container to another node. Progress is posted in Slack. Near the end the container is briefly stopped, so finish your reply soon after calling this.",
|
||||
Args: "A node name from `nodes`, or `auto` (or empty) to pick the best one"},
|
||||
{Name: "listen", Verb: "listen", Shows: true,
|
||||
Help: "Show or change which replies in a channel thread reach you. DMs always read every message.",
|
||||
Args: "`all-messages` to read every reply in this thread, `only-mentions` for replies that @mention the bot. Put `channel` first to set the channel's default. Empty shows the setting"},
|
||||
{Name: "grant", Verb: "grant", Required: true,
|
||||
Help: "Give people permissions in this channel. People are Slack mentions like <@U012AB>, as they appear in messages.",
|
||||
Args: "Mentions then permissions (scale, storage, move, keep, manage or all), like `<@U012AB> move scale`. Start with `default` to change the server-wide list"},
|
||||
{Name: "revoke", Verb: "revoke", Required: true,
|
||||
Help: "Take permissions away in this channel. People are Slack mentions like <@U012AB>.",
|
||||
Args: "Mentions, then optionally permissions, like `<@U012AB> move`. Only mentions removes everything. Start with `default` for the server-wide list"},
|
||||
{Name: "reset_permissions", Verb: "permissions reset",
|
||||
Help: "Make this channel use the server-wide default list of super users again."},
|
||||
{Name: "dm_permission", Verb: "dm", Required: true,
|
||||
Help: "Allow or forbid everyone changing a setting on their own DM container. User managers only.",
|
||||
Args: "A permission and on or off, like `storage off`"},
|
||||
{Name: "managers", Verb: "managers", Shows: true,
|
||||
Help: "Show, add or remove user managers.",
|
||||
Args: "`add <@U012AB>` or `remove <@U012AB>`. Empty lists them"},
|
||||
}
|
||||
|
||||
func commandNamed(name string) (SlackCommand, bool) {
|
||||
for _, c := range Commands {
|
||||
if c.Name == name {
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
return SlackCommand{}, false
|
||||
}
|
||||
|
||||
func (c SlackCommand) Text(args string) string {
|
||||
return strings.TrimSpace(c.Verb + " " + strings.TrimSpace(args))
|
||||
}
|
||||
|
||||
// Missing calls are refused by the server, so the bot doesn't run them.
|
||||
func (c SlackCommand) Missing(args string) bool {
|
||||
return c.Required && strings.TrimSpace(args) == ""
|
||||
}
|
||||
|
||||
func (c SlackCommand) Changes(args string) bool {
|
||||
return !c.Shows || strings.TrimSpace(args) != ""
|
||||
}
|
||||
|
||||
// Reply is what the bot answers a command call with.
|
||||
type Reply struct {
|
||||
Text string `json:"text"`
|
||||
Error bool `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// The MCP server can't reach the bot, so the bot runs the command when it
|
||||
// sees the call over ACP and drops the reply here for the server to pick up.
|
||||
// The server only knows the tool and its args, so they name the file.
|
||||
func replyDir(home string) string { return filepath.Join(home, ".slackerbot", "replies") }
|
||||
|
||||
func replyPrefix(name, args string) string {
|
||||
sum := sha256.Sum256([]byte(name + "\x00" + strings.TrimSpace(args)))
|
||||
return hex.EncodeToString(sum[:8]) + "-"
|
||||
}
|
||||
|
||||
func ReplyPath(home, name, args string) string {
|
||||
return filepath.Join(replyDir(home), replyPrefix(name, args)+util.RandomHex(6)+".json")
|
||||
}
|
||||
|
||||
func argsOf(raw json.RawMessage) string {
|
||||
var in struct {
|
||||
Args string `json:"args"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &in)
|
||||
return in.Args
|
||||
}
|
||||
|
||||
// toolName is the slackerbot tool an ACP tool call is for. Goose names it in
|
||||
// _meta, and older versions only in the title ("slackerbot: send file · …").
|
||||
func toolName(u acp.Update) (string, bool) {
|
||||
if name, ok := strings.CutPrefix(u.ToolName, ServerName+"__"); ok {
|
||||
return name, true
|
||||
}
|
||||
best := ""
|
||||
for _, name := range append([]string{SendFile}, commandNames()...) {
|
||||
t := ServerName + ": " + strings.ReplaceAll(name, "_", " ")
|
||||
if (u.Title == t || strings.HasPrefix(u.Title, t+" ")) && len(name) > len(best) {
|
||||
best = name
|
||||
}
|
||||
}
|
||||
return best, best != ""
|
||||
}
|
||||
|
||||
func commandNames() []string {
|
||||
names := make([]string, len(Commands))
|
||||
for i, c := range Commands {
|
||||
names[i] = c.Name
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// CommandCall reports whether an ACP update starts a command tool call, and with which args.
|
||||
func CommandCall(u acp.Update) (c SlackCommand, args string, ok bool) {
|
||||
if u.Kind != "tool_call" {
|
||||
return SlackCommand{}, "", false
|
||||
}
|
||||
name, ok := toolName(u)
|
||||
if !ok {
|
||||
return SlackCommand{}, "", false
|
||||
}
|
||||
c, ok = commandNamed(name)
|
||||
return c, argsOf(u.RawInput), ok
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"slackerbot/internal/acp"
|
||||
)
|
||||
|
||||
func TestEveryCommandIsListed(t *testing.T) {
|
||||
s := &Server{Home: t.TempDir(), MaxMB: 1}
|
||||
var names []string
|
||||
for _, tool := range s.tools() {
|
||||
names = append(names, tool.(map[string]any)["name"].(string))
|
||||
}
|
||||
for _, want := range []string{"send_file", "status", "sessions", "nodes", "permissions", "stop", "scale", "keep",
|
||||
"storage", "move", "listen", "grant", "revoke", "reset_permissions", "dm_permission", "managers"} {
|
||||
if !strings.Contains(" "+strings.Join(names, " ")+" ", " "+want+" ") {
|
||||
t.Fatalf("%s missing from %v", want, names)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandWaitsForTheBotsReply(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
s := &Server{Home: home, MaxMB: 1, Wait: 300 * time.Millisecond}
|
||||
os.MkdirAll(replyDir(home), 0o755)
|
||||
old := ReplyPath(home, "keep", "24h")
|
||||
os.WriteFile(old, []byte(`{"text":"stale"}`), 0o644)
|
||||
os.Chtimes(old, time.Now().Add(-time.Hour), time.Now().Add(-time.Hour))
|
||||
|
||||
inR, inW := io.Pipe()
|
||||
var out bytes.Buffer
|
||||
done := make(chan error)
|
||||
go func() { done <- s.Serve(inR, &out) }()
|
||||
inW.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"keep","arguments":{"args":" 24h"}}}` + "\n"))
|
||||
inW.Write([]byte(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"scale","arguments":{}}}` + "\n"))
|
||||
inW.Write([]byte(`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"nodes","arguments":{}}}` + "\n"))
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
data, _ := json.Marshal(Reply{Text: "Done! 24h."})
|
||||
os.WriteFile(ReplyPath(home, "keep", "24h"), data, 0o644)
|
||||
inW.Close()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := map[int]string{}
|
||||
errs := map[int]bool{}
|
||||
for _, line := range strings.Split(strings.TrimSpace(out.String()), "\n") {
|
||||
var r struct {
|
||||
ID int
|
||||
Result struct {
|
||||
Content []struct{ Text string }
|
||||
IsError bool
|
||||
}
|
||||
}
|
||||
_ = json.Unmarshal([]byte(line), &r)
|
||||
got[r.ID], errs[r.ID] = r.Result.Content[0].Text, r.Result.IsError
|
||||
}
|
||||
if got[1] != "Done! 24h." || errs[1] {
|
||||
t.Fatalf("keep: %q", got[1])
|
||||
}
|
||||
if !strings.Contains(got[2], "args is required") || !errs[2] {
|
||||
t.Fatalf("scale without args: %q", got[2])
|
||||
}
|
||||
if !strings.Contains(got[3], "didn't answer in time") || !errs[3] {
|
||||
t.Fatalf("unanswered: %q", got[3])
|
||||
}
|
||||
if left, _ := os.ReadDir(replyDir(home)); len(left) != 0 {
|
||||
t.Fatalf("replies should be cleaned up, left %v", left)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandCall(t *testing.T) {
|
||||
c, args, ok := CommandCall(acp.Update{Kind: "tool_call", ToolName: "slackerbot__reset_permissions"})
|
||||
if !ok || c.Text(args) != "permissions reset" {
|
||||
t.Fatalf("by tool name: %+v %q %v", c, args, ok)
|
||||
}
|
||||
c, args, ok = CommandCall(acp.Update{Kind: "tool_call", Title: "slackerbot: scale · up", RawInput: json.RawMessage(`{"args":"up"}`)})
|
||||
if !ok || c.Text(args) != "scale up" {
|
||||
t.Fatalf("by title: %+v %q %v", c, args, ok)
|
||||
}
|
||||
if _, _, ok := CommandCall(acp.Update{Kind: "tool_call", ToolName: "slackerbot__send_file"}); ok {
|
||||
t.Fatal("send_file isn't a command")
|
||||
}
|
||||
if _, _, ok := CommandCall(acp.Update{Kind: "tool_call", ToolName: "developer__shell", Title: "status"}); ok {
|
||||
t.Fatal("other servers' tools aren't commands")
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -22,9 +24,20 @@ const sendFileHelp = "Send a file to the user in Slack: images, videos, PDFs, ar
|
||||
"It's uploaded into the conversation when your turn ends, so mention it in your reply. " +
|
||||
"At most a few files per turn."
|
||||
|
||||
const commandNote = " It's the same as the Slack command `%s`, and runs with the permissions of the person whose message you're answering."
|
||||
|
||||
const (
|
||||
defaultWait = time.Minute
|
||||
pollEvery = 200 * time.Millisecond
|
||||
// A reply older than this when a call starts belongs to an earlier call that gave up.
|
||||
staleAfter = 30 * time.Second
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Home string
|
||||
MaxMB int64
|
||||
// How long a command waits for the bot. Zero means a minute.
|
||||
Wait time.Duration
|
||||
}
|
||||
|
||||
type msg struct {
|
||||
@@ -45,20 +58,105 @@ func (s *Server) Serve(in io.Reader, out io.Writer) error {
|
||||
sc := bufio.NewScanner(in)
|
||||
sc.Buffer(make([]byte, 1<<20), 16<<20)
|
||||
enc := json.NewEncoder(out)
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
write := func(reply msg) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return enc.Encode(reply)
|
||||
}
|
||||
for sc.Scan() {
|
||||
var m msg
|
||||
if json.Unmarshal(sc.Bytes(), &m) != nil || len(m.ID) == 0 {
|
||||
continue
|
||||
}
|
||||
reply := msg{JSONRPC: "2.0", ID: m.ID}
|
||||
// Commands wait on the bot, so they mustn't hold up other requests.
|
||||
if c, args, ok := s.commandCall(m); ok {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
reply.Result = toolResult(s.await(c, args))
|
||||
_ = write(reply)
|
||||
}()
|
||||
continue
|
||||
}
|
||||
reply.Result, reply.Error = s.handle(m)
|
||||
if err := enc.Encode(reply); err != nil {
|
||||
if err := write(reply); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return sc.Err()
|
||||
}
|
||||
|
||||
func toolResult(text string, isErr bool) map[string]any {
|
||||
return map[string]any{"content": []any{map[string]string{"type": "text", "text": text}}, "isError": isErr}
|
||||
}
|
||||
|
||||
func (s *Server) commandCall(m msg) (SlackCommand, string, bool) {
|
||||
if m.Method != "tools/call" {
|
||||
return SlackCommand{}, "", false
|
||||
}
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
_ = json.Unmarshal(m.Params, &p)
|
||||
c, ok := commandNamed(p.Name)
|
||||
return c, argsOf(p.Arguments), ok
|
||||
}
|
||||
|
||||
func (s *Server) await(c SlackCommand, args string) (string, bool) {
|
||||
if c.Missing(args) {
|
||||
return "args is required: " + c.Args, true
|
||||
}
|
||||
wait := s.Wait
|
||||
if wait == 0 {
|
||||
wait = defaultWait
|
||||
}
|
||||
start := time.Now()
|
||||
for {
|
||||
if r, ok := claimReply(replyDir(s.Home), replyPrefix(c.Name, args), start); ok {
|
||||
return r.Text, r.Error
|
||||
}
|
||||
if time.Since(start) > wait {
|
||||
return "slackerbot didn't answer in time, so it may not have run. Its master may be too old for this tool, " +
|
||||
"or the home folder may be full. Ask the user to send the command in Slack instead: " + c.Text(args), true
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
}
|
||||
|
||||
// claimReply takes a reply by deleting it, so two waiting calls can't both get it.
|
||||
// The bot writes a file in one go, so one that doesn't parse yet is still being written.
|
||||
func claimReply(dir, prefix string, since time.Time) (Reply, bool) {
|
||||
entries, _ := os.ReadDir(dir)
|
||||
for _, e := range entries {
|
||||
if !strings.HasPrefix(e.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(dir, e.Name())
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if info.ModTime().Before(since.Add(-staleAfter)) {
|
||||
_ = os.Remove(p)
|
||||
continue
|
||||
}
|
||||
data, err := os.ReadFile(p)
|
||||
var r Reply
|
||||
if err != nil || json.Unmarshal(data, &r) != nil {
|
||||
continue
|
||||
}
|
||||
if os.Remove(p) == nil {
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
return Reply{}, false
|
||||
}
|
||||
|
||||
func (s *Server) handle(m msg) (any, *rpcError) {
|
||||
switch m.Method {
|
||||
case "initialize":
|
||||
@@ -74,18 +172,7 @@ func (s *Server) handle(m msg) (any, *rpcError) {
|
||||
case "ping":
|
||||
return map[string]any{}, nil
|
||||
case "tools/list":
|
||||
return map[string]any{"tools": []any{map[string]any{
|
||||
"name": SendFile,
|
||||
"description": fmt.Sprintf(sendFileHelp, s.Home, s.MaxMB),
|
||||
"inputSchema": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"path": map[string]string{"type": "string", "description": "Path of the file, e.g. " + s.Home + "/out/chart.png"},
|
||||
"comment": map[string]string{"type": "string", "description": "Optional message posted with the file"},
|
||||
},
|
||||
"required": []string{"path"},
|
||||
},
|
||||
}}}, nil
|
||||
return map[string]any{"tools": s.tools()}, nil
|
||||
case "tools/call":
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
@@ -101,11 +188,45 @@ func (s *Server) handle(m msg) (any, *rpcError) {
|
||||
if err := s.Check(p.Arguments.Path); err != nil {
|
||||
text, isErr = err.Error(), true
|
||||
}
|
||||
return map[string]any{"content": []any{map[string]string{"type": "text", "text": text}}, "isError": isErr}, nil
|
||||
return toolResult(text, isErr), nil
|
||||
}
|
||||
return nil, &rpcError{-32601, "method not found: " + m.Method}
|
||||
}
|
||||
|
||||
func (s *Server) tools() []any {
|
||||
list := []any{map[string]any{
|
||||
"name": SendFile,
|
||||
"description": fmt.Sprintf(sendFileHelp, s.Home, s.MaxMB),
|
||||
"inputSchema": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"path": map[string]string{"type": "string", "description": "Path of the file, e.g. " + s.Home + "/out/chart.png"},
|
||||
"comment": map[string]string{"type": "string", "description": "Optional message posted with the file"},
|
||||
},
|
||||
"required": []string{"path"},
|
||||
},
|
||||
}}
|
||||
for _, c := range Commands {
|
||||
schema := map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
if c.Args != "" {
|
||||
schema["properties"] = map[string]any{"args": map[string]string{"type": "string", "description": c.Args}}
|
||||
}
|
||||
if c.Required {
|
||||
schema["required"] = []string{"args"}
|
||||
}
|
||||
usage := c.Verb
|
||||
if c.Args != "" {
|
||||
usage += " <args>"
|
||||
}
|
||||
list = append(list, map[string]any{
|
||||
"name": c.Name,
|
||||
"description": c.Help + fmt.Sprintf(commandNote, usage),
|
||||
"inputSchema": schema,
|
||||
})
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func (s *Server) Check(path string) error {
|
||||
if path == "" {
|
||||
return fmt.Errorf("path is required")
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"flag"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"slackerbot/internal/acp"
|
||||
@@ -47,8 +46,8 @@ type Calls struct {
|
||||
}
|
||||
|
||||
func isSendFile(u acp.Update) bool {
|
||||
return u.ToolName == ServerName+"__"+SendFile ||
|
||||
strings.HasPrefix(u.Title, ServerName+": "+strings.ReplaceAll(SendFile, "_", " "))
|
||||
name, ok := toolName(u)
|
||||
return ok && name == SendFile
|
||||
}
|
||||
|
||||
func (c *Calls) Update(u acp.Update) {
|
||||
|
||||
Reference in new issue
Block a user