-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
455 lines (392 loc) · 11 KB
/
Copy pathmain.go
File metadata and controls
455 lines (392 loc) · 11 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
package main
import (
"errors"
"fmt"
"os"
"strings"
"syscall"
"github.com/spf13/cobra"
"golang.org/x/term"
_ "embed"
)
//go:embed assets/skills/opub/SKILL.md
var opubSkill string
//go:embed assets/copilot-plugin/plugin.json
var copilotPluginJSON string
//go:embed assets/copilot-plugin/.mcp.json
var copilotPluginMCPJSON string
//go:embed assets/copilot-plugin/skills/opub-funded-work/SKILL.md
var copilotPluginSkill string
const version = "0.1.0"
func main() {
root := rootCommand()
if err := root.Execute(); err != nil {
os.Exit(1)
}
}
func rootCommand() *cobra.Command {
root := &cobra.Command{
Use: "opub",
Short: "Use donated opub compute from local tools",
Version: version,
}
root.AddCommand(
setupCmd(),
runCmd(),
doctorCmd(),
mcpCmd(),
pathsCmd(),
)
return root
}
// setup
func setupCmd() *cobra.Command {
var (
project string
projectID string
computeKeyID string
provider string
apiKeyHash string
insecureStorage bool
providerKeyStdin bool
)
cmd := &cobra.Command{
Use: "setup <agent>",
Short: "Configure opub for an agent in the current repository",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceUsage = true
t, err := parseTarget(args[0])
if err != nil {
return err
}
if err := validateProjectName(project); err != nil {
return err
}
if computeKeyID == "" {
return errors.New("pass --compute-key-id from the browser setup output")
}
paths, err := discoverRepoPaths(t.name())
if err != nil {
return err
}
if err := verifyProjectMatchesOrigin(paths, project); err != nil {
return err
}
mode := StorageModeSystem
if insecureStorage {
mode = StorageModeInsecure
}
var projectIDPtr *string
if projectID != "" {
projectIDPtr = &projectID
}
var apiKeyHashPtr *string
if apiKeyHash != "" {
apiKeyHashPtr = &apiKeyHash
}
cfg := &LocalConfig{
Version: 1,
Project: ProjectConfig{FullName: project, ID: projectIDPtr},
ComputeKey: ComputeKeyConfig{ID: computeKeyID},
Provider: ProviderConfig{
Name: provider,
KeyHash: apiKeyHashPtr,
CredentialStorage: storageModeLabel(mode),
},
Target: TargetConfig{Name: t.name()},
}
secret, err := readProviderKey(providerKeyStdin)
if err != nil {
return err
}
ref := t.credentialRef(cfg)
store := CredentialStore{mode: mode}
if err := store.Set(ref, secret); err != nil {
return err
}
if err := writeConfig(paths, cfg); err != nil {
return err
}
fmt.Printf("Configured opub for %s\n", cfg.Project.FullName)
fmt.Printf("Compute key: %s\n", cfg.ComputeKey.ID)
fmt.Printf("Agent: %s\n", t.name())
fmt.Printf("Credentials: %s\n", store.LocationLabel())
fmt.Printf("Config: %s\n", paths.Config)
fmt.Printf("State: %s\n", paths.StateDir)
fmt.Printf("Daily use: opub run %s\n", t.name())
return nil
},
}
cmd.Flags().StringVar(&project, "project", "", "GitHub project in owner/repo format (required)")
cmd.Flags().StringVar(&projectID, "project-id", "", "opub project ID")
cmd.Flags().StringVar(&computeKeyID, "compute-key-id", "", "Compute key ID from the browser setup output (required)")
cmd.Flags().StringVar(&provider, "provider", "openrouter", "Provider name")
cmd.Flags().StringVar(&apiKeyHash, "api-key-hash", "", "Optional provider API key hash diagnostic metadata")
cmd.Flags().BoolVar(&insecureStorage, "insecure-storage", false, "Store credentials in a plain file instead of the system keyring")
cmd.Flags().BoolVar(&providerKeyStdin, "provider-key-stdin", false, "Read provider key from stdin")
cmd.Flags().MarkHidden("provider-key-stdin")
cmd.MarkFlagRequired("project")
cmd.MarkFlagRequired("compute-key-id")
return cmd
}
// run
func runCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "run <agent> [args...]",
Short: "Launch an agent with opub compute credentials",
Args: cobra.MinimumNArgs(1),
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
// With DisableFlagParsing, cobra doesn't intercept -h/--help
if len(args) == 0 || args[0] == "-h" || args[0] == "--help" {
return cmd.Help()
}
// args[0] is the agent, rest are forwarded
t, err := parseTarget(args[0])
if err != nil {
return err
}
forwardArgs := stripRunDelimiter(args[1:])
paths, err := discoverRepoPaths(t.name())
if err != nil {
return err
}
cfg, err := readConfig(paths)
if err != nil {
return err
}
if cfg.Target.Name != t.name() {
return fmt.Errorf("configured target is %q, but requested %q", cfg.Target.Name, t.name())
}
execPath := findExecutable(t.executable())
if execPath == "" {
return fmt.Errorf("target executable %q was not found on PATH", t.executable())
}
mode, err := storageModeFromString(cfg.Provider.CredentialStorage)
if err != nil {
return err
}
store := CredentialStore{mode: mode}
secret, err := store.Get(t.credentialRef(cfg))
if err != nil {
return err
}
session, err := writeSession(paths, cfg)
if err != nil {
return err
}
assets := embeddedLaunchAssets()
if err := t.refresh(forwardArgs, paths, assets); err != nil {
fmt.Fprintf(os.Stderr, "warning: could not refresh %s launch assets: %v\n", t.name(), err)
}
execCmd := t.buildCommand(forwardArgs, paths, assets)
envPairs := t.env(cfg, session, secret, paths)
// Build final env: inherit current env, then apply overrides
environ := os.Environ()
environ = applyEnvPairs(environ, envPairs)
return execProcess(execPath, execCmd.Args, environ)
},
}
return cmd
}
func embeddedLaunchAssets() launchAssets {
return launchAssets{
opubSkill: opubSkill,
copilotPlugin: copilotPluginJSON,
copilotPluginMCP: copilotPluginMCPJSON,
copilotSkill: copilotPluginSkill,
}
}
func stripRunDelimiter(args []string) []string {
if len(args) > 0 && args[0] == "--" {
return args[1:]
}
return args
}
func applyEnvPairs(environ []string, pairs []string) []string {
overrides := make(map[string]string, len(pairs))
for _, p := range pairs {
k, v, _ := strings.Cut(p, "=")
overrides[k] = v
}
var result []string
for _, e := range environ {
k, _, _ := strings.Cut(e, "=")
if _, override := overrides[k]; !override {
result = append(result, e)
}
}
for _, p := range pairs {
result = append(result, p)
}
return result
}
func execProcess(path string, args []string, env []string) error {
return syscall.Exec(path, args, env)
}
func stripFrontmatter(s string) string {
if !strings.HasPrefix(s, "---") {
return s
}
rest := s[3:]
idx := strings.Index(rest, "\n---")
if idx < 0 {
return s
}
return strings.TrimLeft(rest[idx+4:], "\n")
}
// doctor
func doctorCmd() *cobra.Command {
return &cobra.Command{
Use: "doctor <agent>",
Short: "Check opub configuration and credentials for an agent",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
t, err := parseTarget(args[0])
if err != nil {
return err
}
paths, err := discoverRepoPaths(t.name())
if err != nil {
return err
}
fmt.Printf("repo root: %s\n", paths.Root)
fmt.Printf("state dir: %s\n", paths.StateDir)
fmt.Printf("config: %s\n", paths.Config)
fmt.Printf("session: %s\n", paths.Session)
cfg, err := readConfig(paths)
if err != nil {
return err
}
if cfg.Target.Name != t.name() {
return fmt.Errorf("configured target is %q, but requested %q", cfg.Target.Name, t.name())
}
fmt.Printf("project: %s\n", cfg.Project.FullName)
fmt.Printf("compute key: %s\n", cfg.ComputeKey.ID)
fmt.Printf("provider: %s\n", cfg.Provider.Name)
mode, err := storageModeFromString(cfg.Provider.CredentialStorage)
if err != nil {
return err
}
store := CredentialStore{mode: mode}
fmt.Printf("credential storage: %s\n", store.LocationLabel())
ref := t.credentialRef(cfg)
exists, err := store.Exists(ref)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("credential is missing for target %q", t.name())
}
fmt.Println("credential: present")
execPath := findExecutable(t.executable())
if execPath == "" {
return fmt.Errorf("target executable %q was not found on PATH", t.executable())
}
fmt.Printf("agent executable: %s\n", execPath)
fmt.Printf("session state: %s\n", sessionStatus(paths))
fmt.Printf("skill: %s\n", skillStatus(t))
fmt.Printf("mcp: %s\n", mcpStatus(t))
fmt.Println("status: ok")
return nil
},
}
}
// mcp
func mcpCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "mcp",
Short: "MCP server commands",
}
cmd.AddCommand(mcpStdioCmd())
return cmd
}
func mcpStdioCmd() *cobra.Command {
var (
repoRoot string
target string
)
cmd := &cobra.Command{
Use: "stdio",
Short: "Run the opub MCP server on stdin/stdout",
RunE: func(cmd *cobra.Command, args []string) error {
state, err := loadSecretlessState(repoRoot, target)
if err != nil {
return err
}
return runMCPStdio(state, os.Stdin, os.Stdout)
},
}
cmd.Flags().StringVar(&repoRoot, "repo-root", "", "Repository root path")
cmd.Flags().StringVar(&target, "target", "", "Agent name")
cmd.MarkFlagRequired("target")
return cmd
}
// paths
func pathsCmd() *cobra.Command {
return &cobra.Command{
Use: "paths",
Short: "Show opub state and config paths for the current repository",
RunE: func(cmd *cobra.Command, args []string) error {
paths, err := discoverRepoPathsConfigured("")
if err != nil {
return err
}
stateRoot, err := userStateRoot()
if err != nil {
return err
}
fmt.Printf("repo root: %s\n", paths.Root)
fmt.Printf("state root: %s\n", stateRoot)
fmt.Printf("state dir: %s\n", paths.StateDir)
fmt.Printf("config: %s\n", paths.Config)
fmt.Printf("session: %s\n", paths.Session)
if cfg, err := readConfig(paths); err == nil {
t, err := parseTarget(cfg.Target.Name)
if err == nil {
ref := t.credentialRef(cfg)
mode, err := storageModeFromString(cfg.Provider.CredentialStorage)
if err == nil {
store := CredentialStore{mode: mode}
fmt.Printf("credential storage: %s\n", store.LocationLabel())
fmt.Printf("credential service: %s\n", ref.Service)
fmt.Printf("credential account: %s\n", ref.Account)
}
}
}
return nil
},
}
}
// helpers
func readProviderKey(fromStdin bool) (string, error) {
var secret string
var err error
if fromStdin {
var buf strings.Builder
b := make([]byte, 4096)
for {
n, readErr := os.Stdin.Read(b)
buf.Write(b[:n])
if readErr != nil {
break
}
}
secret = buf.String()
} else {
fmt.Fprint(os.Stderr, "One-time provider key: ")
var raw []byte
raw, err = term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", fmt.Errorf("read one-time provider key: %w", err)
}
fmt.Fprintln(os.Stderr)
secret = string(raw)
}
secret = strings.TrimSpace(secret)
if secret == "" {
return "", errors.New("one-time provider key cannot be empty")
}
return secret, nil
}