Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
2984 lines (2823 loc) · 113 KB
/
Copy pathmain.go
File metadata and controls
2984 lines (2823 loc) · 113 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
agents "github.com/lsegal/glorp/agents"
"github.com/lsegal/glorp/browser"
"github.com/lsegal/glorp/core"
"github.com/lsegal/glorp/ngrok"
"github.com/lsegal/glorp/process"
"github.com/lsegal/glorp/webui"
"github.com/mattn/go-isatty"
)
var version = "dev"
var errProjectIssueNotFound = errors.New("project issue not found")
// watchFlagSet builds the `glorp watch` flag set. It is also used, without
// being parsed, to print the command's defaults in `glorp help watch`.
func watchFlagSet(agentSpecs *agentFlag, agentBinaries *agentBinaryFlag, filter *filterFlag) *flag.FlagSet {
flags := flag.NewFlagSet("watch", flag.ExitOnError)
flags.Duration("interval", 30*time.Second, "time between GitHub issue polls")
flags.String("pollmode", "browser", "delivery mode: browser, webhook, or poll")
flags.Bool("poll", false, "deprecated alias for -pollmode=poll")
flags.String("listen", ":0", "address for the GitHub webhook server")
flags.String("webhook-path", "/webhook", "path for GitHub webhook deliveries")
flags.String("webhook-secret", "", "optional GitHub webhook secret")
flags.String("ngrok-binary", ngrok.DefaultBinary, "ngrok executable; fetched through npx when not installed")
flags.String("ngrok-api", "http://127.0.0.1:4040", "deprecated and ignored: the tunnel URL is read from ngrok's own log")
flags.Bool("no-tui", false, "disable the interactive terminal UI")
flags.Bool("no-webui", false, "disable the browser dashboard")
flags.Int("web-ui-port", webui.DefaultPort, "starting port for the browser UI")
flags.String("bind", webui.DefaultBind, "address the browser UI listens on; 0.0.0.0 makes it reachable from other machines")
flags.Bool("yolo", false, "disable agent sandboxes and permission checks")
flags.Int("concurrency", 0, "maximum concurrent agents (0 means 3)")
flags.Var(agentSpecs, "agent", "agent to run as agent/model:level, such as codex, claude/opus, or codex/gpt-5.6:high (repeatable to load balance evenly across concurrency)")
flags.String("ready-state", "", "project status that marks an issue ready for an agent")
flags.Var(agentBinaries, "agent-binary", "executable to invoke one agent through, as NAME=PATH (repeatable); overrides the binary its definition names")
flags.String("codex-binary", "codex", "Codex executable (alias for --agent-binary codex=PATH)")
flags.String("claude-binary", "claude", "Claude executable (alias for --agent-binary claude=PATH)")
flags.Bool("remote-control", false, "ask Claude runs to start Remote Control so they are viewable from the Claude mobile app and claude.ai/code (nothing honours the request under -p yet and no alternative lever exists, so this is off by default and currently reaches nobody)")
flags.Bool("no-merge", false, "leave completed gh-fix pull requests ready for a human to merge")
flags.Bool("no-changelog", false, "skip changelog entries in gh-fix pull requests")
flags.Duration("unblock-interval", defaultUnblockInterval, "how often the stuck-job watchdog checks for paused jobs and jobs with no new output, and runs one agent call to unblock them (0 turns it off)")
flags.String("unblock-agent", "", "agent the stuck-job watchdog's unblock call runs, as agent/model:level (default: the coding agent)")
flags.String("unblock-model", "", "model the stuck-job watchdog's unblock call runs (default: the unblock agent's model)")
flags.String("prompt-agent", "", "agent the dashboards' prompt area runs requests with, as agent/model:level (default: the coding agent)")
flags.String("prompt-model", "", "model the dashboards' prompt area runs requests with (default: the prompt agent's model)")
flags.Duration("update-interval", defaultUpdateInterval, "how often to check for a newer glorp release; an update is offered in the dashboards and applied automatically (0 turns it off)")
flags.Bool("auto-update", true, "apply an available glorp update and restart even while agents are busy, checkpointing their work first; false waits until no agents are active")
flags.Var(&tempDirFlag{}, "temp-dir", "directory new clones are placed in (repeatable, tried in order; the next one is used when one lacks space for a clone; default: the system temp directory)")
flags.String("state", ".glorp.json", "file used to remember handled issue numbers")
flags.String("schedules", "", "file the scheduled prompts are kept in, shared with \"glorp schedule\" (default: .schedules.json beside --state, such as .glorp.schedules.json)")
flags.String("config", agents.DefaultConfigPath, "agent definitions and default values for these switches; separate from --state, and rewritten only when the dashboard saves a setting")
flags.Var(filter, "filter", "GitHub issue search filter (repeatable); the default matches open issues assigned to you")
flags.Bool("all-issues", false, "disable the default issue filter")
flags.String("allowed-commenters", "", "comma-separated GitHub logins allowed to trigger a run with a direct @/glorp:ID mention or a mention of the authenticated gh user (default: the authenticated gh user)")
flags.Bool("browser", false, "deprecated alias for -pollmode=browser")
flags.String("browser-profile", "", "Chrome profile directory for browser mode (default: <config dir>/glorp/browser-data)")
flags.String("browser-binary", "", "Chrome/Chromium/Edge executable for browser mode")
flags.Bool("browser-vision", false, "in browser mode, let an agent read a screenshot of a page whose markup glorp no longer recognises (off by default, hard budget per run)")
flags.Bool("no-headless", false, "in browser mode, drive a visible browser window instead of a headless one, to watch what glorp reads while debugging")
return flags
}
// commandFlags returns the flag set backing a subcommand so help can print its
// defaults, or nil for commands that take no flags.
func commandFlags(name string) *flag.FlagSet {
switch name {
case "watch":
return watchFlagSet(&agentFlag{values: []agentSpec{{Name: "codex"}}}, &agentBinaryFlag{}, &filterFlag{values: []string{defaultIssueFilter}})
case "ui":
return uiFlagSet()
case "auth":
return authFlagSet()
case "browser":
return browserFlagSet()
case "agents":
return agentsFlagSet(&agentsOptions{})
case "clones":
return clonesFlagSet(&tempDirFlag{})
case "schedule":
return scheduleFlagSet()
case "upgrade-skills":
return upgradeSkillsFlagSet(&upgradeSkillsOptions{})
}
return nil
}
func runWatch(args []string) (code int) {
// Agent definitions are loaded before the flags are parsed, because
// --agent is validated against them as it is read and the flag package
// hands values over in the order they were written.
configPath := configPathFromArgs(args, agents.DefaultConfigPath)
registry, err := agents.Load(configPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
setAgentRegistry(registry)
agentSpecs := agentFlag{values: []agentSpec{{Name: "codex"}}}
agentBinaries := agentBinaryFlag{}
filter := filterFlag{values: []string{defaultIssueFilter}}
flags := watchFlagSet(&agentSpecs, &agentBinaries, &filter)
flags.Usage = func() {
cmd, _ := lookupCommand("watch")
fmt.Fprintln(os.Stderr, cmd.usage)
flags.PrintDefaults()
}
if err := flags.Parse(args); err != nil {
return 2
}
// The config file's "settings" section fills in every switch the command
// line left alone (issue #614), so a run's usual configuration lives in
// the file rather than in a shell alias. It is applied after Parse so an
// explicit switch always wins over the file.
configSettings, err := loadConfigSettings(configPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
if err := applyConfigSettings(flags, configPath, configSettings); err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
interval := flagValue[time.Duration](flags, "interval")
poll := flagValue[bool](flags, "poll")
listen := flagValue[string](flags, "listen")
webhookPath := flagValue[string](flags, "webhook-path")
webhookSecret := flagValue[string](flags, "webhook-secret")
ngrokBinary := flagValue[string](flags, "ngrok-binary")
noTui := flagValue[bool](flags, "no-tui")
noWebUI := flagValue[bool](flags, "no-webui")
webUIPort := flagValue[int](flags, "web-ui-port")
bind := strings.TrimSpace(flagValue[string](flags, "bind"))
yolo := flagValue[bool](flags, "yolo")
concurrency := flagValue[int](flags, "concurrency")
readyState := flagValue[string](flags, "ready-state")
codexBinary := flagValue[string](flags, "codex-binary")
claudeBinary := flagValue[string](flags, "claude-binary")
remoteControl := flagValue[bool](flags, "remote-control")
noMerge := flagValue[bool](flags, "no-merge")
noChangelog := flagValue[bool](flags, "no-changelog")
autoUpdate := flagValue[bool](flags, "auto-update")
tempDirs := flagValue[[]string](flags, "temp-dir")
unblockInterval := flagValue[time.Duration](flags, "unblock-interval")
if err := validateUnblockInterval(unblockInterval); err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
unblock := unblockConfig{Agent: strings.TrimSpace(flagValue[string](flags, "unblock-agent")), Model: strings.TrimSpace(flagValue[string](flags, "unblock-model"))}
prompt := unblockConfig{Agent: strings.TrimSpace(flagValue[string](flags, "prompt-agent")), Model: strings.TrimSpace(flagValue[string](flags, "prompt-model"))}
if err := validateUnblockAgent(registry, prompt); err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
if err := validateUnblockAgent(registry, unblock); err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
updateInterval := flagValue[time.Duration](flags, "update-interval")
if err := validateUpdateInterval(updateInterval); err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
statePath := flagValue[string](flags, "state")
if err := guardWorkStateFile(statePath); err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
allIssues := flagValue[bool](flags, "all-issues")
allowedCommenters := splitAllowedCommenters(flagValue[string](flags, "allowed-commenters"))
browserOptions, interval, poll, err := resolveBrowserWatch(flags, interval, poll)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
targets := flags.Args()
if len(targets) == 0 {
if repo, ok := originRemoteTarget(); ok {
targets = []string{repo}
}
}
if len(targets) == 0 {
flags.Usage()
return 2
}
for i, value := range targets {
expanded, err := expandTargetShorthand(value, originRemoteTarget)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
targets[i] = expanded
}
if interval <= 0 || concurrency < 0 {
fmt.Fprintln(os.Stderr, "interval must be positive and concurrency cannot be negative")
return 2
}
if !noWebUI && (webUIPort < 1 || webUIPort > 65535) {
fmt.Fprintln(os.Stderr, "web-ui-port must be between 1 and 65535")
return 2
}
if err := webui.ValidateBind(bind); !noWebUI && err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
limit := concurrency
if limit == 0 {
limit = 3
}
binary := codexBinary
if agentSpecs.values[0].Name == "claude" {
binary = claudeBinary
}
// The web dashboard's restart button (issue #665) shuts the run down like
// Ctrl+C and sets restartRequested. This is deferred first so it runs
// last, after every other deferred cleanup has closed the dashboard port,
// browser, and subprocesses the relaunched instance takes over.
var restartRequested atomic.Bool
var uiDone chan struct{}
defer func() {
if !restartRequested.Load() || code != 0 {
return
}
if uiDone != nil {
// Let the terminal dashboard restore the screen before the new
// instance draws its own.
<-uiDone
}
code = relaunch(os.Stderr)
}()
// Every active run's work is committed and pushed before glorp stops its
// agents (issue #741). The shutdown signals and the restart button share
// this one checkpointer, so both take the same checkpoint, once.
activeRuns := &activeAgents{}
checkpointer := newShutdownCheckpointer(activeRuns, func(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
})
ctx, stop := process.ShutdownContext(func() { checkpointer.Checkpoint() })
defer stop()
ctx, requestShutdown := context.WithCancel(ctx)
defer requestShutdown()
// Nothing glorp started may outlive it, so sweep up any subprocess whose own
// cleanup did not run before the daemon returns (issue #260).
defer process.ReapAll()
var driver *browser.Browser
if browserOptions.Enabled {
// One browser for the whole run: every target gets a tab on it rather
// than a browser of its own. A browser that cannot start is fatal, since
// quietly falling back to the API path would answer a request for
// browser mode with something else entirely.
started, err := browser.Start(ctx, browserOptions.config())
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
driver = started
defer func() { _ = driver.Close() }()
}
gh := GHCLI{Binary: "gh", ReadyState: strings.TrimSpace(readyState), publicRepoCache: &sync.Map{}, selfLoginCache: &sync.Map{}}
gh.Filter, gh.AllIssues = filter.String(), allIssues
if len(allowedCommenters) == 0 {
// Defaults to the authenticated gh user, so a direct @/glorp:ID
// mention only fires for someone glorp already trusts (issue #294).
login, err := gh.resolveSelfLogin(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "resolve authenticated gh user for --allowed-commenters: %v\n", err)
return 1
}
allowedCommenters = []string{login}
}
// A new comment mentioning this login rechecks its issue (issue #708). It
// is a convenience next to @/glorp:ID, so failing to read it is not fatal.
selfLogin, err := gh.resolveSelfLogin(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "resolve authenticated gh user: %v; comments mentioning it will not trigger rechecks\n", err)
}
events := make(chan WebhookEvent, 1)
output := io.Writer(os.Stdout)
var ui *TerminalUI
if shouldUseTerminalUI(noTui, os.Stdout) {
ui = NewTerminalUI(version, upgradeRepo(os.Getenv))
output = ui.Writer()
uiDone = make(chan struct{})
go func() {
defer close(uiDone)
_ = ui.Run(ctx)
}()
}
var webUI *webui.Server
var webServer *http.Server
var webListener net.Listener
var webPort int
if !noWebUI {
var err error
webUI, err = webui.New(version)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
webUI.SetReleaseRepo(upgradeRepo(os.Getenv))
webListener, webPort, err = webui.Listen(bind, webUIPort)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
// Record the bound port so `glorp ui` finds this instance even when it
// listens far away from the default scan range.
removeRecord, err := writeDashboardRecord(dashboardRecordsDir(os.Getenv), webPort, os.Getpid())
if err != nil {
fmt.Fprintf(os.Stderr, "record dashboard port: %v\n", err)
}
defer removeRecord()
webServer = &http.Server{Handler: webUI}
stopFrontend, err := webui.StartFrontend(ctx, output, process.Supervisor{})
if err != nil {
fmt.Fprintf(os.Stderr, "start web UI frontend: %v\n", err)
return 1
}
defer stopFrontend()
defer webServer.Close()
}
if ui == nil && webUI == nil {
fmt.Fprintln(output, "UI disabled")
}
// --remote-control reads as one switch for both agents, but there is nothing
// for it to pass to a Codex run. Say so once at startup rather than leaving an
// opted-in Codex watch to wonder why nothing reached the phone.
if notice := remoteControlCodexNotice(remoteControl, agentSpecs.names()); notice != "" {
fmt.Fprintln(output, notice)
if webUI != nil {
webUI.Log(notice)
}
}
// Opting in currently buys nothing: no lever reaches a `claude -p` run (see
// remoteControlNoLeverFinding). Say so at startup so the flag's silence is
// explained where it is turned on, not only in the README.
if notice := remoteControlInertNotice(remoteControl); notice != "" {
fmt.Fprintln(output, notice)
if webUI != nil {
webUI.Log(notice)
}
}
wOut := output
if ui != nil {
wOut = io.Discard
}
var agentCursor *atomic.Uint64
if len(agentSpecs.values) > 1 {
agentCursor = &atomic.Uint64{}
}
identity, err := newIdentity()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
// The runner picks each run's clone directory from the instance's live
// temp-directories setting, which the dashboard can change (issue #830).
var watch *Glorp
runner := CommandRunner{Binary: binary, CodexBinary: codexBinary, ClaudeBinary: claudeBinary, AgentBinaries: agentBinaries.values(), Agents: agentSpecs.specs(), Agent: agentSpecs.values[0].String(), Repo: targets[0], Identity: identity, Yolo: yolo, RemoteControl: remoteControl, NoMerge: noMerge, NoChangelog: noChangelog, Definitions: registry, agentCursor: agentCursor, Active: activeRuns, CloneRoot: func() (string, error) { return watch.CloneRoot() }}
// Quota commands are run through the same executable the agent itself is
// invoked with, so --agent-binary points both at the same install.
quota := combinedQuotaReader(namedQuotaReaders(registry, agentSpecs.names(), runner.binary))
webUIURL := ""
if webUI != nil {
webUIURL = webui.URL(bind, webPort)
}
w := &Glorp{Repo: targets[0], Targets: targets, Interval: interval, UseWebhooks: !poll, WebUIURL: webUIURL, Events: events, Concurrency: limit, StatePath: statePath, ReadyState: gh.ReadyState, Issues: gh, Discussions: gh, Status: gh, Comments: gh, Mentions: gh, Projects: gh, Identity: identity, AllowedCommenters: allowedCommenters, SelfLogin: selfLogin, UI: combineUIReporters(terminalUIReporter(ui), webUI), Quota: quota, Runner: runner, Active: activeRuns, Registry: registry, Out: wOut, SchedulesPath: flagValue[string](flags, "schedules")}
checkpointer.SetLog(w.logf)
// Once a run's work is checkpointed, its issue's ownership is handed back
// so the next instance can pick it up at once (issue #857).
checkpointer.SetRescind(w.rescindOwnership)
w.noMerge.Store(noMerge)
w.noChangelog.Store(noChangelog)
w.autoUpdate.Store(autoUpdate)
w.SetTempDirs(tempDirs)
watch = w
w.SetUnblockInterval(unblockInterval)
w.SetUnblockAgent(unblock)
w.SetPromptAgent(prompt)
// Browser mode reads issues and boards off GitHub's rendered pages instead
// of the API. A nil browser leaves the GHCLI sources above in place.
applyBrowserSources(w, driver, browserOptions, gh)
restartHandler := newRestartHandler(&restartRequested, checkpointer.Checkpoint, requestShutdown, w.logf, "restart requested from the web dashboard")
// The updater (issue #783) restarts through the same checkpoint and
// shutdown as the restart button, after swapping in the new binary.
updates := newWatchUpdater(updateInterval, activeRuns, w.autoUpdate.Load, newRestartHandler(&restartRequested, checkpointer.Checkpoint, requestShutdown, w.logf, "restarting onto the updated glorp"), w.logf, ui, webUI)
// Installed skills older than this release are reinstalled, or reported
// when they cannot be, rather than left to steer agents with stale
// instructions (issue #797).
if home, err := os.UserHomeDir(); err == nil {
check := skillsCheck{Version: version, Repo: upgradeRepo(os.Getenv), Dir: installedSkillsDir(home), Bundle: bundledSkills, Targets: registry.SkillsTargets(), Logf: w.logf}
check.Refresh = skillsRefresher{Repo: check.Repo, Run: npxCommand}.Refresh
go check.Run(ctx)
}
promptHandler := func(request string) (core.PromptEntry, error) {
return w.SubmitPrompt(ctx, request)
}
if webUI != nil {
agentsHandler := func(ctx context.Context) ([]core.AgentStatus, error) {
return agentStatuses(ctx, w.registry())
}
refreshHandler := func(ctx context.Context) error {
w.nudgePoll()
return nil
}
webUI.SetRestartProgressHandler(checkpointer.Progress)
webUI.SetPromptHandler(promptHandler)
webUI.SetUnblockHandler(w.TriggerUnblock)
webUI.SetIssueUpdateHandler(w.PostIssueUpdate)
webUI.SetAskHandler(w.AskPrompt)
webUI.SetCreateIssueHandler(w.CreateIssue)
// Wired before the server starts, like every handler startWebUI sets.
webUI.SetClonesHandlers(w.ListClones, w.ClearClones)
webUI.SetScheduleHandler(w.HandleSchedule)
webUI.SetJobEventsHandler(w.JobEvents)
startWebUI(webUI, webServer, webListener, bind, webPort, output, w.handleJobAction, persistingSettingsHandler(w.ApplySettings, configPath, w.logf), agentsHandler, refreshHandler, restartHandler)
}
if ui != nil {
ui.SetRefreshHandler(w.nudgePoll)
ui.SetJobActionHandler(w.handleJobAction)
ui.SetPromptHandler(promptHandler)
}
if updates != nil {
if webUI != nil {
webUI.SetUpdateHandler(updates.Apply)
}
if ui != nil {
ui.SetUpdateHandler(updates.Apply)
}
go updates.Run(ctx)
}
var server *http.Server
if !poll {
listener, err := listenForWebhooks(listen)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
server = &http.Server{Addr: listen, Handler: WebhookHandler{Events: events, Secret: webhookSecret, WebhookPath: webhookPath}}
go func() {
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "webhook server: %v\n", err)
}
}()
defer server.Close()
listenAddr := listener.Addr().String()
fmt.Fprintf(output, "webhook server listening on %s%s\n", listenAddr, webhookPath)
ngrokAddr := ngrokTargetAddr(listenAddr)
fmt.Fprintf(output, "starting ngrok tunnel for %s\n", ngrokAddr)
tunnel, err := ngrok.Start(ctx, ngrokBinary, ngrokAddr, output)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
// The supervisor owns the tunnel from here on, so whichever tunnel is
// running when the run ends is the one stopped.
supervisor := &tunnelSupervisor{tunnel: tunnel}
defer supervisor.Close()
endpoint, err := ngrok.WebhookURL(tunnel.URL(), webhookPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
fmt.Fprintf(output, "ngrok tunnel ready at %s\n", tunnel.URL())
configured := 0
for _, target := range targets {
if _, err := gh.ConfigureWebhook(ctx, target, endpoint, webhookSecret); err != nil {
if errors.Is(err, errProjectWebhookUnavailable) {
fmt.Fprintln(output, err)
continue
}
if !errors.Is(err, errWebhookPartiallyConfigured) {
fmt.Fprintln(os.Stderr, err)
return 1
}
fmt.Fprintln(output, err)
}
configured++
fmt.Fprintf(output, "configured GitHub webhook for %s\n", target)
}
if configured == 0 {
fmt.Fprintln(output, "no targets available for webhook configuration")
}
// A project board can gain a repository that was not on it at startup,
// and that repository has no webhook until the target is configured
// again, so keep reconciling while the daemon runs (issue #238).
// The tunnel is checked before each reconciliation too, and started
// again when it stops reaching the webhook server, such as after the
// machine sleeps (issue #683).
supervisor.webhookPath = webhookPath
supervisor.reconciler = newWebhookReconciler(gh, targets, endpoint, webhookSecret, w.logf)
supervisor.start = func(ctx context.Context) (webhookTunnel, error) {
tunnel, err := ngrok.Start(ctx, ngrokBinary, ngrokAddr, output)
if err != nil {
return nil, err
}
return tunnel, nil
}
supervisor.probe, supervisor.logf = probeTunnel, w.logf
w.Webhooks = supervisor.reconcile
w.WebhookOnline = supervisor.online
}
if err := runUntilStopped(ctx, w.Run, shutdownDrainBudget, w.logf); err != nil {
if ui != nil {
ui.program.Quit()
}
fmt.Fprintln(os.Stderr, err)
return 1
}
if ui != nil {
ui.program.Quit()
}
return 0
}
// shutdownDrainBudget is how long the watch may take to wind down once
// shutdown starts, after the checkpoint, before glorp stops waiting for it.
const shutdownDrainBudget = 30 * time.Second
// runUntilStopped runs the watch until it returns, or until it has had budget
// to finish after ctx is cancelled. A run that is still unwinding then is left
// for the deferred reaping, so a shutdown or restart always goes ahead
// instead of waiting forever on one stuck run (issue #749).
func runUntilStopped(ctx context.Context, run func(context.Context) error, budget time.Duration, logf func(string, ...interface{})) error {
done := make(chan error, 1)
go func() { done <- run(ctx) }()
select {
case err := <-done:
return err
case <-ctx.Done():
}
timer := time.NewTimer(budget)
defer timer.Stop()
select {
case err := <-done:
return err
case <-timer.C:
logf("shutdown: runs were still stopping after %s; stopping their processes and going ahead", budget)
return nil
}
}
// startWebUI wires the dashboard's job-action and settings handlers, then
// begins serving requests. The handlers must be wired before the server
// starts accepting connections: a request that lands in the gap sees the
// handler as unset and gets a spurious "unavailable" response, which the
// settings modal has no retry for and so is left stuck (issue #571).
func startWebUI(webUI *webui.Server, webServer *http.Server, listener net.Listener, bind string, port int, output io.Writer, jobActionHandler func(context.Context, core.JobAction) error, settingsHandler func(context.Context, core.SettingsUpdate) (core.SettingsSnapshot, error), agentsHandler func(context.Context) ([]core.AgentStatus, error), refreshHandler func(context.Context) error, restartHandler func(context.Context) ([]core.CheckpointResult, error)) {
webUI.SetJobActionHandler(jobActionHandler)
webUI.SetSettingsHandler(settingsHandler)
webUI.SetAgentsHandler(agentsHandler)
webUI.SetRefreshHandler(refreshHandler)
webUI.SetRestartHandler(restartHandler)
go func() {
if err := webServer.Serve(listener); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "web UI server: %v\n", err)
}
}()
webURL := webui.URL(bind, port)
fmt.Fprintf(output, "web UI listening on %s\n", webURL)
webUI.Log("web UI listening on " + webURL)
if notice := exposedWebUINotice(bind); notice != "" {
fmt.Fprintln(output, notice)
webUI.Log(notice)
}
}
// exposedWebUINotice warns when --bind puts the dashboard within reach of
// other machines (issue #666). The dashboard has no authentication, so anyone
// who can reach it can stop jobs and change this instance's settings.
func exposedWebUINotice(bind string) string {
if webui.IsLoopback(bind) {
return ""
}
address := bind
if address == "" {
address = "all interfaces"
}
return fmt.Sprintf("warning: web UI is bound to %s and has no authentication; anyone who can reach it can control this glorp instance", address)
}
// persistingSettingsHandler writes a dashboard settings change back to the
// config file's settings section after the running instance has accepted it
// (issue #614), so a setting changed in the browser survives a restart. The
// live change has already taken effect by then, so a file that cannot be
// written is logged rather than reported as a failed update.
func persistingSettingsHandler(apply func(context.Context, core.SettingsUpdate) (core.SettingsSnapshot, error), configPath string, logf func(string, ...interface{})) func(context.Context, core.SettingsUpdate) (core.SettingsSnapshot, error) {
return func(ctx context.Context, update core.SettingsUpdate) (core.SettingsSnapshot, error) {
snapshot, err := apply(ctx, update)
if err != nil {
return snapshot, err
}
values := settingsUpdateFlags(update)
if len(values) == 0 {
return snapshot, nil
}
if err := saveConfigSettings(configPath, values); err != nil && logf != nil {
logf("save settings to %s: %v", configPath, err)
}
return snapshot, nil
}
}
// splitAllowedCommenters parses the comma-separated --allowed-commenters
// value into a list of GitHub logins, dropping empty entries left by stray
// commas or surrounding whitespace.
func splitAllowedCommenters(value string) []string {
var logins []string
for _, part := range strings.Split(value, ",") {
if trimmed := strings.TrimSpace(part); trimmed != "" {
logins = append(logins, trimmed)
}
}
return logins
}
// flagValue reads a parsed flag's value from a flag set by name, keeping the
// watch command's long option list readable without threading two dozen
// pointers through it.
func flagValue[T any](flags *flag.FlagSet, name string) T {
var zero T
found := flags.Lookup(name)
if found == nil {
return zero
}
getter, ok := found.Value.(flag.Getter)
if !ok {
return zero
}
value, ok := getter.Get().(T)
if !ok {
return zero
}
return value
}
func listenForWebhooks(address string) (net.Listener, error) {
listener, err := net.Listen("tcp", address)
if err != nil {
return nil, fmt.Errorf("listen for webhooks on %s: %w", address, err)
}
return listener, nil
}
// ngrokTargetAddr rewrites a listener's bound address into one ngrok can
// connect to. A wildcard host (from binding "" or "0.0.0.0" or "::", as the
// default ":0" listen address does) has no meaning as a connection target:
// Linux silently treats it as loopback, but macOS refuses the connection,
// which is what made ngrok report the host port as not listening (issue
// #348). Loopback is always where the webhook server actually listens, so
// substituting it here works on every platform.
func ngrokTargetAddr(address string) string {
host, port, err := net.SplitHostPort(address)
if err != nil {
return address
}
if ip := net.ParseIP(host); host == "" || (ip != nil && ip.IsUnspecified()) {
host = "127.0.0.1"
}
return net.JoinHostPort(host, port)
}
func isTerminal(file *os.File) bool {
fd := file.Fd()
return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)
}
func shouldUseTerminalUI(noTui bool, output *os.File) bool {
return !noTui && shouldUseUI(false, output)
}
func shouldUseUI(disabled bool, output *os.File) bool {
return !disabled && isTerminal(output)
}
func terminalUIReporter(ui *TerminalUI) UIReporter {
if ui == nil {
return nil
}
return ui
}
type GHCLI struct {
Binary string
Filter string
AllIssues bool
ReadyState string
runCommand func(context.Context, ...string) ([]byte, error)
// publicAPI overrides the unauthenticated public GitHub API request used
// to poll public repositories without spending the authenticated gh
// token's rate limit. Nil uses the real network implementation.
publicAPI publicAPIDoer
// publicRepoCache memoizes repo visibility across the lifetime of a run.
// It is a pointer so copies of GHCLI (it is passed by value throughout)
// share one cache; nil (the zero value used in tests that build GHCLI
// literals directly) simply disables memoization rather than panicking.
publicRepoCache *sync.Map
// selfLoginCache memoizes the authenticated gh user's login, needed only
// to translate the "@me" search qualifiers for the public API.
selfLoginCache *sync.Map
}
// ghCommandTimeout bounds a single `gh` invocation. Every read and write glorp
// makes against GitHub goes through one, including the issue listing the poll
// loop blocks on, so a subprocess that hangs -- a stuck TLS connection, a
// prompt nobody answers -- would otherwise stop the watch dispatching anything
// for the rest of the run (issue #472). It is generous enough that no ordinary
// call reaches it, and a variable only so tests need not spend it.
var ghCommandTimeout = 2 * time.Minute
// ghCommandWaitDelay is how long a `gh` call killed at its deadline is given to
// let go of its output pipe before the read gives up on it.
const ghCommandWaitDelay = time.Second
func (g GHCLI) run(ctx context.Context, args ...string) ([]byte, error) {
// The deadline is the command's own, and is applied before the runner is
// chosen so every implementation of the call is bounded by it. For the
// real one it is also the child process's: CommandContext kills it when
// the deadline expires, so a hung `gh` is reaped rather than left behind.
runCtx, cancel := context.WithTimeout(ctx, ghCommandTimeout)
defer cancel()
if g.runCommand != nil {
output, err := g.runCommand(runCtx, args...)
return output, g.timedOut(ctx, runCtx, args, err)
}
cmd := exec.CommandContext(runCtx, g.Binary, args...)
cmd.WaitDelay = ghCommandWaitDelay
output, err := process.CombinedOutput(cmd)
return output, g.timedOut(ctx, runCtx, args, err)
}
// timedOut replaces the bare context error of a `gh` call that ran out of time
// with one naming the call and the deadline, and leaves every other outcome
// alone. A run being shut down is not a timeout, however the command ended.
func (g GHCLI) timedOut(ctx, runCtx context.Context, args []string, err error) error {
if errors.Is(runCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil {
return fmt.Errorf("gh %s did not finish within %s", strings.Join(args, " "), formatInterval(ghCommandTimeout))
}
return err
}
// StacksEnabled reports whether repo has GitHub stacked pull requests
// enabled. The Stacks API answers 404 Not Found for a repository without
// them, which is a definite "no" rather than an error (issue #657).
func (g GHCLI) StacksEnabled(ctx context.Context, repo string) (bool, error) {
if err := g.apiReachable(ctx, g.isPublicRepo(ctx, repo), "repos/"+repo+"/stacks?per_page=1"); err != nil {
if detail := err.Error(); strings.Contains(detail, "HTTP 404") || strings.Contains(detail, "Not Found") {
return false, nil
}
return false, fmt.Errorf("list stacks for %s: %w", repo, err)
}
return true, nil
}
// ForkFor reports where a fix for an issue in repo is pushed (issue #712): an
// empty string when the authenticated user can push to repo, and otherwise
// the OWNER/REPO of the user's fork of it. GitHub's create-fork call returns
// the existing fork when there already is one, so it doubles as the lookup.
func (g GHCLI) ForkFor(ctx context.Context, repo string) (string, error) {
output, err := g.run(ctx, "api", "repos/"+repo, "--jq", ".permissions.push")
if err != nil {
return "", fmt.Errorf("read permissions on %s: %w: %s", repo, err, strings.TrimSpace(string(output)))
}
if strings.TrimSpace(string(output)) == "true" {
return "", nil
}
output, err = g.run(ctx, "api", "-X", "POST", "repos/"+repo+"/forks", "--jq", ".full_name")
if err != nil {
return "", fmt.Errorf("fork %s: %w: %s", repo, err, strings.TrimSpace(string(output)))
}
fork := strings.TrimSpace(string(output))
if !validRepo(fork) {
return "", fmt.Errorf("fork %s: unexpected repository name %q", repo, fork)
}
return fork, nil
}
func (g GHCLI) OriginatingWorkState(ctx context.Context, repo string, number int) (OriginatingWorkState, error) {
public := g.isPublicRepo(ctx, repo)
output, err := g.apiGETObject(ctx, public, "repos/"+repo+"/issues/"+strconv.Itoa(number))
if err != nil {
return OriginatingWorkState{}, fmt.Errorf("read issue #%d state: %w: %s", number, err, strings.TrimSpace(string(output)))
}
var issue struct {
State string `json:"state"`
Body string `json:"body"`
}
if err := json.Unmarshal(output, &issue); err != nil {
return OriginatingWorkState{}, fmt.Errorf("decode issue #%d state: %w", number, err)
}
// The timeline is read in full: a long-lived issue's current pull request
// is often cross-referenced well past the first page (issue #759).
output, err = g.apiGETPaginated(ctx, public, "repos/"+repo+"/issues/"+strconv.Itoa(number)+"/timeline?per_page=100")
if err != nil {
return OriginatingWorkState{}, fmt.Errorf("read issue #%d timeline: %w: %s", number, err, strings.TrimSpace(string(output)))
}
var events []struct {
Event string `json:"event"`
Source struct {
Issue struct {
Number int `json:"number"`
State string `json:"state"`
Body string `json:"body"`
RepositoryURL string `json:"repository_url"`
Repository struct {
FullName string `json:"full_name"`
} `json:"repository"`
PullRequest *struct {
MergedAt *time.Time `json:"merged_at"`
} `json:"pull_request"`
} `json:"issue"`
} `json:"source"`
}
if err := json.Unmarshal(output, &events); err != nil {
return OriginatingWorkState{}, fmt.Errorf("decode issue #%d timeline: %w", number, err)
}
state := OriginatingWorkState{IssueState: issue.State, IssueBody: issue.Body}
for _, event := range events {
pullRequest := event.Source.Issue
if event.Event != "cross-referenced" || pullRequest.PullRequest == nil {
continue
}
// A pull request in another repository, such as one opened from a
// fork, is read back from its own repository (issue #718).
pullRepo := timelineSourceRepo(pullRequest.Repository.FullName, pullRequest.RepositoryURL, repo)
if !closesIssue(pullRequest.Body, pullRepo, repo, number) {
continue
}
pullPublic := public
if !strings.EqualFold(pullRepo, repo) {
pullPublic = g.isPublicRepo(ctx, pullRepo)
}
output, err := g.apiGETObject(ctx, pullPublic, "repos/"+pullRepo+"/pulls/"+strconv.Itoa(pullRequest.Number))
if err != nil {
return OriginatingWorkState{}, fmt.Errorf("read pull request %s#%d state for issue #%d: %w: %s", pullRepo, pullRequest.Number, number, err, strings.TrimSpace(string(output)))
}
var currentPullRequest struct {
State string `json:"state"`
Body string `json:"body"`
MergedAt *time.Time `json:"merged_at"`
Draft bool `json:"draft"`
Base struct {
Ref string `json:"ref"`
Repo struct {
DefaultBranch string `json:"default_branch"`
} `json:"repo"`
} `json:"base"`
}
if err := json.Unmarshal(output, ¤tPullRequest); err != nil {
return OriginatingWorkState{}, fmt.Errorf("decode pull request %s#%d state for issue #%d: %w", pullRepo, pullRequest.Number, number, err)
}
base := currentPullRequest.Base
stacked := base.Ref != "" && base.Repo.DefaultBranch != "" && base.Ref != base.Repo.DefaultBranch
tasksDone, tasksTotal := core.ChecklistProgress(currentPullRequest.Body)
state.PullRequests = append(state.PullRequests, PullRequestWorkState{Repository: pullRepo, Number: pullRequest.Number, State: currentPullRequest.State, Merged: currentPullRequest.MergedAt != nil, IsDraft: currentPullRequest.Draft, Stacked: stacked, TasksDone: tasksDone, TasksTotal: tasksTotal})
}
return state, nil
}
// closesIssue reports whether a pull request body hosted in pullRepo closes
// issue number in repo. A bare #N only names repo's issue when the pull
// request lives there too; from another repository the reference must be
// fully qualified as OWNER/REPO#N or an issue URL (issue #718).
func closesIssue(body, pullRepo, repo string, number int) bool {
quoted := regexp.QuoteMeta(repo)
reference := quoted + `#|https://github\.com/` + quoted + `/issues/`
if strings.EqualFold(pullRepo, repo) {
reference += `|#`
}
pattern := `(?i)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+(?:` + reference + `)` + strconv.Itoa(number) + `\b`
return regexp.MustCompile(pattern).MatchString(body)
}
// timelineSourceRepo returns the OWNER/REPO a timeline event's source issue or
// pull request lives in, falling back to repo when the event omits it.
func timelineSourceRepo(fullName, repositoryURL, repo string) string {
if validRepo(fullName) {
return fullName
}
if index := strings.Index(repositoryURL, "/repos/"); index >= 0 {
if candidate := repositoryURL[index+len("/repos/"):]; validRepo(candidate) {
return candidate
}
}
return repo
}
const defaultIssueFilter = core.DefaultIssueFilter
type filterFlag struct {
values []string
set bool
}
func (f *filterFlag) String() string {
return strings.Join(f.values, " ")
}
func (f *filterFlag) Set(value string) error {
if !f.set {
f.values = nil
f.set = true
}
f.values = append(f.values, value)
return nil
}
// agentSpec is a single --agent value: the agent to run plus the optional
// model and reasoning level to run it with. Each agent carries its own model
// so repeated --agent values can mix agents and models freely.
type agentSpec struct {
Name string
Model string
Level string
}
// String renders the spec back into its provider/model:level form so it can be
// persisted in the work state and parsed again when a session resumes.
func (s agentSpec) String() string {
value := s.Name
if s.Model != "" {
value += "/" + s.Model
}
if s.Level != "" {
value += ":" + s.Level
}
return value
}
// parseAgentSpec parses provider/model:level, where the model and level are
// both optional (for example codex, claude/opus, or codex/gpt-5.6:high).
func parseAgentSpec(value string) (agentSpec, error) {
return parseAgentSpecIn(agentRegistry(), value)
}
// parseAgentSpecIn is parseAgentSpec against an explicit registry. The agent
// name, and the models and levels it accepts, come from the registry rather
// than from a hardcoded list, so an agent declared in .glorp.config.json is
// accepted by --agent on the same terms as a built-in one.
func parseAgentSpecIn(registry *agents.Registry, value string) (agentSpec, error) {
name := strings.TrimSpace(value)
var spec agentSpec
level, hasLevel := "", false
if index := strings.LastIndex(name, ":"); index >= 0 {
level, hasLevel = strings.TrimSpace(name[index+1:]), true
name = strings.TrimSpace(name[:index])
}
if base, model, ok := strings.Cut(name, "/"); ok {
name, spec.Model = strings.TrimSpace(base), strings.TrimSpace(model)
if spec.Model == "" {
return agentSpec{}, fmt.Errorf("agent model cannot be empty")
}
}
definition, ok := registry.Lookup(name)
if !ok {
return agentSpec{}, unknownAgentError(registry, name)
}
if hasLevel {
if !definition.AcceptsLevel(level) {
return agentSpec{}, definition.LevelError()
}
spec.Level = level
}
if spec.Model != "" && !definition.AcceptsModel(spec.Model) {
return agentSpec{}, definition.ModelError()
}
// A spec that names no model takes the definition's managed default
// rather than whatever the agent's CLI would reach for on its own, which
// is usually its largest model (issue #612). Resolving it here, where the
// spec is built, is what makes the choice visible everywhere a spec goes:
// the rendered argv, the dashboard line, and the agent/model:level string
// persisted in the work state, so a resumed session keeps the model it
// started with even if the default later moves.
spec.Model = definition.ModelOrDefault(spec.Model)