-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathmain.go
More file actions
1935 lines (1745 loc) · 61 KB
/
main.go
File metadata and controls
1935 lines (1745 loc) · 61 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 (
"bufio"
"context"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
"github.com/onllm-dev/onwatch/v2/internal/agent"
"github.com/onllm-dev/onwatch/v2/internal/api"
"github.com/onllm-dev/onwatch/v2/internal/config"
"github.com/onllm-dev/onwatch/v2/internal/menubar"
"github.com/onllm-dev/onwatch/v2/internal/notify"
"github.com/onllm-dev/onwatch/v2/internal/store"
"github.com/onllm-dev/onwatch/v2/internal/tracker"
"github.com/onllm-dev/onwatch/v2/internal/update"
"github.com/onllm-dev/onwatch/v2/internal/web"
)
//go:embed VERSION
var embeddedVersion string
var version = "dev"
func init() {
if version == "dev" {
version = strings.TrimSpace(embeddedVersion)
}
}
// dualHandler fans out log records to two slog handlers:
// a file handler (full verbosity) and a stdout handler (warn/error only).
// Used in --debug mode so systemd/journald stays clean while .onwatch.log gets everything.
type dualHandler struct {
file slog.Handler
stdout slog.Handler
}
func (d dualHandler) Enabled(_ context.Context, level slog.Level) bool {
return d.file.Enabled(context.Background(), level) || d.stdout.Enabled(context.Background(), level)
}
func (d dualHandler) Handle(ctx context.Context, r slog.Record) error {
if d.file.Enabled(ctx, r.Level) {
_ = d.file.Handle(ctx, r)
}
if d.stdout.Enabled(ctx, r.Level) {
_ = d.stdout.Handle(ctx, r)
}
return nil
}
func (d dualHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return dualHandler{file: d.file.WithAttrs(attrs), stdout: d.stdout.WithAttrs(attrs)}
}
func (d dualHandler) WithGroup(name string) slog.Handler {
return dualHandler{file: d.file.WithGroup(name), stdout: d.stdout.WithGroup(name)}
}
func main() {
if err := runWithCrashCapture(); err != nil {
if !errors.Is(err, errCodexProfileRefreshAborted) {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
// On Windows, if the error is about missing configuration and we're likely
// running from a double-click (no arguments), show installation instructions
// and wait for user input before closing the window.
if runtime.GOOS == "windows" && len(os.Args) == 1 {
if strings.Contains(err.Error(), "provider must be configured") {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "To set up onWatch, run the PowerShell installer:")
fmt.Fprintln(os.Stderr, " irm https://raw.githubusercontent.com/onllm-dev/onwatch/main/install.ps1 | iex")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Or download install.bat from GitHub releases and double-click it.")
fmt.Fprintln(os.Stderr, "")
fmt.Fprint(os.Stderr, "Press Enter to exit...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
}
os.Exit(1)
}
}
var (
pidDir = defaultPIDDir()
pidFile = filepath.Join(pidDir, "onwatch.pid")
)
// hasFlag checks if a flag exists anywhere in os.Args[1:].
func hasFlag(flag string) bool {
for _, arg := range os.Args[1:] {
if arg == flag {
return true
}
}
return false
}
// hasCommand checks if any of the given commands/flags exist in os.Args[1:].
func hasCommand(cmds ...string) bool {
for _, arg := range os.Args[1:] {
for _, cmd := range cmds {
if arg == cmd {
return true
}
}
}
return false
}
func printMenubarHelp() {
fmt.Print(menubarHelpText())
}
func menubarHelpText() string {
return "" +
"onWatch Menubar Companion\n\n" +
"Usage: onwatch menubar [OPTIONS]\n\n" +
"Options:\n" +
" --port PORT Dashboard port to connect to (default: 9211)\n" +
" --debug Run in foreground (logs to file, stdout gets warn/error)\n" +
" --debugstdout Run in foreground with all logs to stdout\n" +
" --help Show this help message\n"
}
// stopPreviousInstance stops any running onwatch instance using PID file + port check.
// In test mode, only PID file is used (no port scanning) to avoid killing production.
func stopPreviousInstance(port int, testMode bool) {
myPID := os.Getpid()
stopped := false
// Method 1: PID file (handles both "PID" and "PID:PORT" formats)
if data, err := os.ReadFile(pidFile); err == nil {
content := strings.TrimSpace(string(data))
var pid, filePort int
// Parse PID:PORT format (new) or just PID (legacy)
if strings.Contains(content, ":") {
parts := strings.Split(content, ":")
if len(parts) >= 2 {
pid, _ = strconv.Atoi(parts[0])
filePort, _ = strconv.Atoi(parts[1])
}
} else {
pid, _ = strconv.Atoi(content)
}
if pid > 0 && pid != myPID {
if proc, err := os.FindProcess(pid); err == nil {
if err := proc.Signal(syscall.SIGTERM); err == nil {
fmt.Printf("Stopped previous instance (PID %d) via PID file\n", pid)
stopped = true
}
}
}
os.Remove(pidFile)
// If PID file had a port and we didn't stop it, try that specific port
if !stopped && filePort > 0 {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", filePort), 500*time.Millisecond)
if err == nil {
conn.Close()
if pids := findOnwatchOnPort(filePort); len(pids) > 0 {
for _, foundPID := range pids {
if foundPID == myPID {
continue
}
if proc, err := os.FindProcess(foundPID); err == nil {
if err := proc.Signal(syscall.SIGTERM); err == nil {
fmt.Printf("Stopped previous instance (PID %d) on port %d\n", foundPID, filePort)
stopped = true
}
}
}
}
}
}
}
// Method 2: Check if the port is in use and kill the occupying onwatch process
// Skip in test mode to avoid accidentally killing production instances
if !testMode && !stopped && port > 0 {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 500*time.Millisecond)
if err == nil {
conn.Close()
// Port is occupied - find which process holds it
if pids := findOnwatchOnPort(port); len(pids) > 0 {
for _, pid := range pids {
if pid == myPID {
continue
}
if proc, err := os.FindProcess(pid); err == nil {
if err := proc.Signal(syscall.SIGTERM); err == nil {
fmt.Printf("Stopped previous instance (PID %d) on port %d\n", pid, port)
stopped = true
}
}
}
}
}
}
if stopped {
time.Sleep(500 * time.Millisecond)
}
}
// findOnwatchOnPort uses lsof (macOS/Linux) to find onwatch processes on a port.
func findOnwatchOnPort(port int) []int {
if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {
return nil
}
// lsof -ti :PORT gives PIDs listening on that port
out, err := exec.Command("lsof", "-ti", fmt.Sprintf(":%d", port)).Output()
if err != nil {
return nil
}
var pids []int
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
line = strings.TrimSpace(line)
if pid, err := strconv.Atoi(line); err == nil && pid > 0 {
// Verify it's an onwatch process by checking the command name
if isOnwatchProcess(pid) {
pids = append(pids, pid)
}
}
}
return pids
}
// isOnwatchProcess checks if a PID belongs to an onwatch (or legacy syntrack) binary.
func isOnwatchProcess(pid int) bool {
out, err := exec.Command("ps", "-p", strconv.Itoa(pid), "-o", "comm=").Output()
if err != nil {
return false
}
cmd := strings.ToLower(strings.TrimSpace(string(out)))
return strings.Contains(cmd, "onwatch") || strings.Contains(cmd, "syntrack")
}
func ensurePIDDir() error {
return os.MkdirAll(pidDir, 0755)
}
// sha256hex returns the SHA-256 hex hash of a string.
func sha256hex(s string) string {
h := sha256.Sum256([]byte(s))
return fmt.Sprintf("%x", h)
}
// deriveEncryptionKey derives the runtime encryption key for sensitive settings.
// It must stay aligned with the web layer, which encrypts SMTP passwords using
// HKDF with the stored encryption salt when available.
func deriveEncryptionKey(passwordHash string) string {
return web.DeriveEncryptionKey(passwordHash, nil)
}
// deriveLegacyEncryptionKey returns the pre-salt legacy key derivation used by
// older releases, for migration of previously encrypted SMTP passwords.
func deriveLegacyEncryptionKey(passwordHash string) string {
if len(passwordHash) == 64 {
return passwordHash
}
h := sha256.Sum256([]byte(passwordHash))
return fmt.Sprintf("%x", h)
}
// migrateDBLocation moves the database from old default locations to the new one.
// Only runs when no explicit --db or ONWATCH_DB_PATH was set.
func migrateDBLocation(newPath string, logger *slog.Logger) {
oldPaths := []string{
"./onwatch.db",
}
oldHome := os.Getenv("HOME")
if oldHome != "" {
oldPaths = append(oldPaths,
filepath.Join(oldHome, ".onwatch", "onwatch.db"),
)
}
for _, oldPath := range oldPaths {
if oldPath == newPath {
continue
}
if _, err := os.Stat(oldPath); err != nil {
continue
}
if _, err := os.Stat(newPath); err == nil {
break // new already exists, skip
}
// Ensure target directory exists
if err := os.MkdirAll(filepath.Dir(newPath), 0700); err != nil {
logger.Warn("Failed to create data directory", "path", filepath.Dir(newPath), "error", err)
continue
}
// Move DB + WAL/SHM files
if err := os.Rename(oldPath, newPath); err != nil {
logger.Warn("Failed to migrate database", "from", oldPath, "to", newPath, "error", err)
continue
}
os.Rename(oldPath+"-wal", newPath+"-wal")
os.Rename(oldPath+"-shm", newPath+"-shm")
logger.Info("Migrated database", "from", oldPath, "to", newPath)
break
}
}
// fixExplicitDBPath detects when a user's .env has a misconfigured DB_PATH
// (e.g., ./onwatch.db or ./syntrack.db) while the canonical data/ path holds
// the actual historical data. It redirects to the canonical path so the
// dashboard shows existing data instead of appearing empty.
func fixExplicitDBPath(cfg *config.Config, logger *slog.Logger) {
home, err := os.UserHomeDir()
if err != nil || home == "" {
return
}
canonicalPath := filepath.Join(home, ".onwatch", "data", "onwatch.db")
// Already using the canonical path - nothing to fix
absExplicit, _ := filepath.Abs(cfg.DBPath)
absCan, _ := filepath.Abs(canonicalPath)
if absExplicit == absCan {
return
}
// Check if canonical path exists and has data
canInfo, err := os.Stat(canonicalPath)
if err != nil || canInfo.Size() == 0 {
return // canonical doesn't exist or is empty
}
// Check if the explicit path exists
expInfo, err := os.Stat(cfg.DBPath)
if err != nil {
// Explicit path doesn't even exist - use canonical
logger.Info("Explicit DB path not found, redirecting to canonical",
"explicit", cfg.DBPath, "canonical", canonicalPath)
cfg.DBPath = canonicalPath
return
}
// Both exist - use whichever is larger (has more data)
if canInfo.Size() > expInfo.Size() {
logger.Warn("Explicit DB path has less data than canonical path, redirecting",
"explicit", cfg.DBPath, "explicitSize", expInfo.Size(),
"canonical", canonicalPath, "canonicalSize", canInfo.Size())
cfg.DBPath = canonicalPath
}
}
func writePIDFile(port int) error {
if err := ensurePIDDir(); err != nil {
return fmt.Errorf("failed to create PID directory: %w", err)
}
// Store both PID and port for reliable stopping
content := fmt.Sprintf("%d:%d", os.Getpid(), port)
return os.WriteFile(pidFile, []byte(content), 0644)
}
func removePIDFile() {
os.Remove(pidFile)
}
// daemonize re-executes the current binary as a detached background process.
// The parent writes the child's PID to .onwatch.pid and exits.
func daemonize(cfg *config.Config) error {
exe, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
// Resolve symlinks so re-exec works correctly
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
return fmt.Errorf("failed to resolve executable path: %w", err)
}
// Open log file for child's stdout/stderr
logName := ".onwatch.log"
if cfg.TestMode {
logName = ".onwatch-test.log"
}
logPath := filepath.Join(filepath.Dir(cfg.DBPath), logName)
logFile, err := config.OpenRotatingLogFile(logPath)
if err != nil {
return fmt.Errorf("failed to open log file for daemon: %w", err)
}
// Build child command with same args
cmd := exec.Command(exe, os.Args[1:]...)
cmd.Stdout = logFile
cmd.Stderr = logFile
cmd.Env = append(os.Environ(), "_ONWATCH_DAEMON=1")
cmd.SysProcAttr = daemonSysProcAttr()
if err := cmd.Start(); err != nil {
logFile.Close()
return fmt.Errorf("failed to start daemon: %w", err)
}
// Write child PID and port
childPID := cmd.Process.Pid
if err := ensurePIDDir(); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not create PID directory: %v\n", err)
}
pidContent := fmt.Sprintf("%d:%d", childPID, cfg.Port)
if err := os.WriteFile(pidFile, []byte(pidContent), 0644); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not write PID file: %v\n", err)
}
logFile.Close()
fmt.Printf("Daemon started (PID %d), logs: %s\n", childPID, logPath)
return nil
}
func runWithCrashCapture() (err error) {
defer func() {
if r := recover(); r != nil {
stack := string(debug.Stack())
slog.Error("Fatal panic", "panic", r, "stack", stack)
fmt.Fprintf(os.Stderr, "Fatal panic: %v\n%s\n", r, stack)
err = fmt.Errorf("panic: %v", r)
}
}()
return run()
}
func run() error {
// Phase 1: Detect test mode early and configure PID file for isolation
testMode := hasFlag("--test")
if testMode {
pidFile = filepath.Join(pidDir, "onwatch-test.pid")
}
// Phase 2: Handle subcommands (both with and without -- prefix)
// Note: "codex" must be checked before "status" because "codex profile status" contains "status"
if hasCommand("codex") {
return runCodexCommand()
}
if hasCommand("menubar") {
if hasFlag("--help") || hasFlag("-h") {
printMenubarHelp()
return nil
}
return runMenubarCommand()
}
if hasCommand("stop", "--stop") {
return runStop(testMode)
}
if hasCommand("status", "--status") {
return runStatus(testMode)
}
if hasCommand("--version", "-v", "version") {
fmt.Printf("onWatch v%s\n", version)
fmt.Println("github.com/onllm-dev/onwatch")
fmt.Println("Powered by onllm.dev")
return nil
}
if hasCommand("update", "--update") {
return runUpdate()
}
if hasCommand("setup", "--setup") {
return runSetup()
}
if hasCommand("--help", "-h") {
printHelp()
return nil
}
// Memory tuning: GOMEMLIMIT triggers MADV_DONTNEED which actually shrinks RSS.
// Without this, Go uses MADV_FREE on macOS - pages are reclaimable but still
// counted in RSS, causing a permanent ratchet effect.
debug.SetMemoryLimit(40 * 1024 * 1024) // 40 MiB soft limit
debug.SetGCPercent(50) // GC at 50% heap growth (default 100)
// Phase 3: Parse flags and load config
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Resolve auth tokens before any banner output so displayed providers
// match the providers that will actually start.
preflightLogger := slog.Default()
if cfg.AnthropicToken == "" {
if token := api.DetectAnthropicToken(preflightLogger); token != "" {
cfg.AnthropicToken = token
cfg.AnthropicAutoToken = true
}
}
if cfg.CodexToken == "" {
if token := api.DetectCodexToken(preflightLogger); token != "" {
cfg.CodexToken = token
cfg.CodexAutoToken = true
}
}
// If no global Codex token, check if saved profiles exist to bootstrap the provider.
// This allows Docker containers to start Codex polling from saved profiles alone.
if !cfg.HasProvider("codex") {
profilesDir := codexProfilesDirWithDataDir(filepath.Dir(cfg.DBPath))
if hasSavedCodexProfiles(profilesDir) {
cfg.CodexHasProfiles = true
preflightLogger.Info("Codex saved profiles detected, enabling provider", "dir", profilesDir)
}
}
isDaemonChild := os.Getenv("_ONWATCH_DAEMON") == "1"
// Write early diagnostic to stderr (inherited log file fd) BEFORE slog is configured.
// If the daemon child crashes during init, this ensures the log file isn't empty.
if isDaemonChild {
fmt.Fprintf(os.Stderr, "daemon child started (PID %d)\n", os.Getpid())
}
// Auto-fix systemd unit file BEFORE stopping the previous instance.
// When a post-update child runs this, the daemon-reload completes while
// the parent is still alive (systemd tracks it). After the child kills
// the parent below, systemd sees Restart=always and auto-starts the new binary.
// No-op if not under systemd or already up to date.
update.MigrateSystemdUnit(slog.Default())
// Stop any previous instance (parent does this, daemon child skips it)
if !isDaemonChild {
stopPreviousInstance(cfg.Port, testMode)
_ = stopMenubarProcess(testMode)
}
// Early Gemini auto-detection for banner display
if os.Getenv("GEMINI_ENABLED") != "false" && !cfg.GeminiEnabled {
if creds := api.DetectGeminiCredentials(nil); creds != nil {
cfg.GeminiEnabled = true
}
}
// Daemonize: if not in debug mode, not already the daemon child, and NOT in Docker, fork
// Docker containers should always run in foreground mode (logs to stdout)
if !cfg.DebugMode && !isDaemonChild && !cfg.IsDockerEnvironment() {
printBanner(cfg, version)
return daemonize(cfg)
}
// From here on, we are either the daemon child or running in --debug mode.
// In daemon mode, the parent already wrote the PID file with our PID.
// In debug mode, we write our own PID file.
if cfg.DebugMode {
if err := writePIDFile(cfg.Port); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not write PID file: %v\n", err)
}
}
defer removePIDFile()
// Setup logging
logWriter, err := cfg.LogWriter()
if err != nil {
return fmt.Errorf("failed to setup logging: %w", err)
}
defer func() {
if closer, ok := logWriter.(interface{ Close() error }); ok {
closer.Close()
}
}()
// Parse log level
var logLevel slog.Level
switch cfg.LogLevel {
case "debug":
logLevel = slog.LevelDebug
case "warn":
logLevel = slog.LevelWarn
case "error":
logLevel = slog.LevelError
default:
logLevel = slog.LevelInfo
}
// Primary handler: writes to log file (or stdout for --debugstdout/Docker)
fileHandler := slog.NewTextHandler(logWriter, &slog.HandlerOptions{
Level: logLevel,
})
var logger *slog.Logger
if cfg.DebugMode && !cfg.DebugStdout && !cfg.IsDockerEnvironment() {
// --debug mode: file gets full logs, stdout gets only warn/error
stdoutHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelWarn,
})
logger = slog.New(dualHandler{file: fileHandler, stdout: stdoutHandler})
} else {
logger = slog.New(fileHandler)
}
slog.SetDefault(logger)
logger.Info("Runtime startup",
"pid", os.Getpid(),
"port", cfg.Port,
"db_path", cfg.DBPath,
"debug", cfg.DebugMode,
"test_mode", cfg.TestMode,
)
// Warn if using default password
if cfg.IsDefaultPassword() {
logger.Warn("⚠️ USING DEFAULT PASSWORD - set ONWATCH_ADMIN_PASS in .env for production")
}
// Print startup banner (only in debug/foreground mode)
if cfg.DebugMode {
printBanner(cfg, version)
}
// Ensure data directory exists and migrate DB if needed
if err := os.MkdirAll(filepath.Dir(cfg.DBPath), 0700); err != nil {
logger.Warn("Failed to create database directory", "error", err)
}
if !cfg.DBPathExplicit {
migrateDBLocation(cfg.DBPath, logger)
} else {
// Fix for misconfigured DB_PATH: if the user's .env has a relative path
// like ./onwatch.db or ./syntrack.db but the canonical data/ path has
// existing data, redirect to the canonical path to avoid empty dashboard.
fixExplicitDBPath(cfg, logger)
}
// Migrate Codex profiles from legacy ~/.onwatch/codex-profiles/ to data directory
migrateCodexProfiles()
// Open database
db, err := store.New(cfg.DBPath)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
defer db.Close()
logger.Info("Database opened", "path", cfg.DBPath)
// Initialize or load encryption salt for HKDF key derivation
if err := initEncryptionSalt(db, logger); err != nil {
logger.Warn("Failed to initialize encryption salt", "error", err)
}
// Password precedence: DB-stored hash takes priority over .env
dbHash, hashErr := db.GetUser(cfg.AdminUser)
if hashErr == nil && dbHash != "" {
// DB has stored password - use it
cfg.AdminPassHash = dbHash
logger.Info("Using database-stored password for auth")
} else {
// No DB password - hash the .env password and store it
cfg.AdminPassHash = sha256hex(cfg.AdminPass)
if storeErr := db.UpsertUser(cfg.AdminUser, cfg.AdminPassHash); storeErr != nil {
logger.Warn("Failed to store initial password hash", "error", storeErr)
}
logger.Info("Stored initial password hash in database")
}
// Close any orphaned sessions from previous runs (e.g., process was killed)
if closed, err := db.CloseOrphanedSessions(); err != nil {
logger.Warn("Failed to close orphaned sessions", "error", err)
} else if closed > 0 {
logger.Info("Closed orphaned sessions", "count", closed)
}
// Migrate existing sessions to usage-based detection (runs once)
if err := db.MigrateSessionsToUsageBased(cfg.SessionIdleTimeout); err != nil {
logger.Error("Session migration failed", "error", err)
}
// Run cycle migration to fix historical cycles with incorrect durations (runs once)
if results, err := db.RunCycleMigrationIfNeeded(logger); err != nil {
logger.Error("Cycle migration failed", "error", err)
} else if len(results) > 0 {
for _, r := range results {
logger.Info("Cycle migration result",
"provider", r.Provider,
"quotaType", r.QuotaType,
"cyclesFixed", r.CyclesFixed,
"cyclesCreated", r.CyclesCreated,
"snapshotsUsed", r.SnapshotsUsed,
)
}
}
if cfg.AnthropicAutoToken {
logger.Info("Auto-detected Anthropic token from Claude Code credentials")
}
if cfg.CodexAutoToken {
logger.Info("Auto-detected Codex token from Codex credentials")
}
// Apply provider_settings from DB (UI-configured keys/regions override .env)
if db != nil {
web.ApplyProviderSettingsFromDB(db, cfg, logger)
}
// Create API clients based on configured providers
var syntheticClient *api.Client
var zaiClient *api.ZaiClient
if cfg.HasProvider("synthetic") {
syntheticClient = api.NewClient(cfg.SyntheticAPIKey, logger)
logger.Info("Synthetic API client configured")
}
if cfg.HasProvider("zai") {
zaiBaseURL := cfg.ZaiBaseURL + "/monitor/usage/quota/limit"
zaiClient = api.NewZaiClient(cfg.ZaiAPIKey, logger, api.WithZaiBaseURL(zaiBaseURL))
logger.Info("Z.ai API client configured", "base_url", cfg.ZaiBaseURL, "region", cfg.ZaiRegion)
}
var anthropicClient *api.AnthropicClient
if cfg.HasProvider("anthropic") {
anthropicClient = api.NewAnthropicClient(cfg.AnthropicToken, logger)
logger.Info("Anthropic API client configured")
}
var copilotClient *api.CopilotClient
if cfg.HasProvider("copilot") {
copilotClient = api.NewCopilotClient(cfg.CopilotToken, logger)
logger.Info("Copilot API client configured")
}
var codexClient *api.CodexClient
if cfg.CodexToken != "" {
codexCreds := api.DetectCodexCredentials(logger)
codexClient = api.NewCodexClient(cfg.CodexToken, logger)
if codexCreds != nil && codexCreds.AccountID != "" {
codexClient.SetAccountID(codexCreds.AccountID)
}
logger.Info("Codex API client configured")
}
var antigravityClient *api.AntigravityClient
if cfg.HasProvider("antigravity") {
if cfg.AntigravityBaseURL != "" {
// Manual configuration (Docker mode)
conn := &api.AntigravityConnection{
BaseURL: cfg.AntigravityBaseURL,
CSRFToken: cfg.AntigravityCSRFToken,
Protocol: "https",
}
antigravityClient = api.NewAntigravityClient(logger, api.WithAntigravityConnection(conn))
logger.Info("Antigravity API client configured (manual)", "baseURL", cfg.AntigravityBaseURL)
} else {
// Auto-detection mode
antigravityClient = api.NewAntigravityClient(logger)
logger.Info("Antigravity API client configured (auto-detect)")
}
}
// Note: MiniMax clients are now created per-account by MiniMaxAgentManager.
// The legacy MINIMAX_API_KEY is seeded into the default provider account at startup.
var openrouterClient *api.OpenRouterClient
if cfg.HasProvider("openrouter") {
openrouterClient = api.NewOpenRouterClient(cfg.OpenRouterAPIKey, logger)
logger.Info("OpenRouter API client configured")
}
// Gemini provider - env vars or auto-detect from ~/.gemini/oauth_creds.json
var geminiClient *api.GeminiClient
var geminiCreds *api.GeminiCredentials
if os.Getenv("GEMINI_ENABLED") != "false" {
geminiCreds = api.DetectGeminiCredentials(logger, db)
if geminiCreds != nil {
cfg.GeminiEnabled = true
cfg.GeminiAutoToken = true
token := geminiCreds.AccessToken
// If only refresh token available (no access token), agent will refresh on first poll
if token == "" && geminiCreds.RefreshToken != "" {
token = "pending-refresh"
}
if token != "" {
geminiClient = api.NewGeminiClient(token, logger)
source := "auto-detected"
if os.Getenv("GEMINI_REFRESH_TOKEN") != "" || os.Getenv("GEMINI_ACCESS_TOKEN") != "" {
source = "environment variables"
}
logger.Info("Gemini API client configured", "source", source)
}
}
}
// Create components
tr := tracker.New(db, logger)
// Create agents with usage-based session managers
idleTimeout := cfg.SessionIdleTimeout
var ag *agent.Agent
if syntheticClient != nil {
sm := agent.NewSessionManager(db, "synthetic", idleTimeout, logger)
ag = agent.New(syntheticClient, db, tr, cfg.PollInterval, logger, sm)
}
// Create Z.ai tracker
var zaiTr *tracker.ZaiTracker
if cfg.HasProvider("zai") {
zaiTr = tracker.NewZaiTracker(db, logger)
}
var zaiAg *agent.ZaiAgent
if zaiClient != nil {
zaiSm := agent.NewSessionManager(db, "zai", idleTimeout, logger)
zaiAg = agent.NewZaiAgent(zaiClient, db, zaiTr, cfg.PollInterval, logger, zaiSm)
}
// Create Anthropic tracker
var anthropicTr *tracker.AnthropicTracker
if cfg.HasProvider("anthropic") {
anthropicTr = tracker.NewAnthropicTracker(db, logger)
}
var anthropicAg *agent.AnthropicAgent
if anthropicClient != nil {
// Load provider settings from DB (overrides .env)
if db != nil {
if provJSON, _ := db.GetSetting("provider_settings"); provJSON != "" {
var provSettings map[string]map[string]interface{}
if json.Unmarshal([]byte(provJSON), &provSettings) == nil {
if anthSettings, ok := provSettings["anthropic"]; ok {
if src, ok := anthSettings["source"].(string); ok && src != "" {
cfg.AnthropicSource = src
}
}
}
}
}
// ANTHROPIC_SOURCE controls how onWatch gets Anthropic usage data:
// "auto" - statusline when fresh, API polling as fallback (default)
// "statusline" - statusline only, no API polling
// "api" - API polling only, no statusline
anthropicSource := cfg.AnthropicSource
logger.Info("Anthropic data source configured", "source", anthropicSource)
// Set up statusline bridge for "auto" and "statusline" modes
if anthropicSource == "auto" || anthropicSource == "statusline" {
agent.SetupStatuslineBridge(logger)
}
anthropicSm := agent.NewSessionManager(db, "anthropic", idleTimeout, logger)
anthropicAg = agent.NewAnthropicAgent(anthropicClient, db, anthropicTr, cfg.PollInterval, logger, anthropicSm)
// Enable API polling for "auto" and "api" modes
if anthropicSource == "auto" || anthropicSource == "api" {
anthropicAg.SetTokenRefresh(func() string {
return api.DetectAnthropicToken(logger)
})
anthropicAg.SetCredentialsRefresh(func() *api.AnthropicCredentials {
return api.DetectAnthropicCredentials(logger)
})
}
// Enable statusline bridge for "auto" and "statusline" modes
if anthropicSource == "auto" || anthropicSource == "statusline" {
anthropicAg.EnableStatuslineBridge()
// In "statusline" mode, disable hybrid API polling since no API
// credentials are configured. Hybrid only works in "auto" mode.
if anthropicSource == "statusline" {
anthropicAg.SetAPIPollCycleInterval(0)
}
// Apply DB-configured cycle interval (overrides default 10)
if db != nil {
if provJSON, _ := db.GetSetting("provider_settings"); provJSON != "" {
var provSettings map[string]map[string]interface{}
if json.Unmarshal([]byte(provJSON), &provSettings) == nil {
if anthSettings, ok := provSettings["anthropic"]; ok {
if interval, ok := anthSettings["api_poll_cycle_interval"].(float64); ok && int(interval) > 0 {
anthropicAg.SetAPIPollCycleInterval(int(interval))
}
if sm, ok := anthSettings["staleness_minutes"].(float64); ok && sm > 0 {
anthropicAg.SetStatuslineStaleness(time.Duration(sm) * time.Minute)
}
if cc, ok := anthSettings["cc_detection"].(string); ok {
anthropicAg.SetCCDetectionEnabled(cc != "off")
}
}
}
}
}
}
}
// Create Copilot tracker
var copilotTr *tracker.CopilotTracker
if cfg.HasProvider("copilot") {
copilotTr = tracker.NewCopilotTracker(db, logger)
}
var copilotAg *agent.CopilotAgent
if copilotClient != nil {
copilotSm := agent.NewSessionManager(db, "copilot", idleTimeout, logger)
copilotAg = agent.NewCopilotAgent(copilotClient, db, copilotTr, cfg.PollInterval, logger, copilotSm)
}
// Create Codex tracker
var codexTr *tracker.CodexTracker
if cfg.HasProvider("codex") {
codexTr = tracker.NewCodexTracker(db, logger)
}
// Create Codex agent manager for multi-account support
var codexMgr *agent.CodexAgentManager
if cfg.HasProvider("codex") {
codexMgr = agent.NewCodexAgentManager(db, codexTr, cfg.PollInterval, logger)
codexMgr.SetProfilesDir(codexProfilesDirWithDataDir(filepath.Dir(cfg.DBPath)))
// Override profiles dir from DB if configured via UI
if db != nil {
if provJSON, _ := db.GetSetting("provider_settings"); provJSON != "" {
var provSettings map[string]map[string]interface{}
if json.Unmarshal([]byte(provJSON), &provSettings) == nil {
if s := provSettings["codex"]; s != nil {
if dir, _ := s["profiles_dir"].(string); dir != "" {
codexMgr.SetProfilesDir(dir)
logger.Info("Codex profiles directory overridden from UI", "dir", dir)
}
}
}
}
}
}
// Create Antigravity tracker
var antigravityTr *tracker.AntigravityTracker
if cfg.HasProvider("antigravity") {
antigravityTr = tracker.NewAntigravityTracker(db, logger)
}
var minimaxTr *tracker.MiniMaxTracker
if cfg.HasProvider("minimax") {
minimaxTr = tracker.NewMiniMaxTracker(db, logger)
}
var openrouterTr *tracker.OpenRouterTracker
if cfg.HasProvider("openrouter") {
openrouterTr = tracker.NewOpenRouterTracker(db, logger)
}
var geminiTr *tracker.GeminiTracker
if cfg.HasProvider("gemini") {
geminiTr = tracker.NewGeminiTracker(db, logger)
}
var antigravityAg *agent.AntigravityAgent
if antigravityClient != nil {
antigravitySm := agent.NewSessionManager(db, "antigravity", idleTimeout, logger)
antigravityAg = agent.NewAntigravityAgent(antigravityClient, db, antigravityTr, cfg.PollInterval, logger, antigravitySm)
}
// Create MiniMax agent manager for multi-account support.
// If a legacy MINIMAX_API_KEY is configured, seed the default account metadata.
var minimaxMgr *agent.MiniMaxAgentManager
if cfg.HasProvider("minimax") || minimaxTr != nil {
minimaxMgr = agent.NewMiniMaxAgentManager(db, minimaxTr, cfg.PollInterval, logger)
minimaxMgr.SetRegion(cfg.MiniMaxRegion)
// Seed the default account with the legacy API key if it has no metadata yet
if cfg.MiniMaxAPIKey != "" {
if accounts, err := db.QueryActiveProviderAccounts("minimax"); err == nil {
for _, acc := range accounts {
if acc.Name == "default" && (acc.Metadata == "" || acc.Metadata == "{}") {
meta := fmt.Sprintf(`{"api_key":%q,"region":%q}`, cfg.MiniMaxAPIKey, cfg.MiniMaxRegion)
db.UpdateProviderAccountMetadata(acc.ID, meta)
logger.Info("Seeded default MiniMax account with legacy API key", "id", acc.ID)
break
}
}
}
}
}
var openrouterAg *agent.OpenRouterAgent
if openrouterClient != nil {
openrouterSm := agent.NewSessionManager(db, "openrouter", idleTimeout, logger)
openrouterAg = agent.NewOpenRouterAgent(openrouterClient, db, openrouterTr, cfg.PollInterval, logger, openrouterSm)