Repository navigation
Expand file tree
/
Copy pathproxy.go
More file actions
427 lines (372 loc) · 11.3 KB
/
Copy pathproxy.go
File metadata and controls
427 lines (372 loc) · 11.3 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
package testharness
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
const proxyShutdownTimeout = 5 * time.Second
// CapiProxy manages a child process that acts as a replaying proxy to AI endpoints.
// It spawns the shared test harness server from test/harness/server.ts.
type CapiProxy struct {
cmd *exec.Cmd
proxyURL string
connectProxyURL string
caFilePath string
mu sync.Mutex
}
// NewCapiProxy creates a new proxy instance.
func NewCapiProxy() *CapiProxy {
return &CapiProxy{}
}
// Start launches the proxy server and returns its URL.
func (p *CapiProxy) Start() (string, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.proxyURL != "" {
return p.proxyURL, nil
}
// The harness server is in the shared test directory. Anchor the path to
// the repo root (not the process cwd), because the in-process (FFI)
// transport os.Chdir's into a per-test temp workdir, which would otherwise
// break the cwd-relative resolution.
serverPath := RepoPath("test", "harness", "server.ts")
p.cmd = exec.Command("npx", "tsx", serverPath)
p.cmd.Dir = RepoPath("test", "harness")
stdout, err := p.cmd.StdoutPipe()
if err != nil {
return "", fmt.Errorf("failed to get stdout pipe: %w", err)
}
// Forward stderr to parent for debugging
p.cmd.Stderr = os.Stderr
if err := p.cmd.Start(); err != nil {
return "", fmt.Errorf("failed to start proxy server: %w", err)
}
// Read until the server prints "Listening: http://..."; npm/npx may emit
// wrapper output first on some platforms.
reader := bufio.NewReader(stdout)
re := regexp.MustCompile(`Listening: (http://[^\s]+)\s+(\{.*\})$`)
var matches []string
var line string
for {
nextLine, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
p.cmd.Process.Kill()
return "", fmt.Errorf("failed to read proxy URL: %w", err)
}
line = strings.TrimSpace(nextLine)
matches = re.FindStringSubmatch(line)
if len(matches) >= 3 {
break
}
if strings.Contains(line, "Listening: ") {
p.cmd.Process.Kill()
return "", fmt.Errorf("proxy startup line missing CONNECT proxy metadata: %s", line)
}
if err == io.EOF {
p.cmd.Process.Kill()
return "", fmt.Errorf("proxy exited before startup; last output: %s", line)
}
}
p.proxyURL = matches[1]
var metadata struct {
ConnectProxyURL string `json:"connectProxyUrl"`
CAFilePath string `json:"caFilePath"`
}
if err := json.Unmarshal([]byte(matches[2]), &metadata); err != nil {
p.cmd.Process.Kill()
return "", fmt.Errorf("failed to parse proxy startup metadata: %w", err)
}
p.connectProxyURL = metadata.ConnectProxyURL
p.caFilePath = metadata.CAFilePath
if p.connectProxyURL == "" || p.caFilePath == "" {
p.cmd.Process.Kill()
return "", fmt.Errorf("proxy startup metadata missing CONNECT proxy details: %s", line)
}
return p.proxyURL, nil
}
// Stop gracefully shuts down the proxy server.
func (p *CapiProxy) Stop() error {
return p.StopWithOptions(false)
}
// StopWithOptions gracefully shuts down the proxy server.
// If skipWritingCache is true, the proxy won't write captured exchanges to disk.
func (p *CapiProxy) StopWithOptions(skipWritingCache bool) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.cmd == nil || p.cmd.Process == nil {
return nil
}
cmd := p.cmd
defer func() {
p.cmd = nil
p.proxyURL = ""
}()
// Send stop request to the server
if p.proxyURL != "" {
stopURL := p.proxyURL + "/stop"
if skipWritingCache {
stopURL += "?skipWritingCache=true"
}
// Best effort - ignore errors
client := http.Client{Timeout: proxyShutdownTimeout}
resp, err := client.Post(stopURL, "application/json", nil)
if err == nil {
resp.Body.Close()
}
}
exited := make(chan struct{}, 1)
go func() {
_ = cmd.Wait()
exited <- struct{}{}
}()
if !waitForProcessExit(exited, proxyShutdownTimeout) {
if err := killProcessTree(cmd); err != nil {
return fmt.Errorf("failed to kill proxy process: %w", err)
}
if !waitForProcessExit(exited, proxyShutdownTimeout) {
return fmt.Errorf("proxy process did not exit after being killed")
}
}
return nil
}
func killProcessTree(cmd *exec.Cmd) error {
if runtime.GOOS == "windows" {
taskkill := exec.Command(
"taskkill",
"/PID",
strconv.Itoa(cmd.Process.Pid),
"/T",
"/F",
)
if err := taskkill.Run(); err == nil {
return nil
}
}
if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
return err
}
return nil
}
func waitForProcessExit(exited <-chan struct{}, timeout time.Duration) bool {
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-exited:
return true
case <-timer.C:
return false
}
}
// Configure sends configuration to the proxy.
func (p *CapiProxy) Configure(filePath, workDir string) error {
p.mu.Lock()
url := p.proxyURL
p.mu.Unlock()
if url == "" {
return fmt.Errorf("proxy not started")
}
config := fmt.Sprintf(`{"filePath":%q,"workDir":%q}`, filePath, workDir)
resp, err := http.Post(url+"/config", "application/json", strings.NewReader(config))
if err != nil {
return fmt.Errorf("failed to configure proxy: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("proxy config failed with status %d", resp.StatusCode)
}
return nil
}
// GetExchanges retrieves the captured HTTP exchanges from the proxy.
func (p *CapiProxy) GetExchanges() ([]ParsedHttpExchange, error) {
p.mu.Lock()
url := p.proxyURL
p.mu.Unlock()
if url == "" {
return nil, fmt.Errorf("proxy not started")
}
resp, err := http.Get(url + "/exchanges")
if err != nil {
return nil, fmt.Errorf("failed to get exchanges: %w", err)
}
defer resp.Body.Close()
var exchanges []ParsedHttpExchange
if err := json.NewDecoder(resp.Body).Decode(&exchanges); err != nil {
return nil, fmt.Errorf("failed to decode exchanges: %w", err)
}
return exchanges, nil
}
// GetRequests retrieves all captured outbound HTTP requests from the proxy.
func (p *CapiProxy) GetRequests() ([]CapturedRequest, error) {
p.mu.Lock()
url := p.proxyURL
p.mu.Unlock()
if url == "" {
return nil, fmt.Errorf("proxy not started")
}
resp, err := http.Get(url + "/requests")
if err != nil {
return nil, fmt.Errorf("failed to get requests: %w", err)
}
defer resp.Body.Close()
var requests []CapturedRequest
if err := json.NewDecoder(resp.Body).Decode(&requests); err != nil {
return nil, fmt.Errorf("failed to decode requests: %w", err)
}
return requests, nil
}
// CapturedRequest represents an outbound HTTP request captured by the proxy.
type CapturedRequest struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]json.RawMessage `json:"headers"`
Body string `json:"body"`
}
// ParsedHttpExchange represents a captured HTTP exchange.
type ParsedHttpExchange struct {
Request ChatCompletionRequest `json:"request"`
Response *ChatCompletionResponse `json:"response,omitempty"`
RequestHeaders map[string]json.RawMessage `json:"requestHeaders,omitempty"`
}
// ChatCompletionRequest represents an OpenAI chat completion request.
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []ChatCompletionMessage `json:"messages"`
Tools []ChatCompletionTool `json:"tools,omitempty"`
}
// ChatCompletionMessage represents a message in the chat completion request.
type ChatCompletionMessage struct {
Role string `json:"role"`
Content string `json:"content,omitempty"`
RawContent json.RawMessage `json:"-"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
}
// UnmarshalJSON handles Content being either a plain string or an array of
// content parts (e.g. multimodal messages with image_url entries).
func (m *ChatCompletionMessage) UnmarshalJSON(data []byte) error {
type Alias ChatCompletionMessage
aux := &struct {
Content json.RawMessage `json:"content,omitempty"`
*Alias
}{
Alias: (*Alias)(m),
}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
m.RawContent = aux.Content
m.Content = ""
if len(aux.Content) > 0 {
var s string
if json.Unmarshal(aux.Content, &s) == nil {
m.Content = s
}
}
return nil
}
// ToolCall represents a tool call in an assistant message.
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function FunctionCall `json:"function"`
}
// FunctionCall represents the function details in a tool call.
type FunctionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
}
// Message is an alias for ChatCompletionMessage for test convenience.
type Message = ChatCompletionMessage
// ChatCompletionTool represents a tool in the chat completion request.
type ChatCompletionTool struct {
Type string `json:"type"`
Function ChatCompletionToolFunction `json:"function"`
}
// ChatCompletionToolFunction represents a function tool.
type ChatCompletionToolFunction struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
}
// ChatCompletionResponse represents an OpenAI chat completion response.
type ChatCompletionResponse struct {
ID string `json:"id"`
Model string `json:"model"`
Choices []ChatCompletionChoice `json:"choices"`
}
// ChatCompletionChoice represents a choice in the response.
type ChatCompletionChoice struct {
Index int `json:"index"`
Message ChatCompletionMessage `json:"message"`
FinishReason string `json:"finish_reason"`
}
// URL returns the proxy URL, or empty if not started.
func (p *CapiProxy) URL() string {
p.mu.Lock()
defer p.mu.Unlock()
return p.proxyURL
}
// ProxyEnv returns environment variables that route HTTPS traffic through the CONNECT proxy.
func (p *CapiProxy) ProxyEnv() []string {
p.mu.Lock()
defer p.mu.Unlock()
if p.connectProxyURL == "" || p.caFilePath == "" {
return nil
}
noProxy := "127.0.0.1,localhost,::1"
return []string{
"HTTP_PROXY=" + p.connectProxyURL,
"HTTPS_PROXY=" + p.connectProxyURL,
"http_proxy=" + p.connectProxyURL,
"https_proxy=" + p.connectProxyURL,
"NO_PROXY=" + noProxy,
"no_proxy=" + noProxy,
"NODE_EXTRA_CA_CERTS=" + p.caFilePath,
"SSL_CERT_FILE=" + p.caFilePath,
"REQUESTS_CA_BUNDLE=" + p.caFilePath,
"CURL_CA_BUNDLE=" + p.caFilePath,
"GIT_SSL_CAINFO=" + p.caFilePath,
"GH_TOKEN=",
"GITHUB_TOKEN=",
"GH_ENTERPRISE_TOKEN=",
"GITHUB_ENTERPRISE_TOKEN=",
}
}
// SetCopilotUserByToken registers a per-token user configuration on the proxy.
func (p *CapiProxy) SetCopilotUserByToken(token string, response map[string]interface{}) error {
p.mu.Lock()
url := p.proxyURL
p.mu.Unlock()
if url == "" {
return fmt.Errorf("proxy not started")
}
body := map[string]interface{}{
"token": token,
"response": response,
}
data, err := json.Marshal(body)
if err != nil {
return err
}
resp, err := http.Post(url+"/copilot-user-config", "application/json", bytes.NewReader(data))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("setCopilotUserByToken: unexpected status %d", resp.StatusCode)
}
return nil
}