clean up of the codebase
This commit is contained in:
1 parent
7822529a38
commit
0ac61b4ece
52 files changed
+2545
-2274
No files matched your search
@@ -0,0 +1,292 @@
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
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": []any{}}, &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": []any{}}, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.loaded[id] = true
|
||||
a.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
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"`
|
||||
} `json:"update"`
|
||||
}
|
||||
if json.Unmarshal(params, &p) != nil {
|
||||
return
|
||||
}
|
||||
u := Update{Kind: p.Update.Kind, Title: p.Update.Title, Status: p.Update.Status}
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package acp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
func fakeGoose(t *testing.T) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/acp" || r.Header.Get("X-Secret-Key") != "s3cret" {
|
||||
http.Error(w, "nope", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
c, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ctx := context.Background()
|
||||
send := func(v any) { b, _ := json.Marshal(v); _ = c.Write(ctx, websocket.MessageText, b) }
|
||||
var promptID json.RawMessage
|
||||
|
||||
for {
|
||||
_, data, err := c.Read(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var m rpcMsg
|
||||
_ = json.Unmarshal(data, &m)
|
||||
switch m.Method {
|
||||
case "initialize":
|
||||
send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": map[string]any{
|
||||
"protocolVersion": 1, "agentCapabilities": map[string]any{"loadSession": true}}})
|
||||
case "session/new":
|
||||
send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": map[string]any{"sessionId": "sess-1"}})
|
||||
case "session/load":
|
||||
send(map[string]any{"jsonrpc": "2.0", "method": "session/update", "params": map[string]any{
|
||||
"sessionId": "sess-old", "update": map[string]any{"sessionUpdate": "agent_message_chunk",
|
||||
"content": map[string]any{"type": "text", "text": "old history"}}}})
|
||||
send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": nil})
|
||||
case "session/prompt":
|
||||
promptID = m.ID
|
||||
upd := func(u map[string]any) {
|
||||
send(map[string]any{"jsonrpc": "2.0", "method": "session/update",
|
||||
"params": map[string]any{"sessionId": "sess-1", "update": u}})
|
||||
}
|
||||
upd(map[string]any{"sessionUpdate": "agent_message_chunk", "content": map[string]any{"type": "text", "text": "Hello "}})
|
||||
upd(map[string]any{"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "ls /root", "status": "pending"})
|
||||
send(map[string]any{"jsonrpc": "2.0", "id": "perm-1", "method": "session/request_permission",
|
||||
"params": map[string]any{"sessionId": "sess-1", "options": []map[string]any{
|
||||
{"optionId": "no", "name": "Reject", "kind": "reject_once"},
|
||||
{"optionId": "yes", "name": "Allow", "kind": "allow_once"}}}})
|
||||
case "":
|
||||
var res struct {
|
||||
Outcome struct{ Outcome, OptionID string } `json:"outcome"`
|
||||
}
|
||||
_ = json.Unmarshal(m.Result, &res)
|
||||
text := "world"
|
||||
if res.Outcome.OptionID != "yes" {
|
||||
text = "PERMISSION WRONG"
|
||||
}
|
||||
send(map[string]any{"jsonrpc": "2.0", "method": "session/update", "params": map[string]any{
|
||||
"sessionId": "sess-1", "update": map[string]any{"sessionUpdate": "agent_message_chunk",
|
||||
"content": map[string]any{"type": "text", "text": text}}}})
|
||||
send(map[string]any{"jsonrpc": "2.0", "id": promptID, "result": map[string]any{"stopReason": "end_turn"}})
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func TestACP(t *testing.T) {
|
||||
srv := fakeGoose(t)
|
||||
defer srv.Close()
|
||||
addr := strings.TrimPrefix(srv.URL, "http://")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if _, err := DialACP(ctx, addr, "wrong"); err == nil {
|
||||
t.Fatal("wrong secret should fail")
|
||||
}
|
||||
a, err := DialACP(ctx, addr, "s3cret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
if !a.CanLoad {
|
||||
t.Fatal("loadSession capability not read")
|
||||
}
|
||||
id, err := a.NewSession(ctx, "/root")
|
||||
if err != nil || id != "sess-1" {
|
||||
t.Fatalf("new session: %q %v", id, err)
|
||||
}
|
||||
if err := a.LoadSession(ctx, "sess-old", "/root"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var mu sync.Mutex
|
||||
var text strings.Builder
|
||||
var tools []string
|
||||
stop, err := a.Prompt(ctx, id, "hi", func(u Update) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
text.WriteString(u.Text)
|
||||
if u.Kind == "tool_call" {
|
||||
tools = append(tools, u.Title)
|
||||
}
|
||||
})
|
||||
if err != nil || stop != "end_turn" {
|
||||
t.Fatalf("prompt: %q %v", stop, err)
|
||||
}
|
||||
if text.String() != "Hello world" || len(tools) != 1 || tools[0] != "ls /root" {
|
||||
t.Fatalf("got text %q tools %v", text.String(), tools)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user