Files
slacker-bot/slackerbot/internal/acp/acp.go
T
2026-11-01 14:55:33 -05:00

322 lines
7.6 KiB
Go

package acp
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"sync/atomic"
"slackerbot/internal/node"
)
type Update struct {
Kind string
Text string
Title string
Status string
ToolID string
ToolName string
RawInput json.RawMessage
}
// MCP servers started inside the container for every session.
type MCPServer struct {
Name string `json:"name"`
Command string `json:"command"`
Args []string `json:"args"`
Env []any `json:"env"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *rpcError) Error() string { return fmt.Sprintf("agent error %d: %s", e.Code, e.Message) }
type rpcMsg struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
type ACP struct {
conn node.MsgConn
nextID atomic.Int64
writeMu sync.Mutex
mu sync.Mutex
pending map[int64]chan rpcMsg
handlers map[string]func(Update)
loaded map[string]bool
CanLoad bool
Servers []MCPServer
done chan struct{}
err error
}
func DialACP(ctx context.Context, addr, secret string) (*ACP, error) {
conn, err := node.DialAgentWS(ctx, addr, secret)
if err != nil {
return nil, err
}
return New(ctx, conn)
}
func New(ctx context.Context, conn node.MsgConn) (*ACP, error) {
a := &ACP{
conn: conn,
pending: map[int64]chan rpcMsg{},
handlers: map[string]func(Update){},
loaded: map[string]bool{},
done: make(chan struct{}),
}
go a.readLoop()
var init struct {
AgentCapabilities struct {
LoadSession bool `json:"loadSession"`
} `json:"agentCapabilities"`
}
err := a.call(ctx, "initialize", map[string]any{
"protocolVersion": 1,
"clientCapabilities": map[string]any{
"fs": map[string]bool{"readTextFile": false, "writeTextFile": false},
"terminal": false,
},
}, &init)
if err != nil {
a.Close()
return nil, err
}
a.CanLoad = init.AgentCapabilities.LoadSession
return a, nil
}
func (a *ACP) Done() <-chan struct{} { return a.done }
func (a *ACP) Close() { a.conn.Close() }
func (a *ACP) NewSession(ctx context.Context, cwd string) (string, error) {
var res struct {
SessionID string `json:"sessionId"`
}
if err := a.call(ctx, "session/new", map[string]any{"cwd": cwd, "mcpServers": a.servers()}, &res); err != nil {
return "", err
}
a.mu.Lock()
a.loaded[res.SessionID] = true
a.mu.Unlock()
return res.SessionID, nil
}
// The agent replays the session's history as updates; Slack already shows it, so they're dropped.
func (a *ACP) LoadSession(ctx context.Context, id, cwd string) error {
a.mu.Lock()
open := a.loaded[id]
a.mu.Unlock()
if open {
return nil
}
if !a.CanLoad {
return errors.New("this agent can't reopen old sessions")
}
if err := a.call(ctx, "session/load", map[string]any{"sessionId": id, "cwd": cwd, "mcpServers": a.servers()}, nil); err != nil {
return err
}
a.mu.Lock()
a.loaded[id] = true
a.mu.Unlock()
return nil
}
func (a *ACP) servers() []MCPServer {
if a.Servers == nil {
return []MCPServer{}
}
return a.Servers
}
func (a *ACP) Prompt(ctx context.Context, id, text string, onUpdate func(Update)) (stopReason string, err error) {
a.mu.Lock()
a.handlers[id] = onUpdate
a.mu.Unlock()
defer func() {
a.mu.Lock()
delete(a.handlers, id)
a.mu.Unlock()
}()
var res struct {
StopReason string `json:"stopReason"`
}
err = a.call(ctx, "session/prompt", map[string]any{
"sessionId": id,
"prompt": []map[string]string{{"type": "text", "text": text}},
}, &res)
if ctx.Err() != nil {
a.notify("session/cancel", map[string]string{"sessionId": id})
}
return res.StopReason, err
}
func (a *ACP) call(ctx context.Context, method string, params, result any) error {
id := a.nextID.Add(1)
ch := make(chan rpcMsg, 1)
a.mu.Lock()
a.pending[id] = ch
a.mu.Unlock()
defer func() {
a.mu.Lock()
delete(a.pending, id)
a.mu.Unlock()
}()
p, _ := json.Marshal(params)
idRaw, _ := json.Marshal(id)
if err := a.send(ctx, rpcMsg{JSONRPC: "2.0", ID: idRaw, Method: method, Params: p}); err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-a.done:
return fmt.Errorf("connection to goose closed: %w", a.err)
case msg := <-ch:
if msg.Error != nil {
return msg.Error
}
if result != nil && len(msg.Result) > 0 && string(msg.Result) != "null" {
return json.Unmarshal(msg.Result, result)
}
return nil
}
}
func (a *ACP) notify(method string, params any) {
p, _ := json.Marshal(params)
_ = a.send(context.Background(), rpcMsg{JSONRPC: "2.0", Method: method, Params: p})
}
func (a *ACP) send(ctx context.Context, msg rpcMsg) error {
b, err := json.Marshal(msg)
if err != nil {
return err
}
a.writeMu.Lock()
defer a.writeMu.Unlock()
return a.conn.Write(ctx, b)
}
func (a *ACP) readLoop() {
defer close(a.done)
for {
data, err := a.conn.Read(context.Background())
if err != nil {
a.err = err
return
}
var msg rpcMsg
if json.Unmarshal(data, &msg) != nil {
continue
}
switch {
case msg.Method != "" && len(msg.ID) > 0:
go a.handleRequest(msg)
case msg.Method == "session/update":
a.handleUpdate(msg.Params)
case msg.Method == "" && len(msg.ID) > 0:
var id int64
if json.Unmarshal(msg.ID, &id) == nil {
a.mu.Lock()
ch := a.pending[id]
a.mu.Unlock()
if ch != nil {
ch <- msg
}
}
}
}
}
func (a *ACP) handleUpdate(params json.RawMessage) {
var p struct {
SessionID string `json:"sessionId"`
Update struct {
Kind string `json:"sessionUpdate"`
Content json.RawMessage `json:"content"`
Title string `json:"title"`
Status string `json:"status"`
ToolID string `json:"toolCallId"`
Input json.RawMessage `json:"rawInput"`
Meta struct {
Goose struct {
ToolCall struct {
ToolName string `json:"toolName"`
} `json:"toolCall"`
} `json:"goose"`
} `json:"_meta"`
} `json:"update"`
}
if json.Unmarshal(params, &p) != nil {
return
}
u := Update{Kind: p.Update.Kind, Title: p.Update.Title, Status: p.Update.Status,
ToolID: p.Update.ToolID, ToolName: p.Update.Meta.Goose.ToolCall.ToolName, RawInput: p.Update.Input}
// Message chunks carry one content block; tool updates carry a list.
var block struct {
Type string `json:"type"`
Text string `json:"text"`
}
if json.Unmarshal(p.Update.Content, &block) == nil && block.Type == "text" {
u.Text = block.Text
}
a.mu.Lock()
h := a.handlers[p.SessionID]
a.mu.Unlock()
if h != nil {
h(u)
}
}
// Tool permission requests are auto-approved: the container is the sandbox.
func (a *ACP) handleRequest(msg rpcMsg) {
reply := rpcMsg{JSONRPC: "2.0", ID: msg.ID}
switch msg.Method {
case "session/request_permission":
var p struct {
Options []struct {
OptionID string `json:"optionId"`
Kind string `json:"kind"`
} `json:"options"`
}
_ = json.Unmarshal(msg.Params, &p)
choice := ""
for _, want := range []string{"allow_always", "allow_once"} {
for _, o := range p.Options {
if o.Kind == want && choice == "" {
choice = o.OptionID
}
}
}
var outcome any = map[string]string{"outcome": "cancelled"}
if choice != "" {
outcome = map[string]string{"outcome": "selected", "optionId": choice}
}
reply.Result, _ = json.Marshal(map[string]any{"outcome": outcome})
default:
reply.Error = &rpcError{Code: -32601, Message: "method not supported by this client: " + msg.Method}
}
_ = a.send(context.Background(), reply)
}