restart fix + slack commands

This commit is contained in:
ari committed 2026-11-01 15:10:39 -05:00
1 parent e90c9f324b
commit 25fcf85855
22 files changed
+1077 -119

No files matched your search

+135 -14
View File
@@ -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")