client.go

 1// Package copilot provides GitHub Copilot integration.
 2package copilot
 3
 4import (
 5	"bytes"
 6	"fmt"
 7	"io"
 8	"log/slog"
 9	"net/http"
10	"regexp"
11
12	"github.com/charmbracelet/crush/internal/log"
13)
14
15// NewClient creates a new HTTP client with a custom transport that adds the
16// X-Initiator header based on message history in the request body.
17func NewClient(debug bool) *http.Client {
18	return &http.Client{
19		Transport: &initiatorTransport{debug: debug},
20	}
21}
22
23type initiatorTransport struct {
24	debug bool
25}
26
27func (t *initiatorTransport) RoundTrip(req *http.Request) (*http.Response, error) {
28	const (
29		xInitiatorHeader = "X-Initiator"
30		userInitiator    = "user"
31		agentInitiator   = "agent"
32	)
33
34	if req == nil {
35		return nil, fmt.Errorf("HTTP request is nil")
36	}
37	if req.Body == http.NoBody {
38		// No body to inspect; default to user.
39		req.Header.Set(xInitiatorHeader, userInitiator)
40		slog.Debug("Setting X-Initiator header to user (no request body)")
41		return t.roundTrip(req)
42	}
43
44	// Clone request to avoid modifying the original.
45	req = req.Clone(req.Context())
46
47	// Read the original body into bytes so we can examine it.
48	bodyBytes, err := io.ReadAll(req.Body)
49	if err != nil {
50		return nil, fmt.Errorf("failed to read request body: %w", err)
51	}
52	defer req.Body.Close()
53
54	// Restore the original body using the preserved bytes.
55	req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
56
57	// Check for assistant messages using regex to handle whitespace
58	// variations in the JSON while avoiding full unmarshalling overhead.
59	initiator := userInitiator
60	assistantRolePattern := regexp.MustCompile(`"role"\s*:\s*"assistant"`)
61	if assistantRolePattern.Match(bodyBytes) {
62		slog.Debug("Setting X-Initiator header to agent (found assistant messages in history)")
63		initiator = agentInitiator
64	} else {
65		slog.Debug("Setting X-Initiator header to user (no assistant messages)")
66	}
67	req.Header.Set(xInitiatorHeader, initiator)
68
69	return t.roundTrip(req)
70}
71
72func (t *initiatorTransport) roundTrip(req *http.Request) (*http.Response, error) {
73	if t.debug {
74		return log.NewHTTPClient().Transport.RoundTrip(req)
75	}
76	return http.DefaultTransport.RoundTrip(req)
77}