-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclaude.go
More file actions
618 lines (525 loc) · 17.5 KB
/
Copy pathclaude.go
File metadata and controls
618 lines (525 loc) · 17.5 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Package claude provides a wrapper around the Claude CLI.
// Supports both direct exec and tmux-based execution for large prompts.
package claude
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"strings"
"github.com/philjestin/boatmanmode/internal/cost"
"github.com/philjestin/boatmanmode/internal/retry"
"github.com/philjestin/boatmanmode/internal/tmux"
)
// Client wraps the Claude CLI.
type Client struct {
// Command is the claude command to use (default: "claude")
Command string
// WorkDir is the working directory for claude commands
WorkDir string
// Env is additional environment variables to set
Env map[string]string
// UseTmux enables tmux-based execution (better for large prompts)
UseTmux bool
// TmuxManager manages tmux sessions
TmuxManager *tmux.Manager
// SessionName is the name for tmux sessions
SessionName string
// Stream enables streaming output
Stream bool
// Debug enables debug output
Debug bool
// Model specifies which Claude model to use (e.g., "claude-opus-4-6", "claude-sonnet-4-6")
Model string
// Agent specifies a Claude CLI agent/skill to invoke.
Agent string
// Effort sets the reasoning effort level ("low", "medium", "high")
// Empty = CLI default. Only used with models that support extended thinking.
Effort string
// EnablePromptCaching enables prompt caching to reduce costs
EnablePromptCaching bool
// AllowedTools are the tools this client can use.
// Empty/nil means all tools allowed. Use []string{} to disable all tools.
AllowedTools []string
// EnableTools controls whether tools are enabled at all.
// If false, tools are explicitly disabled with --tools "".
EnableTools bool
// MCPConfigs are Claude Code --mcp-config JSON strings or file paths.
MCPConfigs []string
// SkipPermissions automatically approves all tool uses without user confirmation.
// WARNING: This is a security risk - only enable for trusted, non-interactive environments.
SkipPermissions bool
// EventForwarder, if set, is called for each raw stream-json line before parsing.
// This allows the desktop app to receive Claude's raw events for UI streaming.
EventForwarder func(rawLine string)
}
// StreamChunk represents a chunk from Claude's stream-json output.
type StreamChunk struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
Content string `json:"content"`
Delta struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"delta"`
Message struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
} `json:"message"`
// Result text (present in "result" type chunks, newer CLI versions)
Result string `json:"result"`
// Usage data (present in "result" type chunks)
Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheReadTokens int `json:"cache_read_input_tokens"`
CacheWriteTokens int `json:"cache_creation_input_tokens"`
} `json:"usage"`
TotalCostUSD float64 `json:"total_cost_usd"`
}
// New creates a new Claude CLI client.
func New() *Client {
return &Client{
Command: "claude",
Env: make(map[string]string),
Stream: true,
UseTmux: false,
Debug: os.Getenv("BOATMAN_DEBUG") == "1",
}
}
// NewWithWorkDir creates a client that runs in a specific directory.
func NewWithWorkDir(workDir string) *Client {
return &Client{
Command: "claude",
WorkDir: workDir,
Env: make(map[string]string),
Stream: true,
UseTmux: false,
Debug: os.Getenv("BOATMAN_DEBUG") == "1",
}
}
// NewWithTmux creates a client that uses tmux for execution.
func NewWithTmux(workDir, sessionName string) *Client {
return &Client{
Command: "claude",
WorkDir: workDir,
Env: make(map[string]string),
UseTmux: true,
TmuxManager: tmux.NewManager("boatman"),
SessionName: sessionName,
Stream: true,
Debug: os.Getenv("BOATMAN_DEBUG") == "1",
EnableTools: false, // Backward compatibility - tools disabled by default
}
}
// NewWithTools creates a client with specific tool permissions.
// tools: List of allowed tools (e.g., []string{"Read", "Grep", "Glob"})
// Pass nil to allow all tools.
// Pass []string{} to disable all tools.
func NewWithTools(workDir, sessionName string, tools []string) *Client {
return &Client{
Command: "claude",
WorkDir: workDir,
Env: make(map[string]string),
UseTmux: true,
TmuxManager: tmux.NewManager("boatman"),
SessionName: sessionName,
Stream: true,
Debug: os.Getenv("BOATMAN_DEBUG") == "1",
EnableTools: true,
AllowedTools: tools,
}
}
// Message sends a message to Claude and returns the response with usage data.
func (c *Client) Message(ctx context.Context, systemPrompt, userPrompt string) (string, *cost.Usage, error) {
// When BOATMAN_NO_TMUX=1 is set (e.g., by desktop app), bypass tmux and use
// direct streaming so EventForwarder can forward events to the UI.
noTmux := os.Getenv("BOATMAN_NO_TMUX") == "1"
// Use tmux for large prompts or when explicitly enabled (unless bypassed)
if !noTmux && (c.UseTmux || len(userPrompt) > 100000 || len(systemPrompt) > 50000) {
return c.messageTmux(ctx, systemPrompt, userPrompt)
}
if c.Stream {
return c.messageStreaming(ctx, systemPrompt, userPrompt)
}
return c.messageNonStreaming(ctx, systemPrompt, userPrompt)
}
// messageTmux sends a message using tmux session.
func (c *Client) messageTmux(ctx context.Context, systemPrompt, userPrompt string) (string, *cost.Usage, error) {
if c.TmuxManager == nil {
c.TmuxManager = tmux.NewManager("boatman")
}
sessionName := c.SessionName
if sessionName == "" {
sessionName = "claude"
}
sess, err := c.TmuxManager.CreateSession(sessionName, c.WorkDir)
if err != nil {
return "", nil, fmt.Errorf("failed to create tmux session: %w", err)
}
// Don't kill session on completion - let user inspect if needed
// defer c.TmuxManager.KillSession(sess)
opts := tmux.ClaudeOptions{
Model: c.Model,
EnablePromptCaching: c.EnablePromptCaching,
MCPConfigs: append([]string(nil), c.MCPConfigs...),
}
return c.TmuxManager.RunClaudeStreamingWithOptions(ctx, sess, systemPrompt, userPrompt, opts)
}
// messageStreaming sends a message and streams the response with retry support.
func (c *Client) messageStreaming(ctx context.Context, systemPrompt, userPrompt string) (string, *cost.Usage, error) {
var fullResponse string
var usage *cost.Usage
err := retry.Do(ctx, retry.CLIConfig(), "Claude CLI", func() error {
result, resultUsage, err := c.doStreamingRequest(ctx, systemPrompt, userPrompt)
if err != nil {
// Check for retryable error patterns
errStr := err.Error()
if strings.Contains(errStr, "rate limit") ||
strings.Contains(errStr, "overloaded") ||
strings.Contains(errStr, "temporarily") {
return err // Retryable
}
// Most CLI errors are permanent
return retry.Permanent(err)
}
fullResponse = result
usage = resultUsage
return nil
})
return fullResponse, usage, err
}
// streamResult holds the response and usage from streaming.
type streamResult struct {
response string
usage *cost.Usage
err error
}
// doStreamingRequest performs a single streaming request to Claude.
func (c *Client) doStreamingRequest(ctx context.Context, systemPrompt, userPrompt string) (string, *cost.Usage, error) {
args := c.streamingArgs()
// Note: Prompt caching is automatically handled by Claude CLI when using system prompts
// No explicit flag needed in current version (2.1.39+)
if systemPrompt != "" {
args = append(args, "--system-prompt", systemPrompt)
}
// For large prompts, pipe via stdin to avoid OS ARG_MAX limits.
// For small prompts, pass as command-line arg (current behavior).
useStdin := len(userPrompt) > 100000
if !useStdin {
args = append(args, userPrompt)
}
cmd := exec.CommandContext(ctx, c.Command, args...)
if c.WorkDir != "" {
cmd.Dir = c.WorkDir
}
// Get parent environment but filter out CLAUDECODE to allow nested Claude sessions
cmd.Env = filterParentEnv()
for k, v := range c.Env {
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
}
// Pipe large prompts via stdin
if useStdin {
cmd.Stdin = strings.NewReader(userPrompt)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", nil, fmt.Errorf("failed to get stdout pipe: %w", err)
}
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return "", nil, fmt.Errorf("failed to start claude: %w", err)
}
// Stream and collect the response
var fullResponse strings.Builder
var resultUsage *cost.Usage
fmt.Println(" ┌─────────────────────────────────────────────────────────────")
// Create a done channel to signal when reading is complete
readDone := make(chan streamResult, 1)
go func() {
lineBuffer := ""
var usage *cost.Usage
reader := bufio.NewReader(stdout)
for {
// Check for context cancellation between reads
select {
case <-ctx.Done():
readDone <- streamResult{err: ctx.Err()}
return
default:
}
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
// Print any remaining content
if lineBuffer != "" {
fmt.Printf(" │ %s\n", lineBuffer)
}
readDone <- streamResult{response: fullResponse.String(), usage: usage}
return
}
readDone <- streamResult{err: fmt.Errorf("error reading stream: %w", err)}
return
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Forward raw line to event forwarder before parsing
if c.EventForwarder != nil {
c.EventForwarder(line)
}
var chunk StreamChunk
if err := json.Unmarshal([]byte(line), &chunk); err != nil {
if c.Debug {
slog.Debug("failed to parse chunk", "chunk", line, "error", err)
}
continue
}
// Handle different chunk types
var text string
switch chunk.Type {
case "content_block_delta":
// With --verbose, text is in delta.text; without, it may be in content
if chunk.Delta.Text != "" {
text = chunk.Delta.Text
} else {
text = chunk.Content
}
case "assistant":
// Newer CLI versions emit full response as "assistant" type
for _, content := range chunk.Message.Content {
if content.Type == "text" {
text = content.Text
}
}
case "message_stop":
continue
case "result":
// Extract usage data from result chunk
usage = &cost.Usage{
InputTokens: chunk.Usage.InputTokens,
OutputTokens: chunk.Usage.OutputTokens,
CacheReadTokens: chunk.Usage.CacheReadTokens,
CacheWriteTokens: chunk.Usage.CacheWriteTokens,
TotalCostUSD: chunk.TotalCostUSD,
}
// Only capture response text from result if nothing was
// captured yet (avoids doubling with "assistant" chunk).
if fullResponse.Len() == 0 {
// Newer CLI: result text is in top-level "result" field
if chunk.Result != "" {
text = chunk.Result
}
// Older CLI: result text is in message.content
if text == "" {
for _, content := range chunk.Message.Content {
if content.Type == "text" {
text = content.Text
}
}
}
}
}
if text != "" {
fullResponse.WriteString(text)
// Stream to terminal with formatting
lineBuffer += text
for {
idx := strings.Index(lineBuffer, "\n")
if idx == -1 {
break
}
fmt.Printf(" │ %s\n", lineBuffer[:idx])
lineBuffer = lineBuffer[idx+1:]
}
}
}
}()
// Wait for either context cancellation or read completion
select {
case <-ctx.Done():
// Context cancelled - process will be killed by CommandContext
<-readDone // Wait for reader goroutine to finish
return "", nil, ctx.Err()
case result := <-readDone:
if result.err != nil {
return "", nil, result.err
}
resultUsage = result.usage
}
if err := cmd.Wait(); err != nil {
return "", nil, fmt.Errorf("claude command failed: %w\nstderr: %s", err, stderr.String())
}
fmt.Println(" └─────────────────────────────────────────────────────────────")
fmt.Printf(" 📄 Total: %d chars\n", fullResponse.Len())
// Display usage if available
if resultUsage != nil && !resultUsage.IsEmpty() {
fmt.Printf(" 💰 Cost: $%.4f (in: %d, out: %d, cache: %d)\n",
resultUsage.TotalCostUSD, resultUsage.InputTokens, resultUsage.OutputTokens, resultUsage.CacheReadTokens)
}
return fullResponse.String(), resultUsage, nil
}
func (c *Client) streamingArgs() []string {
args := []string{
"-p",
"--output-format", "stream-json",
"--verbose",
}
// Auto-approve tool uses if configured (WARNING: security risk)
if c.SkipPermissions {
args = append(args, "--dangerously-skip-permissions")
}
// Handle tool permissions
if !c.EnableTools {
// Explicitly disable tools for backward compatibility
args = append(args, "--tools", "")
} else if len(c.AllowedTools) > 0 {
// Restrict to specific tools
args = append(args, "--tools", strings.Join(c.AllowedTools, ","))
}
// If EnableTools is true and AllowedTools is nil, omit --tools flag entirely (allows all tools)
// Add model selection if specified
if c.Model != "" {
args = append(args, "--model", c.Model)
}
if c.Agent != "" {
args = append(args, "--agent", c.Agent)
}
if c.Effort != "" {
args = append(args, "--effort", c.Effort)
}
for _, config := range c.MCPConfigs {
if strings.TrimSpace(config) != "" {
args = append(args, "--mcp-config", config)
}
}
return args
}
// messageNonStreaming sends a message without streaming.
// Note: Non-streaming text output doesn't include usage data.
func (c *Client) messageNonStreaming(ctx context.Context, systemPrompt, userPrompt string) (string, *cost.Usage, error) {
args := []string{
"-p",
"--output-format", "text",
}
// Add model selection if specified
if c.Model != "" {
args = append(args, "--model", c.Model)
}
if c.Agent != "" {
args = append(args, "--agent", c.Agent)
}
if c.Effort != "" {
args = append(args, "--effort", c.Effort)
}
// Note: Prompt caching is automatically handled by Claude CLI when using system prompts
// No explicit flag needed in current version (2.1.39+)
if systemPrompt != "" {
args = append(args, "--system-prompt", systemPrompt)
}
useStdin := len(userPrompt) > 100000
if !useStdin {
args = append(args, userPrompt)
}
cmd := exec.CommandContext(ctx, c.Command, args...)
if c.WorkDir != "" {
cmd.Dir = c.WorkDir
}
// Get parent environment but filter out CLAUDECODE to allow nested Claude sessions
cmd.Env = filterParentEnv()
for k, v := range c.Env {
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
}
if useStdin {
cmd.Stdin = strings.NewReader(userPrompt)
}
if c.Debug {
fmt.Printf("[DEBUG] Running: %s %v\n", c.Command, args[:min(3, len(args))])
fmt.Printf("[DEBUG] WorkDir: %s\n", c.WorkDir)
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", nil, fmt.Errorf("claude command failed: %w\nstderr: %s\nstdout: %s", err, stderr.String(), stdout.String()[:min(500, stdout.Len())])
}
// Non-streaming text output doesn't include usage data
return strings.TrimSpace(stdout.String()), nil, nil
}
// MessageWithFiles sends a message with file context to Claude.
// Note: This uses text output format, so usage data is not available.
func (c *Client) MessageWithFiles(ctx context.Context, systemPrompt, userPrompt string, files []string) (string, *cost.Usage, error) {
args := []string{
"-p",
"--output-format", "text",
}
// Add model selection if specified
if c.Model != "" {
args = append(args, "--model", c.Model)
}
if c.Agent != "" {
args = append(args, "--agent", c.Agent)
}
if c.Effort != "" {
args = append(args, "--effort", c.Effort)
}
// Note: Prompt caching is automatically handled by Claude CLI when using system prompts
// No explicit flag needed in current version (2.1.39+)
if systemPrompt != "" {
args = append(args, "--system-prompt", systemPrompt)
}
for _, f := range files {
args = append(args, "--add-dir", f)
}
useStdin := len(userPrompt) > 100000
if !useStdin {
args = append(args, userPrompt)
}
cmd := exec.CommandContext(ctx, c.Command, args...)
if c.WorkDir != "" {
cmd.Dir = c.WorkDir
}
// Get parent environment but filter out CLAUDECODE to allow nested Claude sessions
cmd.Env = filterParentEnv()
for k, v := range c.Env {
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v))
}
if useStdin {
cmd.Stdin = strings.NewReader(userPrompt)
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return "", nil, fmt.Errorf("claude command failed: %w\nstderr: %s\nstdout: %s", err, stderr.String(), stdout.String()[:min(500, stdout.Len())])
}
// Text output format doesn't include usage data
return strings.TrimSpace(stdout.String()), nil, nil
}
// filterParentEnv returns a filtered copy of the parent environment,
// removing CLAUDECODE variables to allow nested Claude Code sessions.
func filterParentEnv() []string {
filtered := make([]string, 0, len(os.Environ()))
for _, env := range os.Environ() {
// Skip CLAUDECODE and CLAUDE_CODE_ENTRYPOINT to allow running inside another Claude Code session
if !strings.HasPrefix(env, "CLAUDECODE=") && !strings.HasPrefix(env, "CLAUDE_CODE_ENTRYPOINT=") {
filtered = append(filtered, env)
}
}
return filtered
}
func min(a, b int) int {
if a < b {
return a
}
return b
}