-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathlaunch.go
More file actions
468 lines (422 loc) · 14.5 KB
/
launch.go
File metadata and controls
468 lines (422 loc) · 14.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
package commands
import (
"errors"
"fmt"
"net"
"os"
"os/exec"
"sort"
"strings"
"github.com/docker/model-runner/cmd/cli/pkg/types"
"github.com/spf13/cobra"
)
// openaiPathSuffix is the path appended to the base URL for OpenAI-compatible endpoints.
const openaiPathSuffix = "/engines/v1"
// dummyAPIKey is a placeholder API key for Docker Model Runner (which doesn't require auth).
const dummyAPIKey = "sk-docker-model-runner" //nolint:gosec // not a real credential
// engineEndpoints holds the resolved base URLs (without path) for both
// client locations.
type engineEndpoints struct {
// base URL reachable from inside a Docker container
// (e.g., http://model-runner.docker.internal).
container string
// base URL reachable from the host machine
// (e.g., http://127.0.0.1:12434).
host string
}
// containerApp describes an app that runs as a Docker container.
type containerApp struct {
defaultImage string
defaultHostPort int
containerPort int
envFn func(baseURL string) []string
extraDockerArgs []string // additional docker run args (e.g., volume mounts)
}
// containerApps are launched via "docker run --rm".
var containerApps = map[string]containerApp{
"anythingllm": {
defaultImage: "mintplexlabs/anythingllm:latest",
defaultHostPort: 3001,
containerPort: 3001,
envFn: anythingllmEnv,
extraDockerArgs: []string{"-v", "anythingllm_storage:/app/server/storage"},
},
"openwebui": {
defaultImage: "ghcr.io/open-webui/open-webui:latest",
defaultHostPort: 3000,
containerPort: 8080,
envFn: openwebuiEnv},
"llmfit": {
defaultImage: "ghcr.io/alexsjones/llmfit",
envFn: llmfitEnv,
},
}
// hostApp describes a native CLI app launched on the host.
type hostApp struct {
envFn func(baseURL string) []string
configInstructions func(baseURL string) []string // for apps that need manual config
}
// hostApps are launched as native executables on the host.
var hostApps = map[string]hostApp{
"opencode": {envFn: openaiEnv(openaiPathSuffix)},
"codex": {envFn: openaiEnv("/v1")},
"claude": {envFn: anthropicEnv},
"openclaw": {configInstructions: openclawConfigInstructions},
}
// supportedApps is derived from the registries above.
var supportedApps = func() []string {
apps := make([]string, 0, len(containerApps)+len(hostApps))
for name := range containerApps {
apps = append(apps, name)
}
for name := range hostApps {
apps = append(apps, name)
}
sort.Strings(apps)
return apps
}()
// appDescriptions provides human-readable descriptions for supported apps.
var appDescriptions = map[string]string{
"anythingllm": "RAG platform with Docker Model Runner provider",
"claude": "Claude Code AI assistant",
"codex": "Codex CLI",
"openclaw": "Open Claw AI assistant",
"opencode": "Open Code AI code editor",
"openwebui": "Open WebUI for models",
"llmfit": "Recommend models that run on your system",
}
func newLaunchCmd() *cobra.Command {
var (
port int
image string
detach bool
dryRun bool
configOnly bool
model string
)
c := &cobra.Command{
Use: "launch [APP] [-- APP_ARGS...]",
Short: "Launch an app configured to use Docker Model Runner",
Long: fmt.Sprintf(`Launch an app configured to use Docker Model Runner.
Without arguments, lists all supported apps.
Supported apps: %s
Examples:
docker model launch
docker model launch opencode
docker model launch llmfit
docker model launch claude -- --help
docker model launch openwebui --port 3000
docker model launch claude --config
docker model launch llmfit -- recommend -n 5`, strings.Join(supportedApps, ", ")),
ValidArgs: supportedApps,
RunE: func(cmd *cobra.Command, args []string) error {
// No args - list supported apps
if len(args) == 0 {
return listSupportedApps(cmd)
}
app := strings.ToLower(args[0])
// Extract passthrough args using -- separator
var appArgs []string
dashIdx := cmd.ArgsLenAtDash()
if dashIdx == -1 {
// No "--" separator
if len(args) > 1 {
return fmt.Errorf("unexpected arguments: %s\nUse '--' to pass extra arguments to the app", strings.Join(args[1:], " "))
}
} else {
// "--" was used: require exactly 1 arg (the app name) before it
if dashIdx != 1 {
return fmt.Errorf("unexpected arguments before '--': %s\nUsage: docker model launch [APP] [-- APP_ARGS...]", strings.Join(args[1:dashIdx], " "))
}
appArgs = args[dashIdx:]
}
runner, err := getStandaloneRunner(cmd.Context())
if err != nil {
return fmt.Errorf("unable to determine standalone runner endpoint: %w", err)
}
ep, err := resolveBaseEndpoints(runner)
if err != nil {
return err
}
// --config: print configuration without launching
if configOnly {
return printAppConfig(cmd, app, ep, image, port)
}
if ca, ok := containerApps[app]; ok {
return launchContainerApp(cmd, ca, ep.container, image, port, detach, appArgs, dryRun)
}
if cli, ok := hostApps[app]; ok {
return launchHostApp(cmd, app, ep.host, cli, model, runner, appArgs, dryRun)
}
return fmt.Errorf("unsupported app %q (supported: %s)", app, strings.Join(supportedApps, ", "))
},
}
c.Flags().IntVar(&port, "port", 0, "Host port to expose (web UIs)")
c.Flags().StringVar(&image, "image", "", "Override container image for containerized apps")
c.Flags().BoolVar(&detach, "detach", false, "Run containerized app in background")
c.Flags().BoolVar(&dryRun, "dry-run", false, "Print what would be executed without running it")
c.Flags().BoolVar(&configOnly, "config", false, "Print configuration without launching")
c.Flags().StringVar(&model, "model", "", "Model to use (for opencode)")
return c
}
// listSupportedApps prints all supported apps with their descriptions and install status.
func listSupportedApps(cmd *cobra.Command) error {
cmd.Println("Supported apps:")
cmd.Println()
for _, name := range supportedApps {
desc := appDescriptions[name]
if desc == "" {
desc = name
}
status := ""
if _, ok := hostApps[name]; ok {
if _, err := exec.LookPath(name); err != nil {
status = " (not installed)"
}
}
cmd.Printf(" %-15s %s%s\n", name, desc, status)
}
cmd.Println()
cmd.Println("Usage: docker model launch [APP] [-- APP_ARGS...]")
return nil
}
// printAppConfig prints the configuration that would be used for the given app.
func printAppConfig(cmd *cobra.Command, app string, ep engineEndpoints, imageOverride string, portOverride int) error {
if ca, ok := containerApps[app]; ok {
img := imageOverride
if img == "" {
img = ca.defaultImage
}
hostPort := portOverride
if hostPort == 0 {
hostPort = ca.defaultHostPort
}
cmd.Printf("Configuration for %s (container app):\n", app)
cmd.Printf(" Image: %s\n", img)
if ca.containerPort > 0 {
cmd.Printf(" Container port: %d\n", ca.containerPort)
}
if ca.defaultHostPort > 0 {
cmd.Printf(" Host port: %d\n", hostPort)
}
if ca.envFn != nil {
cmd.Printf(" Environment:\n")
for _, e := range ca.envFn(ep.container) {
cmd.Printf(" %s\n", e)
}
}
return nil
}
if cli, ok := hostApps[app]; ok {
cmd.Printf("Configuration for %s (host app):\n", app)
if cli.envFn != nil {
cmd.Printf(" Environment:\n")
for _, e := range cli.envFn(ep.host) {
cmd.Printf(" %s\n", e)
}
}
if cli.configInstructions != nil {
cmd.Printf(" Manual configuration:\n")
for _, line := range cli.configInstructions(ep.host) {
cmd.Printf(" %s\n", line)
}
}
return nil
}
return fmt.Errorf("unsupported app %q (supported: %s)", app, strings.Join(supportedApps, ", "))
}
// resolveBaseEndpoints resolves the base URLs (without path) for both
// container and host client locations.
func resolveBaseEndpoints(runner *standaloneRunner) (engineEndpoints, error) {
const (
localhost = "127.0.0.1"
hostDockerInternal = "host.docker.internal"
)
kind := modelRunner.EngineKind()
switch kind {
case types.ModelRunnerEngineKindDesktop:
return engineEndpoints{
container: "http://model-runner.docker.internal",
host: strings.TrimRight(modelRunner.URL(""), "/"),
}, nil
case types.ModelRunnerEngineKindMobyManual:
ep := strings.TrimRight(modelRunner.URL(""), "/")
containerEP := strings.NewReplacer(
"localhost", hostDockerInternal,
localhost, hostDockerInternal,
).Replace(ep)
return engineEndpoints{container: containerEP, host: ep}, nil
case types.ModelRunnerEngineKindCloud, types.ModelRunnerEngineKindMoby:
if runner == nil {
return engineEndpoints{}, errors.New("unable to determine standalone runner endpoint")
}
if runner.gatewayIP != "" && runner.gatewayPort != 0 {
port := fmt.Sprintf("%d", runner.gatewayPort)
return engineEndpoints{
container: "http://" + net.JoinHostPort(runner.gatewayIP, port),
host: "http://" + net.JoinHostPort(localhost, port),
}, nil
}
if runner.hostPort != 0 {
hostPort := fmt.Sprintf("%d", runner.hostPort)
return engineEndpoints{
container: "http://" + net.JoinHostPort(hostDockerInternal, hostPort),
host: "http://" + net.JoinHostPort(localhost, hostPort),
}, nil
}
return engineEndpoints{}, errors.New("unable to determine standalone runner endpoint")
default:
return engineEndpoints{}, fmt.Errorf("unhandled engine kind: %v", kind)
}
}
// launchContainerApp launches a container-based app via "docker run".
func launchContainerApp(cmd *cobra.Command, ca containerApp, baseURL string, imageOverride string, portOverride int, detach bool, appArgs []string, dryRun bool) error {
img := imageOverride
if img == "" {
img = ca.defaultImage
}
hostPort := portOverride
if hostPort == 0 {
hostPort = ca.defaultHostPort
}
dockerArgs := []string{"run", "--rm"}
if detach {
dockerArgs = append(dockerArgs, "-d")
}
if ca.containerPort > 0 {
dockerArgs = append(dockerArgs,
"-p", fmt.Sprintf("%d:%d", hostPort, ca.containerPort),
)
}
dockerArgs = append(dockerArgs, ca.extraDockerArgs...)
if ca.envFn == nil {
return fmt.Errorf("container app requires envFn to be set")
}
for _, e := range ca.envFn(baseURL) {
dockerArgs = append(dockerArgs, "-e", e)
}
dockerArgs = append(dockerArgs, img)
dockerArgs = append(dockerArgs, appArgs...)
if dryRun {
cmd.Printf("Would run: docker %s\n", strings.Join(dockerArgs, " "))
return nil
}
return runExternal(cmd, nil, "docker", dockerArgs...)
}
// launchHostApp launches a native host app executable.
func launchHostApp(cmd *cobra.Command, bin string, baseURL string, cli hostApp, model string, runner *standaloneRunner, appArgs []string, dryRun bool) error {
// Special handling for opencode: use dedicated launcher
if bin == "opencode" {
return launchOpenCode(cmd, baseURL, model, runner, appArgs, dryRun)
}
if !dryRun {
if _, err := exec.LookPath(bin); err != nil {
cmd.PrintErrf("%q executable not found in PATH.\n", bin)
if cli.envFn != nil {
cmd.PrintErrf("Configure your app to use:\n")
for _, e := range cli.envFn(baseURL) {
cmd.PrintErrf(" %s\n", e)
}
}
return fmt.Errorf("%s not found; please install it and re-run", bin)
}
}
if cli.envFn == nil {
return launchUnconfigurableHostApp(cmd, bin, baseURL, cli, appArgs, dryRun)
}
env := cli.envFn(baseURL)
if dryRun {
cmd.Printf("Would run: %s %s\n", bin, strings.Join(appArgs, " "))
for _, e := range env {
cmd.Printf(" %s\n", e)
}
return nil
}
return runExternal(cmd, withEnv(env...), bin, appArgs...)
}
// launchUnconfigurableHostApp handles host apps that need manual config rather than env vars.
func launchUnconfigurableHostApp(cmd *cobra.Command, bin string, baseURL string, cli hostApp, appArgs []string, dryRun bool) error {
enginesEP := baseURL + openaiPathSuffix
cmd.Printf("Configure %s to use Docker Model Runner:\n", bin)
cmd.Printf(" Base URL: %s\n", enginesEP)
cmd.Printf(" API type: openai-completions\n")
cmd.Printf(" API key: %s\n", dummyAPIKey)
if cli.configInstructions != nil {
cmd.Printf("\nExample:\n")
for _, line := range cli.configInstructions(baseURL) {
cmd.Printf(" %s\n", line)
}
}
if dryRun {
cmd.Printf("Would run: %s %s\n", bin, strings.Join(appArgs, " "))
return nil
}
return runExternal(cmd, nil, bin, appArgs...)
}
// openclawConfigInstructions returns configuration commands for openclaw.
func openclawConfigInstructions(baseURL string) []string {
ep := baseURL + openaiPathSuffix
return []string{
fmt.Sprintf("openclaw config set models.providers.docker-model-runner.baseUrl %q", ep),
"openclaw config set models.providers.docker-model-runner.api openai-completions",
fmt.Sprintf("openclaw config set models.providers.docker-model-runner.apiKey %s", dummyAPIKey),
}
}
// openaiEnv returns an env builder that sets OpenAI-compatible
// environment variables using the given path suffix.
func openaiEnv(suffix string) func(string) []string {
return func(baseURL string) []string {
ep := baseURL + suffix
return []string{
"OPENAI_API_BASE=" + ep,
"OPENAI_BASE_URL=" + ep,
"OPENAI_API_BASE_URL=" + ep,
"OPENAI_API_KEY=" + dummyAPIKey,
"OPEN_AI_KEY=" + dummyAPIKey, // AnythingLLM uses this
}
}
}
// openwebuiEnv returns environment variables for Open WebUI with Docker Model Runner.
func openwebuiEnv(baseURL string) []string {
return append(openaiEnv(openaiPathSuffix)(baseURL), "WEBUI_AUTH=false")
}
// anythingllmEnv returns environment variables for AnythingLLM with Docker Model Runner provider.
func anythingllmEnv(baseURL string) []string {
return []string{
"STORAGE_DIR=/app/server/storage",
"LLM_PROVIDER=docker-model-runner",
"DOCKER_MODEL_RUNNER_BASE_PATH=" + baseURL,
}
}
// anthropicEnv returns Anthropic-compatible environment variables.
func anthropicEnv(baseURL string) []string {
return []string{
"ANTHROPIC_BASE_URL=" + baseURL + "/anthropic",
"ANTHROPIC_API_KEY=" + dummyAPIKey,
}
}
func llmfitEnv(baseURL string) []string {
return []string{
"DOCKER_MODEL_RUNNER_HOST=" + baseURL,
}
}
// withEnv returns the current process environment extended with extra vars.
func withEnv(extra ...string) []string {
return append(os.Environ(), extra...)
}
// runExternal executes a program inheriting stdio.
// Security: prog and progArgs are either hardcoded values or user-provided
// arguments that the user explicitly intends to pass to the launched app.
func runExternal(cmd *cobra.Command, env []string, prog string, progArgs ...string) error {
c := exec.Command(prog, progArgs...)
c.Stdout = cmd.OutOrStdout()
c.Stderr = cmd.ErrOrStderr()
c.Stdin = os.Stdin
if env != nil {
c.Env = env
}
if err := c.Run(); err != nil {
return fmt.Errorf("failed to run %s %s: %w", prog, strings.Join(progArgs, " "), err)
}
return nil
}