♻️ Quality: demo.acp.sdk/go without smells (3 → 0)
- Start with launch (the three pipes, then start); the mm binary with cmp.Or (option, MM_BIN, mm) - newToolbox's checks as toolbox.check - prompt.go (a turn's relay and end) and stderr.go (mm's stderr tail) Checked: go test, and the five examples (complete, stream, permission refused/allowed, cancel, clienttools) built from the old and the new code against mm with a scripted fake model: identical output (the position of mm's stderr line in stream is a race, same order 6 times out of 6 on reruns). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2e11277 parent: 833db52 modified
demo.acp.sdk/go/agent.go +29 -149 | @@ -1,7 +1,7 @@ | ||
| 1 | 1 | package minime |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | - "bufio" | |
| 4 | + "cmp" | |
| 5 | 5 | "context" |
| 6 | 6 | "errors" |
| 7 | 7 | "fmt" |
| @@ -69,21 +69,11 @@ func Start(ctx context.Context, opts Options) (*Agent, error) { | ||
| 69 | 69 | if err != nil { |
| 70 | 70 | return nil, err |
| 71 | 71 | } |
| 72 | - stdin, err := cmd.StdinPipe() | |
| 72 | + p, err := launch(cmd) | |
| 73 | 73 | if err != nil { |
| 74 | - return nil, fmt.Errorf("minime: %w", err) | |
| 75 | - } | |
| 76 | - stdout, err := cmd.StdoutPipe() | |
| 77 | - if err != nil { | |
| 78 | - return nil, fmt.Errorf("minime: %w", err) | |
| 79 | - } | |
| 80 | - stderr, err := cmd.StderrPipe() | |
| 81 | - if err != nil { | |
| 82 | - return nil, fmt.Errorf("minime: %w", err) | |
| 83 | - } | |
| 84 | - if err := cmd.Start(); err != nil { | |
| 85 | - return nil, fmt.Errorf("minime: cannot start %s: %w", cmd.Path, err) | |
| 74 | + return nil, err | |
| 86 | 75 | } |
| 76 | + stdin, stdout, stderr := p.stdin, p.stdout, p.stderr | |
| 87 | 77 | |
| 88 | 78 | a := &Agent{ |
| 89 | 79 | cmd: cmd, |
| @@ -112,6 +102,30 @@ func Start(ctx context.Context, opts Options) (*Agent, error) { | ||
| 112 | 102 | return a, nil |
| 113 | 103 | } |
| 114 | 104 | |
| 105 | +// procPipes are mm's standard streams, seen from this side. | |
| 106 | +type procPipes struct { | |
| 107 | + stdin io.WriteCloser | |
| 108 | + stdout, stderr io.ReadCloser | |
| 109 | +} | |
| 110 | + | |
| 111 | +// launch connects mm's three streams and starts it. | |
| 112 | +func launch(cmd *exec.Cmd) (procPipes, error) { | |
| 113 | + var p procPipes | |
| 114 | + var err error | |
| 115 | + if p.stdin, err = cmd.StdinPipe(); err == nil { | |
| 116 | + if p.stdout, err = cmd.StdoutPipe(); err == nil { | |
| 117 | + p.stderr, err = cmd.StderrPipe() | |
| 118 | + } | |
| 119 | + } | |
| 120 | + if err != nil { | |
| 121 | + return procPipes{}, fmt.Errorf("minime: %w", err) | |
| 122 | + } | |
| 123 | + if err := cmd.Start(); err != nil { | |
| 124 | + return procPipes{}, fmt.Errorf("minime: cannot start %s: %w", cmd.Path, err) | |
| 125 | + } | |
| 126 | + return p, nil | |
| 127 | +} | |
| 128 | + | |
| 115 | 129 | // command builds the mm command line from the options, with absolute paths. |
| 116 | 130 | func command(opts Options) (*exec.Cmd, string, error) { |
| 117 | 131 | if opts.Config == "" { |
| @@ -125,13 +139,7 @@ func command(opts Options) (*exec.Cmd, string, error) { | ||
| 125 | 139 | if err != nil { |
| 126 | 140 | return nil, "", fmt.Errorf("minime: %w", err) |
| 127 | 141 | } |
| 128 | - mm := opts.MM | |
| 129 | - if mm == "" { | |
| 130 | - mm = os.Getenv("MM_BIN") | |
| 131 | - } | |
| 132 | - if mm == "" { | |
| 133 | - mm = "mm" | |
| 134 | - } | |
| 142 | + mm := cmp.Or(opts.MM, os.Getenv("MM_BIN"), "mm") | |
| 135 | 143 | cmd := exec.Command(mm, "-acp", "-config", config) |
| 136 | 144 | cmd.Dir = cwd |
| 137 | 145 | return cmd, cwd, nil |
| @@ -218,98 +226,6 @@ func (a *Agent) Stream(ctx context.Context, prompt string) iter.Seq2[Event, erro | ||
| 218 | 226 | } |
| 219 | 227 | } |
| 220 | 228 | |
| 221 | -// promptOutcome is what session/prompt returned. | |
| 222 | -type promptOutcome struct { | |
| 223 | - resp sdk.PromptResponse | |
| 224 | - err error | |
| 225 | -} | |
| 226 | - | |
| 227 | -// run is one turn: it sends session/prompt and relays the events until mm | |
| 228 | -// answers. The prompt runs under its own context, not the caller's: a | |
| 229 | -// cancelled caller sends session/cancel and waits for mm's "cancelled" | |
| 230 | -// answer (ACP's contract) instead of abandoning the request. | |
| 231 | -func (a *Agent) run(ctx context.Context, prompt string, yield func(Event, error) bool) { | |
| 232 | - t := newTurn(ctx, a.sessionID) | |
| 233 | - a.client.begin(t) | |
| 234 | - defer a.client.end() | |
| 235 | - | |
| 236 | - promptCtx, abandon := context.WithCancel(context.Background()) | |
| 237 | - defer abandon() | |
| 238 | - done := make(chan promptOutcome, 1) | |
| 239 | - go func() { | |
| 240 | - resp, err := a.conn.Prompt(promptCtx, sdk.PromptRequest{ | |
| 241 | - SessionId: a.sessionID, | |
| 242 | - Prompt: []sdk.ContentBlock{sdk.TextBlock(prompt)}, | |
| 243 | - }) | |
| 244 | - done <- promptOutcome{resp, err} | |
| 245 | - }() | |
| 246 | - | |
| 247 | - callerDone := ctx.Done() | |
| 248 | - var giveUp <-chan time.Time | |
| 249 | - cancel := func() { | |
| 250 | - if t.cancelled.Swap(true) { | |
| 251 | - return | |
| 252 | - } | |
| 253 | - _ = a.conn.Cancel(context.WithoutCancel(ctx), sdk.CancelNotification{SessionId: a.sessionID}) | |
| 254 | - giveUp = time.After(cancelGrace) | |
| 255 | - } | |
| 256 | - reading := true // false once the caller left the loop: events are then dropped | |
| 257 | - for { | |
| 258 | - select { | |
| 259 | - case <-t.wake: | |
| 260 | - reading = a.relay(t.take(), reading, yield, cancel) | |
| 261 | - case <-callerDone: | |
| 262 | - callerDone = nil // select it once | |
| 263 | - cancel() | |
| 264 | - case <-giveUp: | |
| 265 | - abandon() // mm did not answer the cancel: give up the request | |
| 266 | - giveUp = nil | |
| 267 | - case out := <-done: | |
| 268 | - if reading { | |
| 269 | - a.finish(t, out, promptCtx.Err() != nil, yield) | |
| 270 | - } | |
| 271 | - return | |
| 272 | - } | |
| 273 | - } | |
| 274 | -} | |
| 275 | - | |
| 276 | -// relay hands the queued events to the caller while it reads; when it stops | |
| 277 | -// reading, the turn is cancelled and the rest is dropped. | |
| 278 | -func (a *Agent) relay(events []Event, reading bool, yield func(Event, error) bool, cancel func()) bool { | |
| 279 | - for _, ev := range events { | |
| 280 | - if reading && !yield(ev, nil) { | |
| 281 | - reading = false | |
| 282 | - cancel() | |
| 283 | - } | |
| 284 | - } | |
| 285 | - return reading | |
| 286 | -} | |
| 287 | - | |
| 288 | -// finish yields the events still queued, then the KindDone event, or the | |
| 289 | -// error that ended the turn. abandoned says that run gave the request up | |
| 290 | -// after mm left a cancel unanswered. | |
| 291 | -func (a *Agent) finish(t *turn, out promptOutcome, abandoned bool, yield func(Event, error) bool) { | |
| 292 | - for _, ev := range t.take() { | |
| 293 | - if !yield(ev, nil) { | |
| 294 | - return | |
| 295 | - } | |
| 296 | - } | |
| 297 | - if out.err != nil { | |
| 298 | - if abandoned { | |
| 299 | - yield(Event{}, errors.New("minime: mm did not answer the cancelled turn in time")) | |
| 300 | - return | |
| 301 | - } | |
| 302 | - yield(Event{}, a.failure("turn failed", out.err)) | |
| 303 | - return | |
| 304 | - } | |
| 305 | - yield(Event{ | |
| 306 | - Kind: KindDone, | |
| 307 | - Text: t.answer(), | |
| 308 | - StopReason: string(out.resp.StopReason), | |
| 309 | - Usage: usageOf(out.resp.Usage), | |
| 310 | - }, nil) | |
| 311 | -} | |
| 312 | - | |
| 313 | 229 | // Reset forgets the conversation: a new ACP session on the same mm process. |
| 314 | 230 | // |
| 315 | 231 | // if err := agent.Reset(ctx); err != nil { |
| @@ -394,39 +310,3 @@ func rpcMessage(err error) string { | ||
| 394 | 310 | } |
| 395 | 311 | return msg |
| 396 | 312 | } |
| 397 | - | |
| 398 | -// stderrTail keeps the last line mm wrote on stderr. | |
| 399 | -type stderrTail struct { | |
| 400 | - mu sync.Mutex | |
| 401 | - line string | |
| 402 | -} | |
| 403 | - | |
| 404 | -// follow reads r line by line until it ends, keeping the last non-empty line | |
| 405 | -// and handing every line to onLine when it is set. The returned channel is | |
| 406 | -// closed once r is read to its end. | |
| 407 | -func (s *stderrTail) follow(r io.Reader, onLine func(string)) <-chan struct{} { | |
| 408 | - done := make(chan struct{}) | |
| 409 | - go func() { | |
| 410 | - defer close(done) | |
| 411 | - scanner := bufio.NewScanner(r) | |
| 412 | - scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) | |
| 413 | - for scanner.Scan() { | |
| 414 | - line := scanner.Text() | |
| 415 | - if onLine != nil { | |
| 416 | - onLine(line) | |
| 417 | - } | |
| 418 | - if line != "" { | |
| 419 | - s.mu.Lock() | |
| 420 | - s.line = line | |
| 421 | - s.mu.Unlock() | |
| 422 | - } | |
| 423 | - } | |
| 424 | - }() | |
| 425 | - return done | |
| 426 | -} | |
| 427 | - | |
| 428 | -func (s *stderrTail) last() string { | |
| 429 | - s.mu.Lock() | |
| 430 | - defer s.mu.Unlock() | |
| 431 | - return s.line | |
| 432 | -} | |
| @@ -1,7 +1,7 @@ | |||
| 1 | package minime | 1 | package minime |
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | - "bufio" | 4 | + "cmp" |
| 5 | "context" | 5 | "context" |
| 6 | "errors" | 6 | "errors" |
| 7 | "fmt" | 7 | "fmt" |
| @@ -69,21 +69,11 @@ func Start(ctx context.Context, opts Options) (*Agent, error) { | |||
| 69 | if err != nil { | 69 | if err != nil { |
| 70 | return nil, err | 70 | return nil, err |
| 71 | } | 71 | } |
| 72 | - stdin, err := cmd.StdinPipe() | 72 | + p, err := launch(cmd) |
| 73 | if err != nil { | 73 | if err != nil { |
| 74 | - return nil, fmt.Errorf("minime: %w", err) | 74 | + return nil, err |
| 75 | - } | ||
| 76 | - stdout, err := cmd.StdoutPipe() | ||
| 77 | - if err != nil { | ||
| 78 | - return nil, fmt.Errorf("minime: %w", err) | ||
| 79 | - } | ||
| 80 | - stderr, err := cmd.StderrPipe() | ||
| 81 | - if err != nil { | ||
| 82 | - return nil, fmt.Errorf("minime: %w", err) | ||
| 83 | - } | ||
| 84 | - if err := cmd.Start(); err != nil { | ||
| 85 | - return nil, fmt.Errorf("minime: cannot start %s: %w", cmd.Path, err) | ||
| 86 | } | 75 | } |
| 76 | + stdin, stdout, stderr := p.stdin, p.stdout, p.stderr | ||
| 87 | 77 | ||
| 88 | a := &Agent{ | 78 | a := &Agent{ |
| 89 | cmd: cmd, | 79 | cmd: cmd, |
| @@ -112,6 +102,30 @@ func Start(ctx context.Context, opts Options) (*Agent, error) { | |||
| 112 | return a, nil | 102 | return a, nil |
| 113 | } | 103 | } |
| 114 | 104 | ||
| 105 | +// procPipes are mm's standard streams, seen from this side. | ||
| 106 | +type procPipes struct { | ||
| 107 | + stdin io.WriteCloser | ||
| 108 | + stdout, stderr io.ReadCloser | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +// launch connects mm's three streams and starts it. | ||
| 112 | +func launch(cmd *exec.Cmd) (procPipes, error) { | ||
| 113 | + var p procPipes | ||
| 114 | + var err error | ||
| 115 | + if p.stdin, err = cmd.StdinPipe(); err == nil { | ||
| 116 | + if p.stdout, err = cmd.StdoutPipe(); err == nil { | ||
| 117 | + p.stderr, err = cmd.StderrPipe() | ||
| 118 | + } | ||
| 119 | + } | ||
| 120 | + if err != nil { | ||
| 121 | + return procPipes{}, fmt.Errorf("minime: %w", err) | ||
| 122 | + } | ||
| 123 | + if err := cmd.Start(); err != nil { | ||
| 124 | + return procPipes{}, fmt.Errorf("minime: cannot start %s: %w", cmd.Path, err) | ||
| 125 | + } | ||
| 126 | + return p, nil | ||
| 127 | +} | ||
| 128 | + | ||
| 115 | // command builds the mm command line from the options, with absolute paths. | 129 | // command builds the mm command line from the options, with absolute paths. |
| 116 | func command(opts Options) (*exec.Cmd, string, error) { | 130 | func command(opts Options) (*exec.Cmd, string, error) { |
| 117 | if opts.Config == "" { | 131 | if opts.Config == "" { |
| @@ -125,13 +139,7 @@ func command(opts Options) (*exec.Cmd, string, error) { | |||
| 125 | if err != nil { | 139 | if err != nil { |
| 126 | return nil, "", fmt.Errorf("minime: %w", err) | 140 | return nil, "", fmt.Errorf("minime: %w", err) |
| 127 | } | 141 | } |
| 128 | - mm := opts.MM | 142 | + mm := cmp.Or(opts.MM, os.Getenv("MM_BIN"), "mm") |
| 129 | - if mm == "" { | ||
| 130 | - mm = os.Getenv("MM_BIN") | ||
| 131 | - } | ||
| 132 | - if mm == "" { | ||
| 133 | - mm = "mm" | ||
| 134 | - } | ||
| 135 | cmd := exec.Command(mm, "-acp", "-config", config) | 143 | cmd := exec.Command(mm, "-acp", "-config", config) |
| 136 | cmd.Dir = cwd | 144 | cmd.Dir = cwd |
| 137 | return cmd, cwd, nil | 145 | return cmd, cwd, nil |
| @@ -218,98 +226,6 @@ func (a *Agent) Stream(ctx context.Context, prompt string) iter.Seq2[Event, erro | |||
| 218 | } | 226 | } |
| 219 | } | 227 | } |
| 220 | 228 | ||
| 221 | -// promptOutcome is what session/prompt returned. | ||
| 222 | -type promptOutcome struct { | ||
| 223 | - resp sdk.PromptResponse | ||
| 224 | - err error | ||
| 225 | -} | ||
| 226 | - | ||
| 227 | -// run is one turn: it sends session/prompt and relays the events until mm | ||
| 228 | -// answers. The prompt runs under its own context, not the caller's: a | ||
| 229 | -// cancelled caller sends session/cancel and waits for mm's "cancelled" | ||
| 230 | -// answer (ACP's contract) instead of abandoning the request. | ||
| 231 | -func (a *Agent) run(ctx context.Context, prompt string, yield func(Event, error) bool) { | ||
| 232 | - t := newTurn(ctx, a.sessionID) | ||
| 233 | - a.client.begin(t) | ||
| 234 | - defer a.client.end() | ||
| 235 | - | ||
| 236 | - promptCtx, abandon := context.WithCancel(context.Background()) | ||
| 237 | - defer abandon() | ||
| 238 | - done := make(chan promptOutcome, 1) | ||
| 239 | - go func() { | ||
| 240 | - resp, err := a.conn.Prompt(promptCtx, sdk.PromptRequest{ | ||
| 241 | - SessionId: a.sessionID, | ||
| 242 | - Prompt: []sdk.ContentBlock{sdk.TextBlock(prompt)}, | ||
| 243 | - }) | ||
| 244 | - done <- promptOutcome{resp, err} | ||
| 245 | - }() | ||
| 246 | - | ||
| 247 | - callerDone := ctx.Done() | ||
| 248 | - var giveUp <-chan time.Time | ||
| 249 | - cancel := func() { | ||
| 250 | - if t.cancelled.Swap(true) { | ||
| 251 | - return | ||
| 252 | - } | ||
| 253 | - _ = a.conn.Cancel(context.WithoutCancel(ctx), sdk.CancelNotification{SessionId: a.sessionID}) | ||
| 254 | - giveUp = time.After(cancelGrace) | ||
| 255 | - } | ||
| 256 | - reading := true // false once the caller left the loop: events are then dropped | ||
| 257 | - for { | ||
| 258 | - select { | ||
| 259 | - case <-t.wake: | ||
| 260 | - reading = a.relay(t.take(), reading, yield, cancel) | ||
| 261 | - case <-callerDone: | ||
| 262 | - callerDone = nil // select it once | ||
| 263 | - cancel() | ||
| 264 | - case <-giveUp: | ||
| 265 | - abandon() // mm did not answer the cancel: give up the request | ||
| 266 | - giveUp = nil | ||
| 267 | - case out := <-done: | ||
| 268 | - if reading { | ||
| 269 | - a.finish(t, out, promptCtx.Err() != nil, yield) | ||
| 270 | - } | ||
| 271 | - return | ||
| 272 | - } | ||
| 273 | - } | ||
| 274 | -} | ||
| 275 | - | ||
| 276 | -// relay hands the queued events to the caller while it reads; when it stops | ||
| 277 | -// reading, the turn is cancelled and the rest is dropped. | ||
| 278 | -func (a *Agent) relay(events []Event, reading bool, yield func(Event, error) bool, cancel func()) bool { | ||
| 279 | - for _, ev := range events { | ||
| 280 | - if reading && !yield(ev, nil) { | ||
| 281 | - reading = false | ||
| 282 | - cancel() | ||
| 283 | - } | ||
| 284 | - } | ||
| 285 | - return reading | ||
| 286 | -} | ||
| 287 | - | ||
| 288 | -// finish yields the events still queued, then the KindDone event, or the | ||
| 289 | -// error that ended the turn. abandoned says that run gave the request up | ||
| 290 | -// after mm left a cancel unanswered. | ||
| 291 | -func (a *Agent) finish(t *turn, out promptOutcome, abandoned bool, yield func(Event, error) bool) { | ||
| 292 | - for _, ev := range t.take() { | ||
| 293 | - if !yield(ev, nil) { | ||
| 294 | - return | ||
| 295 | - } | ||
| 296 | - } | ||
| 297 | - if out.err != nil { | ||
| 298 | - if abandoned { | ||
| 299 | - yield(Event{}, errors.New("minime: mm did not answer the cancelled turn in time")) | ||
| 300 | - return | ||
| 301 | - } | ||
| 302 | - yield(Event{}, a.failure("turn failed", out.err)) | ||
| 303 | - return | ||
| 304 | - } | ||
| 305 | - yield(Event{ | ||
| 306 | - Kind: KindDone, | ||
| 307 | - Text: t.answer(), | ||
| 308 | - StopReason: string(out.resp.StopReason), | ||
| 309 | - Usage: usageOf(out.resp.Usage), | ||
| 310 | - }, nil) | ||
| 311 | -} | ||
| 312 | - | ||
| 313 | // Reset forgets the conversation: a new ACP session on the same mm process. | 229 | // Reset forgets the conversation: a new ACP session on the same mm process. |
| 314 | // | 230 | // |
| 315 | // if err := agent.Reset(ctx); err != nil { | 231 | // if err := agent.Reset(ctx); err != nil { |
| @@ -394,39 +310,3 @@ func rpcMessage(err error) string { | |||
| 394 | } | 310 | } |
| 395 | return msg | 311 | return msg |
| 396 | } | 312 | } |
| 397 | - | ||
| 398 | -// stderrTail keeps the last line mm wrote on stderr. | ||
| 399 | -type stderrTail struct { | ||
| 400 | - mu sync.Mutex | ||
| 401 | - line string | ||
| 402 | -} | ||
| 403 | - | ||
| 404 | -// follow reads r line by line until it ends, keeping the last non-empty line | ||
| 405 | -// and handing every line to onLine when it is set. The returned channel is | ||
| 406 | -// closed once r is read to its end. | ||
| 407 | -func (s *stderrTail) follow(r io.Reader, onLine func(string)) <-chan struct{} { | ||
| 408 | - done := make(chan struct{}) | ||
| 409 | - go func() { | ||
| 410 | - defer close(done) | ||
| 411 | - scanner := bufio.NewScanner(r) | ||
| 412 | - scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) | ||
| 413 | - for scanner.Scan() { | ||
| 414 | - line := scanner.Text() | ||
| 415 | - if onLine != nil { | ||
| 416 | - onLine(line) | ||
| 417 | - } | ||
| 418 | - if line != "" { | ||
| 419 | - s.mu.Lock() | ||
| 420 | - s.line = line | ||
| 421 | - s.mu.Unlock() | ||
| 422 | - } | ||
| 423 | - } | ||
| 424 | - }() | ||
| 425 | - return done | ||
| 426 | -} | ||
| 427 | - | ||
| 428 | -func (s *stderrTail) last() string { | ||
| 429 | - s.mu.Lock() | ||
| 430 | - defer s.mu.Unlock() | ||
| 431 | - return s.line | ||
| 432 | -} | ||
added
demo.acp.sdk/go/prompt.go +101 -0 | new file mode 100644 | ||
| @@ -0,0 +1,101 @@ | ||
| 1 | +package minime | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "errors" | |
| 6 | + "time" | |
| 7 | + | |
| 8 | + sdk "github.com/coder/acp-go-sdk" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// promptOutcome is what session/prompt returned. | |
| 12 | +type promptOutcome struct { | |
| 13 | + resp sdk.PromptResponse | |
| 14 | + err error | |
| 15 | +} | |
| 16 | + | |
| 17 | +// run is one turn: it sends session/prompt and relays the events until mm | |
| 18 | +// answers. The prompt runs under its own context, not the caller's: a | |
| 19 | +// cancelled caller sends session/cancel and waits for mm's "cancelled" | |
| 20 | +// answer (ACP's contract) instead of abandoning the request. | |
| 21 | +func (a *Agent) run(ctx context.Context, prompt string, yield func(Event, error) bool) { | |
| 22 | + t := newTurn(ctx, a.sessionID) | |
| 23 | + a.client.begin(t) | |
| 24 | + defer a.client.end() | |
| 25 | + | |
| 26 | + promptCtx, abandon := context.WithCancel(context.Background()) | |
| 27 | + defer abandon() | |
| 28 | + done := make(chan promptOutcome, 1) | |
| 29 | + go func() { | |
| 30 | + resp, err := a.conn.Prompt(promptCtx, sdk.PromptRequest{ | |
| 31 | + SessionId: a.sessionID, | |
| 32 | + Prompt: []sdk.ContentBlock{sdk.TextBlock(prompt)}, | |
| 33 | + }) | |
| 34 | + done <- promptOutcome{resp, err} | |
| 35 | + }() | |
| 36 | + | |
| 37 | + callerDone := ctx.Done() | |
| 38 | + var giveUp <-chan time.Time | |
| 39 | + cancel := func() { | |
| 40 | + if t.cancelled.Swap(true) { | |
| 41 | + return | |
| 42 | + } | |
| 43 | + _ = a.conn.Cancel(context.WithoutCancel(ctx), sdk.CancelNotification{SessionId: a.sessionID}) | |
| 44 | + giveUp = time.After(cancelGrace) | |
| 45 | + } | |
| 46 | + reading := true // false once the caller left the loop: events are then dropped | |
| 47 | + for { | |
| 48 | + select { | |
| 49 | + case <-t.wake: | |
| 50 | + reading = a.relay(t.take(), reading, yield, cancel) | |
| 51 | + case <-callerDone: | |
| 52 | + callerDone = nil // select it once | |
| 53 | + cancel() | |
| 54 | + case <-giveUp: | |
| 55 | + abandon() // mm did not answer the cancel: give up the request | |
| 56 | + giveUp = nil | |
| 57 | + case out := <-done: | |
| 58 | + if reading { | |
| 59 | + a.finish(t, out, promptCtx.Err() != nil, yield) | |
| 60 | + } | |
| 61 | + return | |
| 62 | + } | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +// relay hands the queued events to the caller while it reads; when it stops | |
| 67 | +// reading, the turn is cancelled and the rest is dropped. | |
| 68 | +func (a *Agent) relay(events []Event, reading bool, yield func(Event, error) bool, cancel func()) bool { | |
| 69 | + for _, ev := range events { | |
| 70 | + if reading && !yield(ev, nil) { | |
| 71 | + reading = false | |
| 72 | + cancel() | |
| 73 | + } | |
| 74 | + } | |
| 75 | + return reading | |
| 76 | +} | |
| 77 | + | |
| 78 | +// finish yields the events still queued, then the KindDone event, or the | |
| 79 | +// error that ended the turn. abandoned says that run gave the request up | |
| 80 | +// after mm left a cancel unanswered. | |
| 81 | +func (a *Agent) finish(t *turn, out promptOutcome, abandoned bool, yield func(Event, error) bool) { | |
| 82 | + for _, ev := range t.take() { | |
| 83 | + if !yield(ev, nil) { | |
| 84 | + return | |
| 85 | + } | |
| 86 | + } | |
| 87 | + if out.err != nil { | |
| 88 | + if abandoned { | |
| 89 | + yield(Event{}, errors.New("minime: mm did not answer the cancelled turn in time")) | |
| 90 | + return | |
| 91 | + } | |
| 92 | + yield(Event{}, a.failure("turn failed", out.err)) | |
| 93 | + return | |
| 94 | + } | |
| 95 | + yield(Event{ | |
| 96 | + Kind: KindDone, | |
| 97 | + Text: t.answer(), | |
| 98 | + StopReason: string(out.resp.StopReason), | |
| 99 | + Usage: usageOf(out.resp.Usage), | |
| 100 | + }, nil) | |
| 101 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,101 @@ | |||
| 1 | +package minime | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "errors" | ||
| 6 | + "time" | ||
| 7 | + | ||
| 8 | + sdk "github.com/coder/acp-go-sdk" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// promptOutcome is what session/prompt returned. | ||
| 12 | +type promptOutcome struct { | ||
| 13 | + resp sdk.PromptResponse | ||
| 14 | + err error | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +// run is one turn: it sends session/prompt and relays the events until mm | ||
| 18 | +// answers. The prompt runs under its own context, not the caller's: a | ||
| 19 | +// cancelled caller sends session/cancel and waits for mm's "cancelled" | ||
| 20 | +// answer (ACP's contract) instead of abandoning the request. | ||
| 21 | +func (a *Agent) run(ctx context.Context, prompt string, yield func(Event, error) bool) { | ||
| 22 | + t := newTurn(ctx, a.sessionID) | ||
| 23 | + a.client.begin(t) | ||
| 24 | + defer a.client.end() | ||
| 25 | + | ||
| 26 | + promptCtx, abandon := context.WithCancel(context.Background()) | ||
| 27 | + defer abandon() | ||
| 28 | + done := make(chan promptOutcome, 1) | ||
| 29 | + go func() { | ||
| 30 | + resp, err := a.conn.Prompt(promptCtx, sdk.PromptRequest{ | ||
| 31 | + SessionId: a.sessionID, | ||
| 32 | + Prompt: []sdk.ContentBlock{sdk.TextBlock(prompt)}, | ||
| 33 | + }) | ||
| 34 | + done <- promptOutcome{resp, err} | ||
| 35 | + }() | ||
| 36 | + | ||
| 37 | + callerDone := ctx.Done() | ||
| 38 | + var giveUp <-chan time.Time | ||
| 39 | + cancel := func() { | ||
| 40 | + if t.cancelled.Swap(true) { | ||
| 41 | + return | ||
| 42 | + } | ||
| 43 | + _ = a.conn.Cancel(context.WithoutCancel(ctx), sdk.CancelNotification{SessionId: a.sessionID}) | ||
| 44 | + giveUp = time.After(cancelGrace) | ||
| 45 | + } | ||
| 46 | + reading := true // false once the caller left the loop: events are then dropped | ||
| 47 | + for { | ||
| 48 | + select { | ||
| 49 | + case <-t.wake: | ||
| 50 | + reading = a.relay(t.take(), reading, yield, cancel) | ||
| 51 | + case <-callerDone: | ||
| 52 | + callerDone = nil // select it once | ||
| 53 | + cancel() | ||
| 54 | + case <-giveUp: | ||
| 55 | + abandon() // mm did not answer the cancel: give up the request | ||
| 56 | + giveUp = nil | ||
| 57 | + case out := <-done: | ||
| 58 | + if reading { | ||
| 59 | + a.finish(t, out, promptCtx.Err() != nil, yield) | ||
| 60 | + } | ||
| 61 | + return | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +// relay hands the queued events to the caller while it reads; when it stops | ||
| 67 | +// reading, the turn is cancelled and the rest is dropped. | ||
| 68 | +func (a *Agent) relay(events []Event, reading bool, yield func(Event, error) bool, cancel func()) bool { | ||
| 69 | + for _, ev := range events { | ||
| 70 | + if reading && !yield(ev, nil) { | ||
| 71 | + reading = false | ||
| 72 | + cancel() | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | + return reading | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +// finish yields the events still queued, then the KindDone event, or the | ||
| 79 | +// error that ended the turn. abandoned says that run gave the request up | ||
| 80 | +// after mm left a cancel unanswered. | ||
| 81 | +func (a *Agent) finish(t *turn, out promptOutcome, abandoned bool, yield func(Event, error) bool) { | ||
| 82 | + for _, ev := range t.take() { | ||
| 83 | + if !yield(ev, nil) { | ||
| 84 | + return | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | + if out.err != nil { | ||
| 88 | + if abandoned { | ||
| 89 | + yield(Event{}, errors.New("minime: mm did not answer the cancelled turn in time")) | ||
| 90 | + return | ||
| 91 | + } | ||
| 92 | + yield(Event{}, a.failure("turn failed", out.err)) | ||
| 93 | + return | ||
| 94 | + } | ||
| 95 | + yield(Event{ | ||
| 96 | + Kind: KindDone, | ||
| 97 | + Text: t.answer(), | ||
| 98 | + StopReason: string(out.resp.StopReason), | ||
| 99 | + Usage: usageOf(out.resp.Usage), | ||
| 100 | + }, nil) | ||
| 101 | +} | ||
added
demo.acp.sdk/go/stderr.go +43 -0 | new file mode 100644 | ||
| @@ -0,0 +1,43 @@ | ||
| 1 | +package minime | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "bufio" | |
| 5 | + "io" | |
| 6 | + "sync" | |
| 7 | +) | |
| 8 | + | |
| 9 | +// stderrTail keeps the last line mm wrote on stderr. | |
| 10 | +type stderrTail struct { | |
| 11 | + mu sync.Mutex | |
| 12 | + line string | |
| 13 | +} | |
| 14 | + | |
| 15 | +// follow reads r line by line until it ends, keeping the last non-empty line | |
| 16 | +// and handing every line to onLine when it is set. The returned channel is | |
| 17 | +// closed once r is read to its end. | |
| 18 | +func (s *stderrTail) follow(r io.Reader, onLine func(string)) <-chan struct{} { | |
| 19 | + done := make(chan struct{}) | |
| 20 | + go func() { | |
| 21 | + defer close(done) | |
| 22 | + scanner := bufio.NewScanner(r) | |
| 23 | + scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) | |
| 24 | + for scanner.Scan() { | |
| 25 | + line := scanner.Text() | |
| 26 | + if onLine != nil { | |
| 27 | + onLine(line) | |
| 28 | + } | |
| 29 | + if line != "" { | |
| 30 | + s.mu.Lock() | |
| 31 | + s.line = line | |
| 32 | + s.mu.Unlock() | |
| 33 | + } | |
| 34 | + } | |
| 35 | + }() | |
| 36 | + return done | |
| 37 | +} | |
| 38 | + | |
| 39 | +func (s *stderrTail) last() string { | |
| 40 | + s.mu.Lock() | |
| 41 | + defer s.mu.Unlock() | |
| 42 | + return s.line | |
| 43 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,43 @@ | |||
| 1 | +package minime | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "bufio" | ||
| 5 | + "io" | ||
| 6 | + "sync" | ||
| 7 | +) | ||
| 8 | + | ||
| 9 | +// stderrTail keeps the last line mm wrote on stderr. | ||
| 10 | +type stderrTail struct { | ||
| 11 | + mu sync.Mutex | ||
| 12 | + line string | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +// follow reads r line by line until it ends, keeping the last non-empty line | ||
| 16 | +// and handing every line to onLine when it is set. The returned channel is | ||
| 17 | +// closed once r is read to its end. | ||
| 18 | +func (s *stderrTail) follow(r io.Reader, onLine func(string)) <-chan struct{} { | ||
| 19 | + done := make(chan struct{}) | ||
| 20 | + go func() { | ||
| 21 | + defer close(done) | ||
| 22 | + scanner := bufio.NewScanner(r) | ||
| 23 | + scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) | ||
| 24 | + for scanner.Scan() { | ||
| 25 | + line := scanner.Text() | ||
| 26 | + if onLine != nil { | ||
| 27 | + onLine(line) | ||
| 28 | + } | ||
| 29 | + if line != "" { | ||
| 30 | + s.mu.Lock() | ||
| 31 | + s.line = line | ||
| 32 | + s.mu.Unlock() | ||
| 33 | + } | ||
| 34 | + } | ||
| 35 | + }() | ||
| 36 | + return done | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +func (s *stderrTail) last() string { | ||
| 40 | + s.mu.Lock() | ||
| 41 | + defer s.mu.Unlock() | ||
| 42 | + return s.line | ||
| 43 | +} | ||
modified
demo.acp.sdk/go/tools.go +22 -11 | @@ -116,17 +116,8 @@ func newToolbox(tools []Tool, discovery string) (*toolbox, error) { | ||
| 116 | 116 | if t.Method == "" { |
| 117 | 117 | t.Method = defaultToolPrefix + t.Name |
| 118 | 118 | } |
| 119 | - switch { | |
| 120 | - case strings.TrimSpace(t.Name) == "": | |
| 121 | - return nil, errors.New("minime: a Tool has no Name") | |
| 122 | - case names[t.Name]: | |
| 123 | - return nil, fmt.Errorf("minime: two tools are named %q", t.Name) | |
| 124 | - case !strings.HasPrefix(t.Method, "_"): | |
| 125 | - return nil, fmt.Errorf("minime: tool %q: Method %q must start with \"_\"", t.Name, t.Method) | |
| 126 | - case t.Method == toolsListMethod || box.byMethod[t.Method].Handle != nil: | |
| 127 | - return nil, fmt.Errorf("minime: tool %q: Method %q is already taken", t.Name, t.Method) | |
| 128 | - case t.Handle == nil: | |
| 129 | - return nil, fmt.Errorf("minime: tool %q has no Handle", t.Name) | |
| 119 | + if err := box.check(t, names); err != nil { | |
| 120 | + return nil, err | |
| 130 | 121 | } |
| 131 | 122 | names[t.Name] = true |
| 132 | 123 | box.byMethod[t.Method] = t |
| @@ -135,6 +126,26 @@ func newToolbox(tools []Tool, discovery string) (*toolbox, error) { | ||
| 135 | 126 | return box, nil |
| 136 | 127 | } |
| 137 | 128 | |
| 129 | +// check says what is wrong with tool t among the ones already in the box | |
| 130 | +// (names): no name, a name or a method taken, a method that is not an ACP | |
| 131 | +// extension, no handler. | |
| 132 | +func (b *toolbox) check(t Tool, names map[string]bool) error { | |
| 133 | + var err error | |
| 134 | + switch { | |
| 135 | + case strings.TrimSpace(t.Name) == "": | |
| 136 | + err = errors.New("minime: a Tool has no Name") | |
| 137 | + case names[t.Name]: | |
| 138 | + err = fmt.Errorf("minime: two tools are named %q", t.Name) | |
| 139 | + case !strings.HasPrefix(t.Method, "_"): | |
| 140 | + err = fmt.Errorf("minime: tool %q: Method %q must start with \"_\"", t.Name, t.Method) | |
| 141 | + case t.Method == toolsListMethod || b.byMethod[t.Method].Handle != nil: | |
| 142 | + err = fmt.Errorf("minime: tool %q: Method %q is already taken", t.Name, t.Method) | |
| 143 | + case t.Handle == nil: | |
| 144 | + err = fmt.Errorf("minime: tool %q has no Handle", t.Name) | |
| 145 | + } | |
| 146 | + return err | |
| 147 | +} | |
| 148 | + | |
| 138 | 149 | // capabilities is the clientCapabilities._meta sent at initialize: the list |
| 139 | 150 | // itself (meta), `true` (request), or nothing when there is no tool. |
| 140 | 151 | func (b *toolbox) capabilities() map[string]any { |
| @@ -116,17 +116,8 @@ func newToolbox(tools []Tool, discovery string) (*toolbox, error) { | |||
| 116 | if t.Method == "" { | 116 | if t.Method == "" { |
| 117 | t.Method = defaultToolPrefix + t.Name | 117 | t.Method = defaultToolPrefix + t.Name |
| 118 | } | 118 | } |
| 119 | - switch { | 119 | + if err := box.check(t, names); err != nil { |
| 120 | - case strings.TrimSpace(t.Name) == "": | 120 | + return nil, err |
| 121 | - return nil, errors.New("minime: a Tool has no Name") | ||
| 122 | - case names[t.Name]: | ||
| 123 | - return nil, fmt.Errorf("minime: two tools are named %q", t.Name) | ||
| 124 | - case !strings.HasPrefix(t.Method, "_"): | ||
| 125 | - return nil, fmt.Errorf("minime: tool %q: Method %q must start with \"_\"", t.Name, t.Method) | ||
| 126 | - case t.Method == toolsListMethod || box.byMethod[t.Method].Handle != nil: | ||
| 127 | - return nil, fmt.Errorf("minime: tool %q: Method %q is already taken", t.Name, t.Method) | ||
| 128 | - case t.Handle == nil: | ||
| 129 | - return nil, fmt.Errorf("minime: tool %q has no Handle", t.Name) | ||
| 130 | } | 121 | } |
| 131 | names[t.Name] = true | 122 | names[t.Name] = true |
| 132 | box.byMethod[t.Method] = t | 123 | box.byMethod[t.Method] = t |
| @@ -135,6 +126,26 @@ func newToolbox(tools []Tool, discovery string) (*toolbox, error) { | |||
| 135 | return box, nil | 126 | return box, nil |
| 136 | } | 127 | } |
| 137 | 128 | ||
| 129 | +// check says what is wrong with tool t among the ones already in the box | ||
| 130 | +// (names): no name, a name or a method taken, a method that is not an ACP | ||
| 131 | +// extension, no handler. | ||
| 132 | +func (b *toolbox) check(t Tool, names map[string]bool) error { | ||
| 133 | + var err error | ||
| 134 | + switch { | ||
| 135 | + case strings.TrimSpace(t.Name) == "": | ||
| 136 | + err = errors.New("minime: a Tool has no Name") | ||
| 137 | + case names[t.Name]: | ||
| 138 | + err = fmt.Errorf("minime: two tools are named %q", t.Name) | ||
| 139 | + case !strings.HasPrefix(t.Method, "_"): | ||
| 140 | + err = fmt.Errorf("minime: tool %q: Method %q must start with \"_\"", t.Name, t.Method) | ||
| 141 | + case t.Method == toolsListMethod || b.byMethod[t.Method].Handle != nil: | ||
| 142 | + err = fmt.Errorf("minime: tool %q: Method %q is already taken", t.Name, t.Method) | ||
| 143 | + case t.Handle == nil: | ||
| 144 | + err = fmt.Errorf("minime: tool %q has no Handle", t.Name) | ||
| 145 | + } | ||
| 146 | + return err | ||
| 147 | +} | ||
| 148 | + | ||
| 138 | // capabilities is the clientCapabilities._meta sent at initialize: the list | 149 | // capabilities is the clientCapabilities._meta sent at initialize: the list |
| 139 | // itself (meta), `true` (request), or nothing when there is no tool. | 150 | // itself (meta), `true` (request), or nothing when there is no tool. |
| 140 | func (b *toolbox) capabilities() map[string]any { | 151 | func (b *toolbox) capabilities() map[string]any { |