forked from kenn-io/agentsview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
2404 lines (2260 loc) · 72.1 KB
/
Copy pathconfig.go
File metadata and controls
2404 lines (2260 loc) · 72.1 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 config
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"log"
"maps"
"net"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
"github.com/gofrs/flock"
"github.com/spf13/pflag"
"go.kenn.io/agentsview/internal/parser"
)
// TerminalConfig holds terminal launch preferences.
type TerminalConfig struct {
// Mode: "auto" (detect terminal), "custom" (use CustomBin),
// or "clipboard" (never launch, always copy).
Mode string `json:"mode" toml:"mode"`
// CustomBin is the terminal binary path (used when Mode == "custom").
CustomBin string `json:"custom_bin,omitempty" toml:"custom_bin"`
// CustomArgs is a template for terminal args. Use {cmd} as
// placeholder for the resume command (e.g. "-- bash -c {cmd}").
CustomArgs string `json:"custom_args,omitempty" toml:"custom_args"`
}
// ProxyConfig controls an optional managed reverse proxy.
type ProxyConfig struct {
// Mode enables a managed proxy implementation.
// Currently supported: "caddy".
Mode string `json:"mode,omitempty" toml:"mode"`
// Bin overrides the proxy executable path.
Bin string `json:"bin,omitempty" toml:"bin"`
// BindHost is the local interface/IP the proxy binds to.
BindHost string `json:"bind_host,omitempty" toml:"bind_host"`
// PublicPort is the external port exposed by the proxy.
PublicPort int `json:"public_port,omitempty" toml:"public_port"`
// TLSCert and TLSKey are used by managed HTTPS mode.
TLSCert string `json:"tls_cert,omitempty" toml:"tls_cert"`
TLSKey string `json:"tls_key,omitempty" toml:"tls_key"`
// AllowedSubnets restrict inbound clients to these CIDRs.
AllowedSubnets []string `json:"allowed_subnets,omitempty" toml:"allowed_subnets"`
}
// PGConfig holds PostgreSQL connection settings.
type PGConfig struct {
URL string `toml:"url" json:"url"`
Schema string `toml:"schema" json:"schema"`
MachineName string `toml:"machine_name" json:"machine_name"`
AllowInsecure bool `toml:"allow_insecure" json:"allow_insecure"`
Projects []string `toml:"projects" json:"projects,omitempty"`
ExcludeProjects []string `toml:"exclude_projects" json:"exclude_projects,omitempty"`
}
type pgEnvOverrides struct {
URL string
Schema string
MachineName string
}
// ResolvedPGTarget is one PostgreSQL target after target selection,
// defaulting, and default-target env overrides are applied.
type ResolvedPGTarget struct {
Name string
Config PGConfig
IsDefault bool
}
var pgConfigKeys = map[string]struct{}{
"url": {},
"schema": {},
"machine_name": {},
"allow_insecure": {},
"projects": {},
"exclude_projects": {},
}
// DuckDBConfig holds DuckDB mirror and Quack connection settings.
type DuckDBConfig struct {
Path string `toml:"path" json:"path"`
URL string `toml:"url" json:"url"`
Token string `toml:"token" json:"token,omitempty"`
MachineName string `toml:"machine_name" json:"machine_name"`
AllowInsecure bool `toml:"allow_insecure" json:"allow_insecure"`
Projects []string `toml:"projects" json:"projects,omitempty"`
ExcludeProjects []string `toml:"exclude_projects" json:"exclude_projects,omitempty"`
}
// VectorConfig holds settings for the optional local semantic-search
// vector index (embeddings + vectors.db).
type VectorConfig struct {
Enabled bool `toml:"enabled" json:"enabled"`
DBPath string `toml:"db_path" json:"db_path,omitempty"`
// IncludeAutomated controls whether automated (e.g. roborev) sessions'
// messages are embedded into the vector index, mirroring the
// IncludeAutomated convention search already uses to exclude those
// sessions from results by default. Default false: automated sessions
// are excluded from embedding, since they otherwise dominate a large
// archive's index with content that search already hides by default.
// `embeddings build --include-automated` can override this for a
// one-off build; see that flag's help for the scheduled-build caveat.
IncludeAutomated bool `toml:"include_automated" json:"include_automated"`
Embeddings VectorEmbeddingsConfig `toml:"embeddings" json:"embeddings"`
Embed VectorEmbedConfig `toml:"embed" json:"embed"`
}
// VectorEmbeddingsConfig describes the embedding space — the model identity
// every server must share — and the named servers that can encode it.
//
// Model identity (model, dimension, max_input_chars, input_suffix) is
// deliberately global rather than per-server: it joins the generation
// fingerprint, and query vectors are only comparable to stored document
// vectors from the same space. Servers differ only in transport and
// capacity, so a build run on any server produces vectors every other
// server's queries can search.
type VectorEmbeddingsConfig struct {
Model string `toml:"model" json:"model"`
Dimension int `toml:"dimension" json:"dimension"`
// MaxInputChars caps the rune length of each chunk sent for
// embedding. Default 8192.
MaxInputChars int `toml:"max_input_chars" json:"max_input_chars"`
// InputSuffix is appended verbatim to every text sent for embedding
// (documents and queries alike). Some models expect a terminator the
// serving layer does not add — e.g. Qwen3-Embedding under llama.cpp
// wants "<|endoftext|>" appended client-side. Changing it cuts a new
// vector generation. Default empty.
InputSuffix string `toml:"input_suffix" json:"input_suffix,omitempty"`
// DefaultServer names the server used for search-time query encoding
// and for builds that don't select one (scheduled builds, and
// `embeddings build` without --using). Optional when exactly one
// server is defined.
DefaultServer string `toml:"default_server" json:"default_server,omitempty"`
// Servers is the set of named OpenAI-compatible endpoints that serve
// Model, keyed by the name `embeddings build --using <name>` selects.
Servers map[string]VectorEmbeddingsServerConfig `toml:"servers" json:"servers"`
}
// VectorEmbeddingsServerConfig is one named embeddings server: transport
// and capacity settings only; the model identity lives on
// VectorEmbeddingsConfig.
type VectorEmbeddingsServerConfig struct {
Endpoint string `toml:"endpoint" json:"endpoint"`
// APIKeyEnv names the environment variable holding the API key.
// Empty means anonymous access.
APIKeyEnv string `toml:"api_key_env" json:"api_key_env,omitempty"`
// BatchSize is the number of inputs sent per HTTP call. Default 32.
BatchSize int `toml:"batch_size" json:"batch_size"`
// Concurrency is the number of documents embedded in parallel during a
// build against this server. Sequential requests leave a build
// round-trip-bound against remote endpoints, so the default is 4;
// servers that process one request at a time simply queue the extras.
Concurrency int `toml:"concurrency" json:"concurrency"`
// Timeout is a parseable duration string applied to each HTTP
// call. Default "30s".
Timeout string `toml:"timeout" json:"timeout"`
// MaxRetries is the maximum total attempts on 429/5xx/network errors
// (4xx fails fast); 0 means one attempt. Default 3.
MaxRetries int `toml:"max_retries" json:"max_retries"`
}
// ResolvedDefaultServer returns the server name used when no explicit
// choice is made: default_server when set, otherwise the only defined
// server, otherwise "".
func (c VectorEmbeddingsConfig) ResolvedDefaultServer() string {
if c.DefaultServer != "" {
return c.DefaultServer
}
if len(c.Servers) == 1 {
for name := range c.Servers {
return name
}
}
return ""
}
// Server resolves name to a defined embeddings server; "" means the
// default. The resolved name is returned alongside the server so callers
// can report which server a build actually used.
func (c VectorEmbeddingsConfig) Server(name string) (string, VectorEmbeddingsServerConfig, error) {
if name == "" {
name = c.ResolvedDefaultServer()
}
s, ok := c.Servers[name]
if !ok {
return "", VectorEmbeddingsServerConfig{}, fmt.Errorf(
"[vector.embeddings] no server named %q; define it under [vector.embeddings.servers.%s] (have: %s)",
name, name, strings.Join(sortedServerNames(c.Servers), ", "))
}
return name, s, nil
}
// normalizedEmbeddingsServers fills each named server's unset transport
// fields with their defaults (batch_size 32, concurrency 4, timeout "30s",
// max_retries 3). meta.IsDefined distinguishes "unset" (apply the default)
// from an explicit zero — an explicit max_retries = 0 disables retries, and
// an explicit zero batch_size/concurrency stays zero so validation rejects
// it instead of silently substituting the default.
func normalizedEmbeddingsServers(
servers map[string]VectorEmbeddingsServerConfig, meta toml.MetaData,
) map[string]VectorEmbeddingsServerConfig {
out := make(map[string]VectorEmbeddingsServerConfig, len(servers))
for name, s := range servers {
if !meta.IsDefined("vector", "embeddings", "servers", name, "batch_size") {
s.BatchSize = 32
}
if !meta.IsDefined("vector", "embeddings", "servers", name, "concurrency") {
s.Concurrency = 4
}
if s.Timeout == "" {
s.Timeout = "30s"
}
if !meta.IsDefined("vector", "embeddings", "servers", name, "max_retries") {
s.MaxRetries = 3
}
out[name] = s
}
return out
}
// sortedServerNames returns the configured server names in sorted order,
// for deterministic error messages and validation.
func sortedServerNames(servers map[string]VectorEmbeddingsServerConfig) []string {
names := make([]string, 0, len(servers))
for name := range servers {
names = append(names, name)
}
sort.Strings(names)
return names
}
// VectorEmbedConfig configures when the daemon runs embedding work.
type VectorEmbedConfig struct {
// RunAfterSync enables debounced embedding of sync deltas.
// Defaults to true when unset; read it via RunAfterSyncEnabled.
RunAfterSync *bool `toml:"run_after_sync" json:"run_after_sync,omitempty"`
// BackstopInterval is a parseable duration string for a periodic
// full rescan. Default "24h"; a negative duration disables it.
BackstopInterval string `toml:"backstop_interval" json:"backstop_interval"`
}
// Validate checks the vector config for internal consistency. It is a
// no-op when the section is disabled.
func (c VectorConfig) Validate() error {
if !c.Enabled {
return nil
}
if c.Embeddings.Model == "" {
return fmt.Errorf("[vector.embeddings] model is required when [vector] is enabled")
}
if c.Embeddings.Dimension <= 0 {
return fmt.Errorf("[vector.embeddings] dimension must be greater than 0 when [vector] is enabled")
}
if c.Embeddings.MaxInputChars <= 0 {
return fmt.Errorf(
"[vector.embeddings] max_input_chars must be greater than 0, got %d",
c.Embeddings.MaxInputChars)
}
if err := c.Embeddings.validateServers(); err != nil {
return err
}
backstop, err := time.ParseDuration(c.Embed.BackstopInterval)
if err != nil {
return fmt.Errorf("[vector.embed] invalid backstop_interval %q: %w", c.Embed.BackstopInterval, err)
}
if backstop == 0 {
return fmt.Errorf(
"[vector.embed] backstop_interval must not be zero; " +
"use a negative value to disable or omit for the 24h default")
}
return nil
}
// ResolvedDBPath returns DBPath if set, else <dataDir>/vectors.db.
func (c VectorConfig) ResolvedDBPath(dataDir string) string {
if c.DBPath != "" {
return c.DBPath
}
return filepath.Join(dataDir, "vectors.db")
}
// APIKey reads the API key from the environment variable named by
// APIKeyEnv. Returns "" when APIKeyEnv is unset.
func (c VectorEmbeddingsServerConfig) APIKey() string {
if c.APIKeyEnv == "" {
return ""
}
return os.Getenv(c.APIKeyEnv)
}
// validateServers checks the named-servers section: at least one server, an
// unambiguous default, and per-server transport settings that parse.
func (c VectorEmbeddingsConfig) validateServers() error {
if len(c.Servers) == 0 {
return fmt.Errorf(
"[vector.embeddings] at least one server is required when [vector] is enabled; " +
"define one under [vector.embeddings.servers.<name>]")
}
if c.DefaultServer == "" && len(c.Servers) > 1 {
return fmt.Errorf(
"[vector.embeddings] default_server is required when more than one server is defined (have: %s)",
strings.Join(sortedServerNames(c.Servers), ", "))
}
if c.DefaultServer != "" {
if _, ok := c.Servers[c.DefaultServer]; !ok {
return fmt.Errorf(
"[vector.embeddings] default_server %q is not a defined server (have: %s)",
c.DefaultServer, strings.Join(sortedServerNames(c.Servers), ", "))
}
}
for _, name := range sortedServerNames(c.Servers) {
if err := c.Servers[name].validate(name); err != nil {
return err
}
}
return nil
}
// validate checks one named server's transport settings.
func (c VectorEmbeddingsServerConfig) validate(name string) error {
section := fmt.Sprintf("[vector.embeddings.servers.%s]", name)
if c.Endpoint == "" {
return fmt.Errorf("%s endpoint is required", section)
}
if c.BatchSize <= 0 {
return fmt.Errorf("%s batch_size must be greater than 0, got %d", section, c.BatchSize)
}
if c.Concurrency <= 0 {
return fmt.Errorf("%s concurrency must be greater than 0, got %d", section, c.Concurrency)
}
if c.MaxRetries < 0 {
return fmt.Errorf("%s max_retries must be >= 0, got %d", section, c.MaxRetries)
}
timeout, err := time.ParseDuration(c.Timeout)
if err != nil {
return fmt.Errorf("%s invalid timeout %q: %w", section, c.Timeout, err)
}
if timeout <= 0 {
return fmt.Errorf("%s timeout must be greater than 0, got %q", section, c.Timeout)
}
return nil
}
// RunAfterSyncEnabled reports whether embedding should run after sync,
// defaulting to true when RunAfterSync is unset.
func (c VectorEmbedConfig) RunAfterSyncEnabled() bool {
if c.RunAfterSync == nil {
return true
}
return *c.RunAfterSync
}
// AutomatedConfig holds user-supplied additions to the
// automated-session classifier. Parse-only; all semantic
// normalization (trim, dedupe, length cap, built-in overlap
// drop) happens inside the db setters.
type AutomatedConfig struct {
Prefixes []string `toml:"prefixes" json:"prefixes,omitempty"`
Substrings []string `toml:"substrings" json:"substrings,omitempty"`
ExactMatches []string `toml:"exact_matches" json:"exact_matches,omitempty"`
}
// AgentConfig holds per-agent runtime overrides.
type AgentConfig struct {
Binary string `json:"binary,omitempty" toml:"binary"`
Sandbox string `json:"sandbox,omitempty" toml:"sandbox"`
AllowUnsafe bool `json:"allow_unsafe,omitempty" toml:"allow_unsafe"`
}
type CustomModelRate struct {
Input float64 `json:"input" toml:"input"`
Output float64 `json:"output" toml:"output"`
CacheCreation float64 `json:"cache_creation,omitempty" toml:"cache_creation"`
CacheRead float64 `json:"cache_read,omitempty" toml:"cache_read"`
}
type RemoteTransport string
const (
RemoteTransportSSH RemoteTransport = "ssh"
RemoteTransportHTTP RemoteTransport = "http"
)
// RemoteHost describes one target for config-driven `agentsview sync`
// fan-out. Host is required. SSH remotes may set User and Port
// (Port 0 means the ssh default of 22). HTTP remotes must set URL
// and Token. A zero/empty Interval disables periodic remote
// sync for this host.
type RemoteHost struct {
Host string `toml:"host" json:"host"`
Transport RemoteTransport `toml:"transport,omitempty" json:"transport,omitempty"`
User string `toml:"user,omitempty" json:"user,omitempty"`
Port int `toml:"port,omitempty" json:"port,omitempty"`
URL string `toml:"url,omitempty" json:"url,omitempty"`
Token string `toml:"token,omitempty" json:"-"`
Interval time.Duration `toml:"interval,omitempty" json:"interval,omitempty"`
}
// Config holds all application configuration.
type Config struct {
Host string `json:"host" toml:"host"`
Port int `json:"port" toml:"port"`
DataDir string `json:"data_dir" toml:"data_dir"`
DBPath string `json:"-" toml:"-"`
PublicURL string `json:"public_url,omitempty" toml:"public_url"`
PublicOrigins []string `json:"public_origins,omitempty" toml:"public_origins"`
Proxy ProxyConfig `json:"proxy,omitempty" toml:"proxy"`
WatchExcludePatterns []string `json:"watch_exclude_patterns,omitempty" toml:"watch_exclude_patterns"`
CursorSecret string `json:"cursor_secret" toml:"cursor_secret"`
CursorAdminAPIKey string `json:"cursor_admin_api_key,omitempty" toml:"cursor_admin_api_key"`
CursorAdminEmail string `json:"cursor_admin_email,omitempty" toml:"cursor_admin_email"`
CursorAdminUserID string `json:"cursor_admin_user_id,omitempty" toml:"cursor_admin_user_id"`
GithubToken string `json:"github_token,omitempty" toml:"github_token"`
Terminal TerminalConfig `json:"terminal,omitempty" toml:"terminal"`
AuthToken string `json:"auth_token,omitempty" toml:"auth_token"`
RequireAuth bool `json:"require_auth" toml:"require_auth"`
NoBrowser bool `json:"no_browser" toml:"no_browser"`
DisableUpdateCheck bool `json:"disable_update_check" toml:"disable_update_check"`
NoSync bool `json:"-" toml:"-"`
PG PGConfig `json:"pg,omitempty" toml:"pg"`
DefaultPG string `json:"default_pg,omitempty" toml:"default_pg"`
PGTargets map[string]PGConfig `json:"-" toml:"-"`
DuckDB DuckDBConfig `json:"duckdb,omitempty" toml:"duckdb"`
Vector VectorConfig `json:"vector,omitempty" toml:"vector"`
Automated AutomatedConfig `json:"automated,omitempty" toml:"automated"`
Agent map[string]AgentConfig `json:"agent,omitempty" toml:"agent"`
WriteTimeout time.Duration `json:"-" toml:"-"`
// AgentDirs maps each AgentType to its configured
// directories. Single-dir agents store a one-element
// slice; unconfigured agents use nil.
AgentDirs map[parser.AgentType][]string `json:"-" toml:"-"`
// agentDirSource tracks how each agent's dirs were
// set so loadFile doesn't override env-set values.
agentDirSource map[parser.AgentType]dirSource
ResultContentBlockedCategories []string `json:"result_content_blocked_categories,omitempty" toml:"result_content_blocked_categories"`
// SyncIncludeCwdPrefixes, when non-empty, restricts local session
// ingestion to sessions whose working directory equals one of the
// prefixes or lives underneath one. Sessions without a recorded
// cwd are skipped while the filter is active. Config-file only;
// remote sync is unaffected because the prefixes describe local
// paths.
SyncIncludeCwdPrefixes []string `json:"-" toml:"sync_include_cwd_prefixes"`
// EventsCoalesceInterval is the minimum wall-clock time between
// SSE data_changed broadcasts to connected clients. Emits that
// arrive within this window after a prior broadcast are coalesced
// into a single trailing broadcast, bounding dashboard refetch
// work during bursts of sync activity. Zero disables coalescing.
EventsCoalesceInterval time.Duration `json:"events_coalesce_interval,omitempty" toml:"events_coalesce_interval"`
DaemonIdleTimeout time.Duration `json:"daemon_idle_timeout,omitempty" toml:"daemon_idle_timeout"`
CustomModelPricing map[string]CustomModelRate `json:"custom_model_pricing,omitempty" toml:"custom_model_pricing"`
// RemoteHosts is the config-file list of remote targets that
// `agentsview sync` (with no --host) syncs after the local
// pass. CLI/config-file only; never serialized to the
// settings API, so there is no web-UI editing of this list.
RemoteHosts []RemoteHost `json:"-" toml:"-"`
// HostExplicit is true when the user passed --host on the CLI.
// Used to prevent auto-bind to 0.0.0.0 when the user
// explicitly requested a specific host.
HostExplicit bool `json:"-" toml:"-"`
pgEnvOverrides pgEnvOverrides
}
type dirSource int
const (
dirDefault dirSource = iota
dirFile
dirEnv
)
// ResolveDirs returns the effective directories for an agent.
func (c *Config) ResolveDirs(
agent parser.AgentType,
) []string {
return c.AgentDirs[agent]
}
// IsUserConfigured reports whether the agent's directories
// were explicitly set by the user (via env var or config file)
// rather than populated from defaults.
func (c *Config) IsUserConfigured(
agent parser.AgentType,
) bool {
return c.agentDirSource[agent] != dirDefault
}
// ValidateRemoteHosts checks the configured remote_hosts entries
// for semantic errors. It checks the trimmed values that loadFile
// already normalized, so what is validated here is exactly what is
// passed to remote sync. Returns an aggregated error naming every
// offending entry, or nil when all entries are valid.
func (c Config) ValidateRemoteHosts() error {
var problems []string
seen := make(map[string]int, len(c.RemoteHosts))
for i, h := range c.RemoteHosts {
transport := h.Transport
if transport == "" {
transport = RemoteTransportSSH
}
if h.Host == "" {
problems = append(problems,
fmt.Sprintf("entry %d: host is required", i+1))
}
if trimmed := strings.TrimSpace(h.Host); isSSHOptionShaped(h.Host) {
problems = append(problems,
fmt.Sprintf("entry %d: host must not begin with '-' (got %q)",
i+1, trimmed))
}
if trimmed := strings.TrimSpace(h.User); isSSHOptionShaped(h.User) {
problems = append(problems,
fmt.Sprintf("entry %d (%q): user must not begin with '-' (got %q)",
i+1, h.Host, trimmed))
}
if h.Port < 0 || h.Port > 65535 {
problems = append(problems,
fmt.Sprintf("entry %d (%q): invalid port %d",
i+1, h.Host, h.Port))
}
if h.Interval < 0 {
problems = append(problems,
fmt.Sprintf("entry %d (%q): invalid interval %s",
i+1, h.Host, h.Interval))
}
switch transport {
case RemoteTransportSSH:
if h.URL != "" {
problems = append(problems,
fmt.Sprintf("entry %d (%q): url is only valid for http",
i+1, h.Host))
}
if h.Token != "" {
problems = append(problems,
fmt.Sprintf("entry %d (%q): token is only valid for http",
i+1, h.Host))
}
case RemoteTransportHTTP:
if h.User != "" {
problems = append(problems,
fmt.Sprintf("entry %d (%q): user is only valid for ssh",
i+1, h.Host))
}
if h.Port != 0 {
problems = append(problems,
fmt.Sprintf("entry %d (%q): port is only valid for ssh",
i+1, h.Host))
}
if err := validateRemoteHTTPURL(h.URL); err != nil {
problems = append(problems,
fmt.Sprintf("entry %d (%q): %v",
i+1, h.Host, err))
}
if h.Token == "" {
problems = append(problems,
fmt.Sprintf("entry %d (%q): token is required for http",
i+1, h.Host))
}
default:
problems = append(problems,
fmt.Sprintf("entry %d (%q): invalid transport %q",
i+1, h.Host, h.Transport))
}
// Remote sync namespaces sessions and the skip cache by
// host alone (see ssh.RemoteSync), so two entries sharing a
// host collide regardless of user/port. Reject duplicates
// rather than silently share or overwrite cached state.
if h.Host != "" {
if first, ok := seen[h.Host]; ok {
problems = append(problems,
fmt.Sprintf("entry %d: duplicate host %q (already at entry %d)",
i+1, h.Host, first))
} else {
seen[h.Host] = i + 1
}
}
}
if len(problems) > 0 {
return fmt.Errorf("remote_hosts: %s",
strings.Join(problems, "; "))
}
return nil
}
func validateRemoteHTTPURL(raw string) error {
value := strings.TrimSpace(raw)
if value == "" {
return fmt.Errorf("url is required")
}
u, err := url.Parse(value)
if err != nil {
return fmt.Errorf("invalid url: %w", err)
}
scheme := strings.ToLower(u.Scheme)
if scheme != "http" && scheme != "https" {
return fmt.Errorf("url must use http or https")
}
if u.Hostname() == "" {
return fmt.Errorf("url must include a host")
}
if u.User != nil {
return fmt.Errorf("url must not include userinfo")
}
if u.RawQuery != "" || u.ForceQuery {
return fmt.Errorf("url must not include query")
}
if u.Fragment != "" || u.RawFragment != "" || strings.Contains(value, "#") {
return fmt.Errorf("url must not include fragment")
}
return nil
}
func isSSHOptionShaped(value string) bool {
return strings.HasPrefix(strings.TrimSpace(value), "-")
}
// Default returns a Config with default values.
func Default() (Config, error) {
home, err := os.UserHomeDir()
if err != nil {
return Config{}, fmt.Errorf(
"determining home directory: %w", err,
)
}
dataDir := filepath.Join(home, ".agentsview")
agentDirs := make(map[parser.AgentType][]string)
agentDirSource := make(map[parser.AgentType]dirSource)
for _, def := range parser.Registry {
dirs := make([]string, len(def.DefaultDirs))
root := ""
if def.DefaultRootEnvVar != "" {
root = os.Getenv(def.DefaultRootEnvVar)
}
for i, rel := range def.DefaultDirs {
if root != "" {
dirs[i] = reRootDefaultDir(root, rel)
continue
}
dirs[i] = filepath.Join(home, rel)
}
agentDirs[def.Type] = dirs
agentDirSource[def.Type] = dirDefault
}
return Config{
Host: "127.0.0.1",
Port: 8080,
DataDir: dataDir,
DBPath: filepath.Join(dataDir, "sessions.db"),
WriteTimeout: 30 * time.Second,
AgentDirs: agentDirs,
agentDirSource: agentDirSource,
WatchExcludePatterns: []string{".git", "node_modules", "__pycache__", ".venv", "venv", "vendor", ".next"},
ResultContentBlockedCategories: []string{"Read", "Glob"},
EventsCoalesceInterval: 10 * time.Second,
DaemonIdleTimeout: 20 * time.Minute,
Agent: map[string]AgentConfig{},
Vector: VectorConfig{
Embeddings: VectorEmbeddingsConfig{
MaxInputChars: 8192,
},
Embed: VectorEmbedConfig{
BackstopInterval: "24h",
},
},
}, nil
}
func reRootDefaultDir(root, rel string) string {
rel = filepath.Clean(rel)
if _, tail, ok := strings.Cut(rel, string(filepath.Separator)); ok && tail != "" {
return filepath.Join(root, tail)
}
return root
}
// Load builds a Config by layering: defaults < config file < env < flags.
// The provided FlagSet must already be parsed by the caller.
// Only flags that were explicitly set override the lower layers.
func Load(fs *flag.FlagSet) (Config, error) {
cfg, err := LoadMinimal()
if err != nil {
return cfg, err
}
applyFlags(&cfg, fs)
if err := finalize(&cfg); err != nil {
return cfg, err
}
return cfg, nil
}
// LoadPFlags builds a Config from a parsed Cobra/pflag FlagSet.
func LoadPFlags(fs *pflag.FlagSet) (Config, error) {
cfg, err := LoadMinimal()
if err != nil {
return cfg, err
}
applyPFlags(&cfg, fs)
if err := finalize(&cfg); err != nil {
return cfg, err
}
return cfg, nil
}
// LoadPGServe builds a Config for `pg serve` by preserving
// shared and PG settings from defaults/env/config file while
// resetting serve-specific network/browser settings to defaults.
// Only explicitly provided serve flags are applied on top.
func LoadPGServe(fs *flag.FlagSet) (Config, error) {
cfg, err := loadPGServeBase()
if err != nil {
return cfg, err
}
applyFlags(&cfg, fs)
if err := finalize(&cfg); err != nil {
return cfg, err
}
return cfg, nil
}
// LoadPGServePFlags builds a PG serve config from a parsed Cobra/pflag FlagSet.
func LoadPGServePFlags(fs *pflag.FlagSet) (Config, error) {
cfg, err := loadPGServeBase()
if err != nil {
return cfg, err
}
applyPFlags(&cfg, fs)
if err := finalize(&cfg); err != nil {
return cfg, err
}
return cfg, nil
}
// LoadDuckDBServePFlags builds a DuckDB serve config from a parsed Cobra/pflag
// FlagSet. It intentionally uses the same isolated serve defaults as pg serve.
func LoadDuckDBServePFlags(fs *pflag.FlagSet) (Config, error) {
cfg, err := loadPGServeBase()
if err != nil {
return cfg, err
}
applyPFlags(&cfg, fs)
if err := finalize(&cfg); err != nil {
return cfg, err
}
return cfg, nil
}
func loadPGServeBase() (Config, error) {
cfg, err := Default()
if err != nil {
return cfg, err
}
cfg.loadEnv()
if err := cfg.loadFile(); err != nil {
return cfg, fmt.Errorf("loading config file: %w", err)
}
if err := cfg.ensureCursorSecret(); err != nil {
return cfg, fmt.Errorf("ensuring cursor secret: %w", err)
}
cfg.DBPath = filepath.Join(cfg.DataDir, "sessions.db")
// pg serve intentionally ignores persisted normal serve/public/proxy
// settings so an existing SQLite-backed serve deployment cannot silently
// reconfigure the PG-backed server. Until a dedicated pg-serve config
// namespace exists, only explicit pg-serve flags should shape its
// network/proxy behavior.
cfg.Host = "127.0.0.1"
cfg.Port = 8080
cfg.PublicURL = ""
cfg.PublicOrigins = nil
cfg.Proxy = ProxyConfig{}
cfg.NoBrowser = false
cfg.HostExplicit = false
return cfg, nil
}
// LoadMinimal builds a Config from defaults, env, and config file,
// without parsing CLI flags. Use this for subcommands that manage
// their own flag sets.
func LoadMinimal() (Config, error) {
cfg, err := Default()
if err != nil {
return cfg, err
}
cfg.loadEnv()
if err := cfg.loadFile(); err != nil {
return cfg, fmt.Errorf("loading config file: %w", err)
}
if err := finalize(&cfg); err != nil {
return cfg, err
}
if err := cfg.ensureCursorSecret(); err != nil {
return cfg, fmt.Errorf("ensuring cursor secret: %w", err)
}
cfg.DBPath = filepath.Join(cfg.DataDir, "sessions.db")
return cfg, nil
}
// LoadReadOnly builds a Config from defaults, env, and config.toml without
// writing config migrations or generated secrets. Use it for diagnostic
// commands that must not mutate user state.
func LoadReadOnly() (Config, error) {
cfg, err := Default()
if err != nil {
return cfg, err
}
cfg.loadEnv()
if err := cfg.loadFileReadOnly(); err != nil {
return cfg, fmt.Errorf("loading config file: %w", err)
}
if err := finalize(&cfg); err != nil {
return cfg, err
}
cfg.DBPath = filepath.Join(cfg.DataDir, "sessions.db")
return cfg, nil
}
func (c *Config) configPath() string {
return filepath.Join(c.DataDir, "config.toml")
}
func (c *Config) jsonConfigPath() string {
return filepath.Join(c.DataDir, "config.json")
}
// migrateJSONToTOML converts config.json to config.toml if
// config.json exists and config.toml does not. The original
// JSON file is renamed to config.json.bak.
func (c *Config) migrateJSONToTOML() error {
return c.withConfigLock(func() error {
jsonPath := c.jsonConfigPath()
tomlPath := c.configPath()
if _, err := os.Stat(tomlPath); err == nil {
return nil // TOML already exists
}
data, err := os.ReadFile(jsonPath)
if os.IsNotExist(err) {
return nil // no JSON to migrate
}
if err != nil {
return fmt.Errorf("reading config.json for migration: %w", err)
}
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
return fmt.Errorf("parsing config.json for migration: %w", err)
}
var buf bytes.Buffer
if err := toml.NewEncoder(&buf).Encode(m); err != nil {
return fmt.Errorf("encoding config.toml: %w", err)
}
if err := os.WriteFile(tomlPath, buf.Bytes(), 0o600); err != nil {
return fmt.Errorf("writing config.toml: %w", err)
}
if err := os.Rename(jsonPath, jsonPath+".bak"); err != nil {
return fmt.Errorf("renaming config.json to .bak: %w", err)
}
return nil
})
}
func (c *Config) loadFile() error {
return c.loadFileWithMigration(true)
}
func (c *Config) loadFileReadOnly() error {
return c.loadFileWithMigration(false)
}
func (c *Config) loadFileWithMigration(migrate bool) error {
if migrate {
if err := c.migrateJSONToTOML(); err != nil {
return err
}
}
path := c.configPath()
if _, err := os.Stat(path); os.IsNotExist(err) {
if migrate {
return nil
}
return c.loadLegacyJSONReadOnly()
} else if err != nil {
return fmt.Errorf("checking config: %w", err)
}
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("reading config: %w", err)
}
return c.applyConfigTOML(string(data))
}
func (c *Config) loadLegacyJSONReadOnly() error {
data, err := os.ReadFile(c.jsonConfigPath())
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("reading config.json: %w", err)
}
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
return fmt.Errorf("parsing config.json: %w", err)
}
var buf bytes.Buffer
if err := toml.NewEncoder(&buf).Encode(m); err != nil {
return fmt.Errorf("encoding config.json: %w", err)
}
return c.applyConfigTOML(buf.String())
}
func (c *Config) applyConfigTOML(data string) error {
var file struct {
GithubToken string `toml:"github_token"`
CursorSecret string `toml:"cursor_secret"`
CursorAdminAPIKey string `toml:"cursor_admin_api_key"`
CursorAdminEmail string `toml:"cursor_admin_email"`
CursorAdminUserID string `toml:"cursor_admin_user_id"`
Host string `toml:"host"`
Port int `toml:"port"`
PublicURL string `toml:"public_url"`
PublicOrigins []string `toml:"public_origins"`
Proxy ProxyConfig `toml:"proxy"`
WatchExcludePatterns []string `toml:"watch_exclude_patterns"`
SyncIncludeCwdPrefixes []string `toml:"sync_include_cwd_prefixes"`
ResultContentBlockedCategories []string `toml:"result_content_blocked_categories"`
Terminal TerminalConfig `toml:"terminal"`
AuthToken string `toml:"auth_token"`
RequireAuth bool `toml:"require_auth"`
RemoteAccess bool `toml:"remote_access"`
DisableUpdateCheck bool `toml:"disable_update_check"`
DefaultPG string `toml:"default_pg"`
PG PGConfig `toml:"pg"`
DuckDB DuckDBConfig `toml:"duckdb"`
Vector VectorConfig `toml:"vector"`
Automated AutomatedConfig `toml:"automated"`
Agent map[string]AgentConfig `toml:"agent"`
EventsCoalesceInterval time.Duration `toml:"events_coalesce_interval"`
DaemonIdleTimeout time.Duration `toml:"daemon_idle_timeout"`
CustomModelPricing map[string]CustomModelRate `toml:"custom_model_pricing"`
RemoteHosts []RemoteHost `toml:"remote_hosts"`
}
meta, err := toml.Decode(data, &file)
if err != nil {
return fmt.Errorf("parsing config: %w", err)
}
var raw map[string]any
if _, err := toml.Decode(data, &raw); err != nil {
return fmt.Errorf("parsing config raw: %w", err)
}
if file.GithubToken != "" {
c.GithubToken = file.GithubToken
}
if file.CursorSecret != "" {
c.CursorSecret = file.CursorSecret
}
if file.CursorAdminAPIKey != "" && c.CursorAdminAPIKey == "" {
c.CursorAdminAPIKey = file.CursorAdminAPIKey
}
if file.CursorAdminEmail != "" && c.CursorAdminEmail == "" {
c.CursorAdminEmail = file.CursorAdminEmail
}
if file.CursorAdminUserID != "" && c.CursorAdminUserID == "" {
c.CursorAdminUserID = file.CursorAdminUserID
}
if file.Host != "" {
c.Host = file.Host
}
if file.Port != 0 {
c.Port = file.Port