1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
|
// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
// Command acp-trace is a throwaway spike (issue #2): it drives one ACP agent
// with github.com/coder/acp-go-sdk and records every JSON-RPC line exchanged,
// so the ADR can rely on real traffic instead of the specification alone.
//
// Usage:
//
// go run . -agent alice -out ../../docs/spikes/acp/traces/alice.jsonl \
// -prompt "Hello, who are you?" -prompt "Thanks!"
//
// The agent is started through scripts/agents.sh, which enforces the
// two-agents limit and unloads the model when the agent exits.
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
acp "github.com/coder/acp-go-sdk"
)
type promptList []string
func (p *promptList) String() string { return strings.Join(*p, " | ") }
func (p *promptList) Set(v string) error { *p = append(*p, v); return nil }
func main() {
var prompts promptList
agent := flag.String("agent", "alice", "agent folder name under agents/")
out := flag.String("out", "trace.jsonl", "file receiving the JSON-RPC lines")
permission := flag.String("permission", "allow", "answer to permission requests: allow, reject or cancel")
cancelAfter := flag.Duration("cancel-after", 0, "send session/cancel this long after the last prompt starts (0 = never)")
flag.Var(&prompts, "prompt", "prompt to send, repeatable")
flag.Parse()
if err := run(*agent, *out, *permission, *cancelAfter, prompts); err != nil {
fmt.Fprintln(os.Stderr, "acp-trace:", err)
os.Exit(1)
}
}
func run(agent, out, permission string, cancelAfter time.Duration, prompts []string) error {
repoRoot, err := filepath.Abs("../..")
if err != nil {
return err
}
trace, err := newTraceFile(out)
if err != nil {
return err
}
defer trace.Close()
cmd := exec.Command(filepath.Join(repoRoot, "scripts", "agents.sh"), "run", agent)
cmd.Stderr = os.Stderr
agentStdin, err := cmd.StdinPipe()
if err != nil {
return err
}
agentStdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
defer func() {
_ = agentStdin.Close()
_ = cmd.Wait()
}()
client := &printingClient{permission: permission}
conn := acp.NewClientSideConnection(client, trace.tee("client→agent", agentStdin), trace.teeReader("agent→client", agentStdout))
ctx, stop := context.WithTimeout(context.Background(), 10*time.Minute)
defer stop()
initResp, err := conn.Initialize(ctx, acp.InitializeRequest{
ProtocolVersion: acp.ProtocolVersionNumber,
ClientCapabilities: acp.ClientCapabilities{},
ClientInfo: &acp.Implementation{Name: "sidekicks-acp-trace", Version: "0.0.0"},
})
if err != nil {
return fmt.Errorf("initialize: %w", err)
}
fmt.Printf("== agent: %+v\n== protocol version: %d\n", initResp.AgentInfo, initResp.ProtocolVersion)
session, err := conn.NewSession(ctx, acp.NewSessionRequest{
Cwd: filepath.Join(repoRoot, "agents", agent),
McpServers: []acp.McpServer{},
})
if err != nil {
return fmt.Errorf("session/new: %w", err)
}
fmt.Println("== session:", session.SessionId)
for i, text := range prompts {
fmt.Printf("\n>> %s\n", text)
if cancelAfter > 0 && i == len(prompts)-1 {
time.AfterFunc(cancelAfter, func() {
fmt.Println("\n== sending session/cancel")
_ = conn.Cancel(ctx, acp.CancelNotification{SessionId: session.SessionId})
})
}
resp, err := conn.Prompt(ctx, acp.PromptRequest{
SessionId: session.SessionId,
Prompt: []acp.ContentBlock{acp.TextBlock(text)},
})
if err != nil {
return fmt.Errorf("session/prompt: %w", err)
}
fmt.Printf("\n== stop reason: %s\n", resp.StopReason)
}
return nil
}
// printingClient answers the agent's requests the way a test needs: it prints
// the streamed updates and answers permission requests with a fixed choice.
type printingClient struct {
permission string
}
func (c *printingClient) RequestPermission(_ context.Context, p acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) {
fmt.Printf("\n== permission requested for %q, options:", p.ToolCall.ToolCallId)
for _, option := range p.Options {
fmt.Printf(" [%s %s]", option.Kind, option.OptionId)
}
fmt.Println(" → answering", c.permission)
if c.permission == "cancel" {
return acp.RequestPermissionResponse{Outcome: acp.RequestPermissionOutcome{Cancelled: &acp.RequestPermissionOutcomeCancelled{}}}, nil
}
wanted := map[string]acp.PermissionOptionKind{"allow": acp.PermissionOptionKindAllowOnce, "reject": acp.PermissionOptionKindRejectOnce}[c.permission]
for _, option := range p.Options {
if option.Kind == wanted {
return acp.RequestPermissionResponse{Outcome: acp.RequestPermissionOutcome{Selected: &acp.RequestPermissionOutcomeSelected{OptionId: option.OptionId}}}, nil
}
}
return acp.RequestPermissionResponse{}, errors.New("no permission option of kind " + string(wanted))
}
func (c *printingClient) SessionUpdate(_ context.Context, n acp.SessionNotification) error {
update := n.Update
switch {
case update.AgentMessageChunk != nil && update.AgentMessageChunk.Content.Text != nil:
fmt.Print(update.AgentMessageChunk.Content.Text.Text)
case update.AgentThoughtChunk != nil:
fmt.Print("·")
case update.ToolCall != nil:
fmt.Printf("\n[tool %s] %s (%s)\n", update.ToolCall.Kind, update.ToolCall.Title, update.ToolCall.Status)
case update.ToolCallUpdate != nil:
fmt.Printf("\n[tool update] %s → %v\n", update.ToolCallUpdate.ToolCallId, update.ToolCallUpdate.Status)
case update.AvailableCommandsUpdate != nil:
fmt.Printf("\n[commands] %d available\n", len(update.AvailableCommandsUpdate.AvailableCommands))
case update.Plan != nil:
fmt.Printf("\n[plan] %d entries\n", len(update.Plan.Entries))
}
return nil
}
// The spike advertises no fs/terminal capability, so the agent must not call these.
func (c *printingClient) ReadTextFile(context.Context, acp.ReadTextFileRequest) (acp.ReadTextFileResponse, error) {
return acp.ReadTextFileResponse{}, errors.New("fs/read_text_file not advertised")
}
func (c *printingClient) WriteTextFile(context.Context, acp.WriteTextFileRequest) (acp.WriteTextFileResponse, error) {
return acp.WriteTextFileResponse{}, errors.New("fs/write_text_file not advertised")
}
func (c *printingClient) CreateTerminal(context.Context, acp.CreateTerminalRequest) (acp.CreateTerminalResponse, error) {
return acp.CreateTerminalResponse{}, errors.New("terminal not advertised")
}
func (c *printingClient) KillTerminal(context.Context, acp.KillTerminalRequest) (acp.KillTerminalResponse, error) {
return acp.KillTerminalResponse{}, errors.New("terminal not advertised")
}
func (c *printingClient) TerminalOutput(context.Context, acp.TerminalOutputRequest) (acp.TerminalOutputResponse, error) {
return acp.TerminalOutputResponse{}, errors.New("terminal not advertised")
}
func (c *printingClient) ReleaseTerminal(context.Context, acp.ReleaseTerminalRequest) (acp.ReleaseTerminalResponse, error) {
return acp.ReleaseTerminalResponse{}, errors.New("terminal not advertised")
}
func (c *printingClient) WaitForTerminalExit(context.Context, acp.WaitForTerminalExitRequest) (acp.WaitForTerminalExitResponse, error) {
return acp.WaitForTerminalExitResponse{}, errors.New("terminal not advertised")
}
// traceFile writes one JSON object per JSON-RPC line: {"t", "dir", "msg"}.
type traceFile struct {
mu sync.Mutex
file *os.File
start time.Time
}
func newTraceFile(path string) (*traceFile, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, err
}
file, err := os.Create(path)
if err != nil {
return nil, err
}
return &traceFile{file: file, start: time.Now()}, nil
}
func (t *traceFile) Close() error { return t.file.Close() }
func (t *traceFile) record(direction string, line []byte) {
t.mu.Lock()
defer t.mu.Unlock()
entry := map[string]any{"ms": time.Since(t.start).Milliseconds(), "dir": direction}
if json.Valid(line) {
entry["msg"] = json.RawMessage(line)
} else {
entry["raw"] = string(line)
}
encoded, _ := json.Marshal(entry)
_, _ = t.file.Write(append(encoded, '\n'))
}
// tee returns a writer that records every complete line before forwarding it.
func (t *traceFile) tee(direction string, w io.Writer) io.Writer {
reader, writer := io.Pipe()
go func() {
scanner := bufio.NewScanner(reader)
scanner.Buffer(make([]byte, 1<<20), 16<<20)
for scanner.Scan() {
line := scanner.Bytes()
t.record(direction, line)
_, _ = w.Write(append(append([]byte{}, line...), '\n'))
}
}()
return writer
}
// teeReader returns a reader that records every complete line it delivers.
func (t *traceFile) teeReader(direction string, r io.Reader) io.Reader {
reader, writer := io.Pipe()
go func() {
scanner := bufio.NewScanner(r)
scanner.Buffer(make([]byte, 1<<20), 16<<20)
for scanner.Scan() {
line := scanner.Bytes()
t.record(direction, line)
_, _ = writer.Write(append(append([]byte{}, line...), '\n'))
}
_ = writer.CloseWithError(scanner.Err())
}()
return reader
}
|