-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathserver.go
More file actions
310 lines (286 loc) · 10.6 KB
/
server.go
File metadata and controls
310 lines (286 loc) · 10.6 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
package server
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"sort"
"strings"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/xerrors"
"github.com/coder/agentapi/lib/httpapi"
"github.com/coder/agentapi/lib/logctx"
"github.com/coder/agentapi/lib/msgfmt"
st "github.com/coder/agentapi/lib/screentracker"
"github.com/coder/agentapi/lib/termexec"
)
type AgentType = msgfmt.AgentType
const (
AgentTypeClaude AgentType = msgfmt.AgentTypeClaude
AgentTypeGoose AgentType = msgfmt.AgentTypeGoose
AgentTypeAider AgentType = msgfmt.AgentTypeAider
AgentTypeCodex AgentType = msgfmt.AgentTypeCodex
AgentTypeGemini AgentType = msgfmt.AgentTypeGemini
AgentTypeCopilot AgentType = msgfmt.AgentTypeCopilot
AgentTypeAmp AgentType = msgfmt.AgentTypeAmp
AgentTypeCursor AgentType = msgfmt.AgentTypeCursor
AgentTypeAuggie AgentType = msgfmt.AgentTypeAuggie
AgentTypeAmazonQ AgentType = msgfmt.AgentTypeAmazonQ
AgentTypeOpencode AgentType = msgfmt.AgentTypeOpencode
AgentTypeCustom AgentType = msgfmt.AgentTypeCustom
)
// agentTypeAliases contains the mapping of possible input agent type strings to their canonical AgentType values
var agentTypeAliases = map[string]AgentType{
"claude": AgentTypeClaude,
"goose": AgentTypeGoose,
"aider": AgentTypeAider,
"codex": AgentTypeCodex,
"gemini": AgentTypeGemini,
"copilot": AgentTypeCopilot,
"amp": AgentTypeAmp,
"auggie": AgentTypeAuggie,
"cursor": AgentTypeCursor,
"cursor-agent": AgentTypeCursor,
"q": AgentTypeAmazonQ,
"amazonq": AgentTypeAmazonQ,
"opencode": AgentTypeOpencode,
"custom": AgentTypeCustom,
}
func parseAgentType(firstArg string, agentTypeVar string) (AgentType, error) {
// if the agent type is provided, use it
if castedAgentType, ok := agentTypeAliases[agentTypeVar]; ok {
return castedAgentType, nil
}
if agentTypeVar != "" {
return AgentTypeCustom, fmt.Errorf("invalid agent type: %s", agentTypeVar)
}
// if the agent type is not provided, guess it from the first argument
if castedFirstArg, ok := agentTypeAliases[firstArg]; ok {
return castedFirstArg, nil
}
return AgentTypeCustom, nil
}
func runServer(ctx context.Context, logger *slog.Logger, argsToPass []string) error {
agent := argsToPass[0]
agentTypeValue := viper.GetString(FlagType)
agentType, err := parseAgentType(agent, agentTypeValue)
if err != nil {
return xerrors.Errorf("failed to parse agent type: %w", err)
}
termWidth := viper.GetUint16(FlagTermWidth)
termHeight := viper.GetUint16(FlagTermHeight)
if termWidth < 10 {
return xerrors.Errorf("term width must be at least 10")
}
if termHeight < 10 {
return xerrors.Errorf("term height must be at least 10")
}
// Read stdin if it's piped, to be used as initial prompt
initialPrompt := viper.GetString(FlagInitialPrompt)
if initialPrompt == "" {
if !isatty.IsTerminal(os.Stdin.Fd()) {
if stdinData, err := io.ReadAll(os.Stdin); err != nil {
return xerrors.Errorf("failed to read stdin: %w", err)
} else if len(stdinData) > 0 {
initialPrompt = string(stdinData)
logger.Info("Read initial prompt from stdin", "bytes", len(stdinData))
}
}
}
printOpenAPI := viper.GetBool(FlagPrintOpenAPI)
experimentalACP := viper.GetBool(FlagExperimentalACP)
if printOpenAPI && experimentalACP {
return xerrors.Errorf("flags --%s and --%s are mutually exclusive", FlagPrintOpenAPI, FlagExperimentalACP)
}
var agentIO st.AgentIO
var transport = "pty"
var process *termexec.Process
var acpResult *httpapi.SetupACPResult
if printOpenAPI {
agentIO = nil
} else if experimentalACP {
var err error
acpResult, err = httpapi.SetupACP(ctx, httpapi.SetupACPConfig{
Program: agent,
ProgramArgs: argsToPass[1:],
})
if err != nil {
return xerrors.Errorf("failed to setup ACP: %w", err)
}
acpIO := acpResult.AgentIO
agentIO = acpIO
transport = "acp"
} else {
proc, err := httpapi.SetupProcess(ctx, httpapi.SetupProcessConfig{
Program: agent,
ProgramArgs: argsToPass[1:],
TerminalWidth: termWidth,
TerminalHeight: termHeight,
AgentType: agentType,
})
if err != nil {
return xerrors.Errorf("failed to setup process: %w", err)
}
process = proc
agentIO = proc
}
port := viper.GetInt(FlagPort)
srv, err := httpapi.NewServer(ctx, httpapi.ServerConfig{
AgentType: agentType,
AgentIO: agentIO,
Transport: transport,
Port: port,
ChatBasePath: viper.GetString(FlagChatBasePath),
AllowedHosts: viper.GetStringSlice(FlagAllowedHosts),
AllowedOrigins: viper.GetStringSlice(FlagAllowedOrigins),
InitialPrompt: initialPrompt,
})
if err != nil {
return xerrors.Errorf("failed to create server: %w", err)
}
if printOpenAPI {
fmt.Println(srv.GetOpenAPI())
return nil
}
logger.Info("Starting server on port", "port", port)
processExitCh := make(chan error, 1)
// Wait for process exit in PTY mode
if process != nil {
go func() {
defer close(processExitCh)
if err := process.Wait(); err != nil {
if errors.Is(err, termexec.ErrNonZeroExitCode) {
processExitCh <- xerrors.Errorf("========\n%s\n========\n: %w", strings.TrimSpace(process.ReadScreen()), err)
} else {
processExitCh <- xerrors.Errorf("failed to wait for process: %w", err)
}
}
if err := srv.Stop(ctx); err != nil {
logger.Error("Failed to stop server", "error", err)
}
}()
}
// Wait for process exit in ACP mode
if acpResult != nil {
go func() {
defer close(processExitCh)
defer close(acpResult.Done) // Signal cleanup goroutine to exit
if err := acpResult.Wait(); err != nil {
processExitCh <- xerrors.Errorf("ACP process exited: %w", err)
}
if err := srv.Stop(ctx); err != nil {
logger.Error("Failed to stop server", "error", err)
}
}()
}
if err := srv.Start(); err != nil && err != context.Canceled && err != http.ErrServerClosed {
return xerrors.Errorf("failed to start server: %w", err)
}
select {
case err := <-processExitCh:
return xerrors.Errorf("agent exited with error: %w", err)
default:
}
return nil
}
var agentNames = (func() []string {
names := make([]string, 0, len(agentTypeAliases))
for agentType := range agentTypeAliases {
names = append(names, agentType)
}
sort.Strings(names)
return names
})()
type flagSpec struct {
name string
shorthand string
defaultValue any
usage string
flagType string
}
const (
FlagType = "type"
FlagPort = "port"
FlagPrintOpenAPI = "print-openapi"
FlagChatBasePath = "chat-base-path"
FlagTermWidth = "term-width"
FlagTermHeight = "term-height"
FlagAllowedHosts = "allowed-hosts"
FlagAllowedOrigins = "allowed-origins"
FlagExit = "exit"
FlagInitialPrompt = "initial-prompt"
FlagExperimentalACP = "experimental-acp"
)
func CreateServerCmd() *cobra.Command {
serverCmd := &cobra.Command{
Use: "server [agent]",
Short: "Run the server",
Long: fmt.Sprintf("Run the server with the specified agent (one of: %s)", strings.Join(agentNames, ", ")),
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// The --exit flag is used for testing validation of flags in the test suite
if viper.GetBool(FlagExit) {
return
}
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
if viper.GetBool(FlagPrintOpenAPI) {
// We don't want log output here.
logger = slog.New(logctx.DiscardHandler)
}
ctx := logctx.WithLogger(context.Background(), logger)
if err := runServer(ctx, logger, cmd.Flags().Args()); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
},
}
flagSpecs := []flagSpec{
{FlagType, "t", "", fmt.Sprintf("Override the agent type (one of: %s, custom)", strings.Join(agentNames, ", ")), "string"},
{FlagPort, "p", 3284, "Port to run the server on", "int"},
{FlagPrintOpenAPI, "P", false, "Print the OpenAPI schema to stdout and exit", "bool"},
{FlagChatBasePath, "c", "/chat", "Base path for assets and routes used in the static files of the chat interface", "string"},
{FlagTermWidth, "W", uint16(80), "Width of the emulated terminal", "uint16"},
{FlagTermHeight, "H", uint16(1000), "Height of the emulated terminal", "uint16"},
// localhost is the default host for the server. Port is ignored during matching.
{FlagAllowedHosts, "a", []string{"localhost", "127.0.0.1", "[::1]"}, "HTTP allowed hosts (hostnames only, no ports). Use '*' for all, comma-separated list via flag, space-separated list via AGENTAPI_ALLOWED_HOSTS env var", "stringSlice"},
// localhost:3284 is the default origin when you open the chat interface in your browser. localhost:3000 and 3001 are used during development.
{FlagAllowedOrigins, "o", []string{"http://localhost:3284", "http://localhost:3000", "http://localhost:3001"}, "HTTP allowed origins. Use '*' for all, comma-separated list via flag, space-separated list via AGENTAPI_ALLOWED_ORIGINS env var", "stringSlice"},
{FlagInitialPrompt, "I", "", "Initial prompt for the agent. Recommended only if the agent doesn't support initial prompt in interaction mode. Will be read from stdin if piped (e.g., echo 'prompt' | agentapi server -- my-agent)", "string"},
{FlagExperimentalACP, "", false, "Use experimental ACP transport instead of PTY", "bool"},
}
for _, spec := range flagSpecs {
switch spec.flagType {
case "string":
serverCmd.Flags().StringP(spec.name, spec.shorthand, spec.defaultValue.(string), spec.usage)
case "int":
serverCmd.Flags().IntP(spec.name, spec.shorthand, spec.defaultValue.(int), spec.usage)
case "bool":
serverCmd.Flags().BoolP(spec.name, spec.shorthand, spec.defaultValue.(bool), spec.usage)
case "uint16":
serverCmd.Flags().Uint16P(spec.name, spec.shorthand, spec.defaultValue.(uint16), spec.usage)
case "stringSlice":
serverCmd.Flags().StringSliceP(spec.name, spec.shorthand, spec.defaultValue.([]string), spec.usage)
default:
panic(fmt.Sprintf("unknown flag type: %s", spec.flagType))
}
if err := viper.BindPFlag(spec.name, serverCmd.Flags().Lookup(spec.name)); err != nil {
panic(fmt.Sprintf("failed to bind flag %s: %v", spec.name, err))
}
}
serverCmd.Flags().Bool(FlagExit, false, "Exit immediately after parsing arguments")
if err := serverCmd.Flags().MarkHidden(FlagExit); err != nil {
panic(fmt.Sprintf("failed to mark flag %s as hidden: %v", FlagExit, err))
}
if err := viper.BindPFlag(FlagExit, serverCmd.Flags().Lookup(FlagExit)); err != nil {
panic(fmt.Sprintf("failed to bind flag %s: %v", FlagExit, err))
}
viper.SetEnvPrefix("AGENTAPI")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
return serverCmd
}