返回 DeepSeek-Reasonix
config.go
根目录 / internal / config / config.go
1 // Package config loads Reasonix's runtime configuration from TOML. Resolution order:
2 // flag > project ./reasonix.toml > user config.toml (in the OS user-config dir) > built-in defaults.
3 // Secrets come from the environment via api_key_env and are never stored in
4 // config files.
5 package config
6
7 import (
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "net/netip"
13 "net/url"
14 "os"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "slices"
19 "strings"
20
21 fileencoding "reasonix/internal/fileutil/encoding"
22 "reasonix/internal/netclient"
23 "reasonix/internal/permissionpreset"
24 "reasonix/internal/provider"
25 )
26
27 var validSkillName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$`)
28
29 // IsValidSkillName reports whether name is a usable skill identifier.
30 func IsValidSkillName(name string) bool { return validSkillName.MatchString(name) }
31
32 // SkillNameKey normalizes a skill identifier for config comparisons.
33 func SkillNameKey(name string) string {
34 name = strings.TrimSpace(name)
35 if !IsValidSkillName(name) {
36 return ""
37 }
38 if runtime.GOOS == "windows" {
39 return strings.ToLower(name)
40 }
41 return name
42 }
43
44 // Config is Reasonix's runtime configuration.
45 type Config struct {
46 ConfigVersion int `toml:"config_version"`
47 DefaultModel string `toml:"default_model"`
48 Language string `toml:"language"` // ui/model language tag (e.g. "zh"); empty = auto-detect from $LANG / $REASONIX_LANG
49 CredentialsStore string `toml:"credentials_store"`
50 UI UIConfig `toml:"ui"`
51 CLI CLIConfig `toml:"cli"`
52 Desktop DesktopConfig `toml:"desktop"`
53 Billing BillingConfig `toml:"billing"`
54 Telemetry TelemetryConfig `toml:"telemetry"`
55 Notifications NotificationsConfig `toml:"notifications"`
56 Agent AgentConfig `toml:"agent"`
57 Providers []ProviderEntry `toml:"providers"`
58 Tools ToolsConfig `toml:"tools"`
59 Checkpoints CheckpointsConfig `toml:"checkpoints"`
60 Permissions PermissionsConfig `toml:"permissions"`
61 Sandbox SandboxConfig `toml:"sandbox"`
62 Network NetworkConfig `toml:"network"`
63 Environment EnvironmentConfig `toml:"environment"`
64 Plugins []PluginEntry `toml:"plugins"`
65 Skills SkillsConfig `toml:"skills"`
66 Statusline StatuslineConfig `toml:"statusline"`
67 LSP LSPConfig `toml:"lsp"`
68 Browser BrowserConfig `toml:"browser"`
69 Bot BotConfig `toml:"bot"`
70 Serve ServeConfig `toml:"serve"`
71 Secrets SecretsConfig `toml:"secrets"`
72 Remote RemoteConfig `toml:"remote"`
73 Attachments AttachmentsConfig `toml:"attachments,omitempty"`
74
75 systemPromptFileSource promptFileSource
76 providerSources map[string]providerSourceScope
77 shadowedProjectProviders []ProviderEntry
78 ignoredProjectDefaultModel string
79 ignoredLegacyStepLimits bool
80 expansionEnv map[string]string
81 pluginPackageOwners map[string]string
82 pluginPackageSkillOwners map[string][]string
83 pluginPackageAgentOwners map[string][]string
84 // explicitProjectSkillKeys records project-level skill fields that the
85 // settings UI intentionally owns even when their value equals the built-in
86 // default. It is transient edit metadata and is never serialized directly.
87 explicitProjectSkillKeys map[string]bool
88 stagedModelCredentials []string
89 modelCredentialCommit *modelCredentialCommitJournal
90 editLoadErr error
91 // loadWarnings are non-fatal issues observed while loading config (corrupt
92 // user/project files recovered via last-known-good or defaults). They never
93 // rewrite the original file; the UI may surface them for doctor repair.
94 loadWarnings []string
95 openCodeGoJournal *openCodeGoJournal
96 projectScope projectScopeReport
97 }
98
99 // KeepProjectSkillKey marks a skill field as an intentional project override.
100 // An explicit empty/false project value must still be written so it can
101 // override a non-default user setting in the layered configuration.
102 func (c *Config) KeepProjectSkillKey(key string) error {
103 key = strings.TrimSpace(key)
104 switch key {
105 case "paths", "excluded_paths", "disabled_skills", "disable_implicit_invocation", "max_depth":
106 default:
107 return fmt.Errorf("unknown project skill key %q", key)
108 }
109 if c.explicitProjectSkillKeys == nil {
110 c.explicitProjectSkillKeys = make(map[string]bool)
111 }
112 c.explicitProjectSkillKeys[key] = true
113 return nil
114 }
115
116 func (c *Config) keepsProjectSkillKey(key string) bool {
117 return c != nil && c.explicitProjectSkillKeys[key]
118 }
119
120 type promptFileSource uint8
121
122 const (
123 promptFileSourceUnknown promptFileSource = iota
124 promptFileSourceUser
125 promptFileSourceProject
126 )
127
128 type systemPromptFileError struct {
129 configured string
130 candidates []string
131 errors []error
132 allMissing bool
133 }
134
135 func (e *systemPromptFileError) Error() string {
136 detail := "could not be read from any configured location"
137 if e.allMissing {
138 detail = "not found at any configured location"
139 }
140 message := fmt.Sprintf("system_prompt_file %q %s: %s", e.configured, detail, strings.Join(e.candidates, ", "))
141 if !e.allMissing && len(e.errors) > 0 {
142 message += ": " + errors.Join(e.errors...).Error()
143 }
144 return message
145 }
146
147 func (e *systemPromptFileError) Unwrap() error { return errors.Join(e.errors...) }
148
149 // IsMissingSystemPromptFile reports whether every allowed location for a
150 // configured prompt file was absent. Permission, containment, and other I/O
151 // failures deliberately return false so callers do not start without an
152 // explicitly configured prompt.
153 func IsMissingSystemPromptFile(err error) bool {
154 var target *systemPromptFileError
155 return errors.As(err, &target) && target.allMissing
156 }
157
158 // TelemetryConfig controls content-free CLI usage metrics. It is user-global:
159 // project reasonix.toml values are ignored so a cloned repository cannot opt a
160 // user into reporting.
161 type TelemetryConfig struct {
162 CLIMetrics string `toml:"cli_metrics"` // auto|on|off; empty means consent has not been requested
163 }
164
165 // CLITelemetryConfigured reports whether the user has made an explicit CLI
166 // telemetry choice. The runtime policy still treats an absent value as auto,
167 // but persistence must preserve absence until the first eligible consent prompt.
168 func (c *Config) CLITelemetryConfigured() bool {
169 if c == nil {
170 return false
171 }
172 switch strings.ToLower(strings.TrimSpace(c.Telemetry.CLIMetrics)) {
173 case "auto", "on", "off":
174 return true
175 default:
176 return false
177 }
178 }
179
180 // CLITelemetryMode returns the normalized CLI telemetry policy.
181 func (c *Config) CLITelemetryMode() string {
182 if c == nil {
183 return "auto"
184 }
185 switch strings.ToLower(strings.TrimSpace(c.Telemetry.CLIMetrics)) {
186 case "on":
187 return "on"
188 case "off":
189 return "off"
190 default:
191 return "auto"
192 }
193 }
194
195 // LoadWarnings returns non-fatal config load issues (corrupt files recovered in
196 // memory). The returned slice is a copy.
197 func (c *Config) LoadWarnings() []string {
198 if c == nil || len(c.loadWarnings) == 0 {
199 return nil
200 }
201 out := make([]string, len(c.loadWarnings))
202 copy(out, c.loadWarnings)
203 return out
204 }
205
206 // HasLoadWarnings reports whether the load used a degraded in-memory fallback.
207 func (c *Config) HasLoadWarnings() bool {
208 return c != nil && len(c.loadWarnings) > 0
209 }
210
211 func (c *Config) addLoadWarning(msg string) {
212 if c == nil {
213 return
214 }
215 msg = strings.TrimSpace(msg)
216 if msg == "" {
217 return
218 }
219 c.loadWarnings = append(c.loadWarnings, msg)
220 }
221
222 // IgnoredLegacyAgentStepLimits reports whether this load found and ignored the
223 // retired [agent].max_steps or planner_max_steps settings. Boot removes standard
224 // key assignments before loading, while read-only/config-only loads only report
225 // and normalize them in memory.
226 func (c *Config) IgnoredLegacyAgentStepLimits() bool {
227 return c != nil && c.ignoredLegacyStepLimits
228 }
229
230 // IgnoredProjectDefaultModel returns the project reasonix.toml default_model
231 // that LoadForRoot ignored because no configured provider serves it (see
232 // restoreUnresolvableProjectDefaultModel), or "" when none was ignored.
233 func (c *Config) IgnoredProjectDefaultModel() string {
234 if c == nil {
235 return ""
236 }
237 return c.ignoredProjectDefaultModel
238 }
239
240 // SecretsConfig controls the credential protection layers. It is a user-global
241 // setting: project reasonix.toml values are ignored (see LoadForRoot), so a
242 // cloned repository cannot silently opt the user into workflow-breaking
243 // protections.
244 type SecretsConfig struct {
245 // FilterSubprocessEnv strips credential-like environment variables
246 // (*_API_KEY, *TOKEN*, *SECRET*, ...) from tool subprocesses (bash, hooks,
247 // LSP, MCP stdio). Default off: it breaks token-based workflows such as
248 // `gh`, HTTPS `git push`, and `npm publish`.
249 FilterSubprocessEnv bool `toml:"filter_subprocess_env"`
250 // ProtectSensitiveFiles makes read/list/search tools treat credential
251 // paths (.env, .git-credentials, .netrc, *.pem/*.key/*.p12/*.pfx, ~/.ssh)
252 // as invisible. Default off because hiding the files breaks legitimate
253 // "edit my .env" workflows.
254 ProtectSensitiveFiles bool `toml:"protect_sensitive_files"`
255 }
256
257 type providerSourceScope string
258
259 const (
260 providerSourceUser providerSourceScope = "user"
261 providerSourceProject providerSourceScope = "project"
262 )
263
264 // UIConfig controls CLI presentation-only settings. Desktop appearance is kept in
265 // DesktopConfig so desktop preferences cannot alter terminal output or prompts.
266 type UIConfig struct {
267 Theme string `toml:"theme"` // auto|dark|light; empty resolves to auto
268 ThemeStyle string `toml:"theme_style"` // graphite|aurora|slate|carbon|nocturne|amber and legacy aliases
269 ShortcutLayout string `toml:"shortcut_layout"` // classic|desktop; accepted for compatibility
270 CloseBehavior string `toml:"close_behavior"` // legacy desktop close behavior; prefer desktop.close_behavior
271 ShowReasoning bool `toml:"show_reasoning"` // Ctrl+O / /verbose: show thinking text in CLI; false = collapsed
272 ShowTurnUsage bool `toml:"show_turn_usage"` // show per-request token/cost receipts in the CLI/TUI transcript
273 CursorShape string `toml:"cursor_shape"` // block|underline|bar; empty defaults to bar
274 }
275
276 // CLIConfig controls user-global native CLI behavior. It is separate from
277 // project runtime settings so a repository cannot change the installed
278 // binary's update channel.
279 type CLIConfig struct {
280 // UpdateChannel is decoded for compatibility with pre-single-channel
281 // configurations. Runtime behavior is always the official release channel,
282 // and the canonical renderer intentionally drops this field.
283 UpdateChannel string `toml:"update_channel"`
284 }
285
286 // NotificationsConfig controls optional system notifications for CLI chat/run.
287 type NotificationsConfig struct {
288 Enabled bool `toml:"enabled"`
289 TurnDone bool `toml:"turn_done"`
290 ApprovalRequest bool `toml:"approval_request"`
291 AskRequest bool `toml:"ask_request"`
292 }
293
294 // EnvironmentEnabled reports whether startup environment probing should feed the
295 // cache-stable system prompt.
296 func (c *Config) EnvironmentEnabled() bool {
297 return c == nil || c.Environment.Enabled == nil || *c.Environment.Enabled
298 }
299
300 // UITheme normalizes ui.theme to a supported value.
301 func (c *Config) UITheme() string {
302 switch strings.ToLower(strings.TrimSpace(c.UI.Theme)) {
303 case "dark":
304 return "dark"
305 case "light":
306 return "light"
307 default:
308 return "auto"
309 }
310 }
311
312 // UIThemeStyle normalizes ui.theme_style. Empty means "pick the default style
313 // for the resolved light/dark shell".
314 func (c *Config) UIThemeStyle() string {
315 return normalizeThemeStyle(c.UI.ThemeStyle)
316 }
317
318 // UIShortcutLayout normalizes the legacy CLI shortcut layout setting. It is
319 // retained for configuration compatibility; permission presets are selected
320 // explicitly and are not encoded in this layout.
321 func (c *Config) UIShortcutLayout() string {
322 switch strings.ToLower(strings.TrimSpace(c.UI.ShortcutLayout)) {
323 case "desktop", "dual", "dual-axis", "dual_axis":
324 return "desktop"
325 default:
326 return "classic"
327 }
328 }
329
330 // UICursorShape normalizes ui.cursor_shape. The slim "bar" default stays
331 // visible without covering CJK wide characters. Valid values are "block",
332 // "underline", and "bar".
333 func (c *Config) UICursorShape() string {
334 switch strings.ToLower(strings.TrimSpace(c.UI.CursorShape)) {
335 case "block":
336 return "block"
337 case "underline":
338 return "underline"
339 default:
340 return "bar"
341 }
342 }
343
344 func normalizeThemeStyle(style string) string {
345 switch strings.ToLower(strings.TrimSpace(style)) {
346 case "graphite", "aurora", "slate", "carbon", "nocturne", "amber", "ember", "midnight", "sandstone", "porcelain", "linen", "glacier":
347 return strings.ToLower(strings.TrimSpace(style))
348 default:
349 return ""
350 }
351 }
352
353 // The retired "classic" style normalizes to workbench, like any other value
354 // this build does not know, so a config written before the style was removed
355 // keeps working and the Go side and the UI agree on what it means.
356 func normalizeDesktopLayoutStyle(style string) string {
357 switch strings.ToLower(strings.TrimSpace(style)) {
358 case "creation":
359 return "creation"
360 default:
361 return "workbench"
362 }
363 }
364
365 func normalizeCloseBehavior(mode string) string {
366 switch strings.ToLower(strings.TrimSpace(mode)) {
367 case "quit", "exit":
368 return "quit"
369 default:
370 return "background"
371 }
372 }
373
374 // DesktopLanguage normalizes the desktop UI language. Empty means auto-detect
375 // from the browser/OS locale; it deliberately does not read top-level language,
376 // which is used by the CLI/model-facing runtime.
377 func (c *Config) DesktopLanguage() string {
378 switch strings.ToLower(strings.TrimSpace(c.Desktop.Language)) {
379 case "en":
380 return "en"
381 case "zh":
382 return "zh"
383 default:
384 return ""
385 }
386 }
387
388 // DesktopCurrency returns the explicit user-global pricing currency. The
389 // persisted field keeps its original desktop namespace for compatibility;
390 // empty means the pricing region follows the desktop/CLI language.
391 func (c *Config) DesktopCurrency() string {
392 if c == nil {
393 return ""
394 }
395 switch strings.ToUpper(strings.TrimSpace(c.Desktop.Currency)) {
396 case "CNY", "RMB", "CNH":
397 return "CNY"
398 case "USD":
399 return "USD"
400 default:
401 return ""
402 }
403 }
404
405 // DesktopTheme normalizes desktop.theme. New desktop users default to the OS
406 // automatic graphite product look; an explicit auto/light/dark is preserved.
407 func (c *Config) DesktopTheme() string {
408 switch strings.ToLower(strings.TrimSpace(c.Desktop.Theme)) {
409 case "auto":
410 return "auto"
411 case "light":
412 return "light"
413 case "dark":
414 return "dark"
415 default:
416 return "auto"
417 }
418 }
419
420 // DesktopThemeStyle normalizes desktop.theme_style. Empty means the frontend
421 // chooses the default style for the resolved desktop theme.
422 func (c *Config) DesktopThemeStyle() string {
423 return normalizeThemeStyle(c.Desktop.ThemeStyle)
424 }
425
426 // DesktopTerminalTheme normalizes the integrated terminal colour preference.
427 // Auto deliberately follows the resolved desktop app theme, including OS theme
428 // changes while desktop.theme is also auto.
429 func (c *Config) DesktopTerminalTheme() string {
430 switch strings.ToLower(strings.TrimSpace(c.Desktop.TerminalTheme)) {
431 case "dark":
432 return "dark"
433 case "light":
434 return "light"
435 default:
436 return "auto"
437 }
438 }
439
440 // DesktopLayoutStyle defaults to workbench. The retired "classic" value is
441 // normalized on read rather than migrated to disk: nothing behaves differently
442 // for it, so there is no rewritten value worth persisting.
443 func (c *Config) DesktopLayoutStyle() string {
444 if strings.EqualFold(strings.TrimSpace(c.Desktop.ThemeStyle), "workbench") && strings.TrimSpace(c.Desktop.LayoutStyle) == "" {
445 return "workbench"
446 }
447 return normalizeDesktopLayoutStyle(c.Desktop.LayoutStyle)
448 }
449
450 // DesktopCloseBehavior normalizes the desktop close-window preference. It falls
451 // back to the legacy ui.close_behavior value for configs written before [desktop]
452 // existed.
453 func (c *Config) DesktopCloseBehavior() string {
454 if strings.TrimSpace(c.Desktop.CloseBehavior) != "" {
455 return normalizeCloseBehavior(c.Desktop.CloseBehavior)
456 }
457 return normalizeCloseBehavior(c.UI.CloseBehavior)
458 }
459
460 // UICloseBehavior is the legacy name for DesktopCloseBehavior.
461 func (c *Config) UICloseBehavior() string {
462 return c.DesktopCloseBehavior()
463 }
464
465 // DesktopConversationWidth returns the normalized desktop conversation width.
466 // Unknown and missing values fall back to standard for backward compatibility.
467 func (c *Config) DesktopConversationWidth() string {
468 if c != nil && strings.EqualFold(strings.TrimSpace(c.Desktop.ConversationWidth), "full") {
469 return "full"
470 }
471 return "standard"
472 }
473
474 // NormalizeToolApprovalMode returns the canonical execution permission preset.
475 // Legacy ask/auto/yolo values are migrated conservatively.
476 func NormalizeToolApprovalMode(mode string) string {
477 return string(permissionpreset.Normalize(mode))
478 }
479
480 // DesktopDefaultToolApprovalMode is the permission preset for new desktop
481 // sessions. An omitted value defaults to workspace-write; restored legacy
482 // values use the conservative migration in permissionpreset.Normalize.
483 func (c *Config) DesktopDefaultToolApprovalMode() string {
484 if c == nil {
485 return string(permissionpreset.WorkspaceWrite)
486 }
487 return string(permissionpreset.NormalizeDefault(c.Desktop.DefaultToolApprovalMode))
488 }
489
490 // DesktopStatusBarStyle normalizes the desktop status bar metric label style.
491 // Unmigrated configurations adopt icon labels once; later choices are preserved.
492 func (c *Config) DesktopStatusBarStyle() string {
493 if !c.Desktop.StatusBarStyleInitialized {
494 return "icon"
495 }
496 switch strings.ToLower(strings.TrimSpace(c.Desktop.StatusBarStyle)) {
497 case "icon":
498 return "icon"
499 case "text":
500 return "text"
501 default:
502 return "icon"
503 }
504 }
505
506 var defaultDesktopStatusBarItems = []string{
507 "model",
508 "workspace",
509 "git_branch",
510 "cache",
511 "cache_avg",
512 "session_tokens",
513 "turn_tokens",
514 "turn_tps",
515 "turn_output_tokens",
516 "turn_cache_tokens",
517 "turn_cost",
518 "session_turns",
519 "context",
520 "compact",
521 "cost",
522 "balance",
523 }
524
525 var knownDesktopStatusBarItems = desktopStatusBarItemSet(defaultDesktopStatusBarItems)
526
527 func desktopStatusBarItemSet(items []string) map[string]bool {
528 out := make(map[string]bool, len(items))
529 for _, item := range items {
530 out[item] = true
531 }
532 return out
533 }
534
535 // DefaultDesktopStatusBarItems returns the default ordered visible desktop
536 // status bar items.
537 func DefaultDesktopStatusBarItems() []string {
538 return append([]string(nil), defaultDesktopStatusBarItems...)
539 }
540
541 // DesktopStatusBarItems normalizes the ordered visible desktop status bar items.
542 // An unset or empty list uses the default full set; explicit non-empty lists
543 // preserve user order and omit hidden items.
544 func (c *Config) DesktopStatusBarItems() []string {
545 return normalizeDesktopStatusBarItems(c.Desktop.StatusBarItems)
546 }
547
548 func normalizeDesktopStatusBarItems(items []string) []string {
549 out := make([]string, 0, len(items))
550 seen := map[string]bool{}
551 for _, raw := range items {
552 id := strings.TrimSpace(raw)
553 if !knownDesktopStatusBarItems[id] || seen[id] {
554 continue
555 }
556 out = append(out, id)
557 seen[id] = true
558 }
559 if len(out) == 0 {
560 return DefaultDesktopStatusBarItems()
561 }
562 return out
563 }
564
565 // DesktopCheckUpdates reports whether the desktop should check for updates on
566 // startup. Missing configs default to true so existing users keep update notices.
567 func (c *Config) DesktopCheckUpdates() bool {
568 if c == nil || c.Desktop.CheckUpdates == nil {
569 return true
570 }
571 return *c.Desktop.CheckUpdates
572 }
573
574 // NormalizeCLIUpdateChannel returns the only public native CLI update channel.
575 // The input remains accepted so older preview configurations keep loading.
576 func NormalizeCLIUpdateChannel(_ string) string {
577 return "stable"
578 }
579
580 // CLIUpdateChannel returns the user-global native CLI update channel.
581 func (c *Config) CLIUpdateChannel() string {
582 if c == nil {
583 return "stable"
584 }
585 return NormalizeCLIUpdateChannel(c.CLI.UpdateChannel)
586 }
587
588 // NormalizeDesktopUpdateChannel returns the only public Desktop update channel.
589 // Legacy preview/canary/beta/next values are deliberately ignored so an old
590 // configuration cannot strand the installation on the retired channel.
591 func NormalizeDesktopUpdateChannel(_ string) string {
592 return "stable"
593 }
594
595 // DesktopUpdateChannel returns the desktop channel whose latest pointer should be
596 // checked. Missing or unknown configs default to stable.
597 func (c *Config) DesktopUpdateChannel() string {
598 if c == nil {
599 return "stable"
600 }
601 return NormalizeDesktopUpdateChannel(c.Desktop.UpdateChannel)
602 }
603
604 // ColdResumePruneEnabled reports whether stale tool results are elided when a
605 // session resumes past the provider cache window. Default true (cheaper cold
606 // restart); users keep full history by disabling it.
607 func (c *Config) ColdResumePruneEnabled() bool {
608 if c == nil || c.Agent.ColdResumePrune == nil {
609 return true
610 }
611 return *c.Agent.ColdResumePrune
612 }
613
614 // ResponseLanguage normalizes the top-level language preference for final
615 // answers. Empty means auto: replies follow the current user turn.
616 func (c *Config) ResponseLanguage() string {
617 if c == nil {
618 return "auto"
619 }
620 return NormalizeLanguage(c.Language)
621 }
622
623 // NormalizeLanguage returns one of auto|zh|en for UI/default reply language settings.
624 func NormalizeLanguage(lang string) string {
625 switch strings.ToLower(strings.TrimSpace(lang)) {
626 case "", "auto", "detect", "default":
627 return "auto"
628 case "zh", "cn", "chinese", "中文":
629 return "zh"
630 case "en", "english":
631 return "en"
632 default:
633 return "auto"
634 }
635 }
636
637 // ReasoningLanguage normalizes agent.reasoning_language. Empty means auto:
638 // visible reasoning follows the conversation language already described by the
639 // stable LanguagePolicy. Legacy "default" is treated as auto.
640 func (c *Config) ReasoningLanguage() string {
641 if c == nil {
642 return "auto"
643 }
644 return NormalizeReasoningLanguage(c.Agent.ReasoningLanguage)
645 }
646
647 // NormalizeReasoningLanguage returns one of auto|zh|en.
648 func NormalizeReasoningLanguage(lang string) string {
649 switch strings.ToLower(strings.TrimSpace(lang)) {
650 case "", "auto", "follow", "conversation", "detect", "default", "model", "model-default", "model_default", "provider":
651 return "auto"
652 case "zh", "cn", "chinese", "中文":
653 return "zh"
654 case "en", "english":
655 return "en"
656 default:
657 return "auto"
658 }
659 }
660
661 // DesktopTelemetry reports whether the desktop sends the anonymous launch ping.
662 // It carries no conversation, key, or file data — see desktop/README.md.
663 func (c *Config) DesktopTelemetry() bool {
664 if c == nil || c.Desktop.Telemetry == nil {
665 return true
666 }
667 return *c.Desktop.Telemetry
668 }
669
670 // DesktopMetrics reports whether the desktop sends aggregate desktop metrics —
671 // anonymous (signal, bucket) counters, never content. Default on.
672 func (c *Config) DesktopMetrics() bool {
673 if c == nil || c.Desktop.Metrics == nil {
674 return true
675 }
676 return *c.Desktop.Metrics
677 }
678
679 // LSPConfig governs the optional Language Server Protocol tools (lsp_definition,
680 // lsp_references, lsp_hover, lsp_diagnostics). Enabled defaults to true; the
681 // servers themselves are never bundled — each resolves on PATH and the tool
682 // returns an install hint when it is missing, so the capability is dormant until
683 // the user installs a server. Servers overrides or extends the built-in language
684 // → server map, keyed by language id (e.g. "go", "rust", "python").
685 type LSPConfig struct {
686 Enabled bool `toml:"enabled"`
687 Servers map[string]LSPServer `toml:"servers"`
688 }
689
690 // LSPServer overrides a built-in language's server or, when keyed by a new
691 // language, adds one. An empty field falls back to the built-in default for that
692 // language; Extensions is required when adding a language the built-ins don't
693 // cover (e.g. ".ex" for Elixir) so files route to it.
694 type LSPServer struct {
695 Command string `toml:"command"`
696 Args []string `toml:"args"`
697 Env map[string]string `toml:"env"`
698 LanguageID string `toml:"language_id"`
699 Extensions []string `toml:"extensions"`
700 InstallHint string `toml:"install_hint"`
701 }
702
703 // StatuslineConfig configures a custom status line. Command, when set, is run at
704 // startup and after each turn; its first line of stdout replaces the built-in
705 // status data row. A JSON payload (model, context tokens, cwd) is fed on stdin.
706 type StatuslineConfig struct {
707 Command string `toml:"command"`
708 }
709
710 // CheckpointsConfig tunes rewind snapshot retention. Zero values leave the
711 // built-in defaults in place (100 turns, 1 GiB soft budget).
712 type CheckpointsConfig struct {
713 // RetainTurns caps how many turns of file payloads are kept.
714 RetainTurns int `toml:"retain_turns"`
715 // BlobQuotaBytes is the soft byte budget for retained file payloads. A
716 // protected or current turn may temporarily exceed it.
717 BlobQuotaBytes int64 `toml:"blob_quota_bytes"`
718 }
719
720 // BotConfig 控制多渠道 IM bot 消息网关。
721 type BotConfig struct {
722 Enabled bool `toml:"enabled"`
723 Model string `toml:"model"` // 用于 bot 的模型名,空则用 default_model
724 ToolApprovalMode string `toml:"tool_approval_mode"`
725 MaxSteps int `toml:"max_steps"`
726 DebounceMs int `toml:"debounce_ms"` // 消息合并窗口,毫秒
727 QueueMode string `toml:"queue_mode"` // steer|followup|collect|interrupt
728 QueueCap int `toml:"queue_cap"`
729 QueueDrop string `toml:"queue_drop"` // summarize|old|new
730 IgnoreSelfMessages bool `toml:"ignore_self_messages"`
731 SelfUserIDs BotSelfUserIDs `toml:"self_user_ids"`
732 Control BotControlConfig `toml:"control"`
733 Pairing BotPairingConfig `toml:"pairing"`
734 Allowlist BotAllowlist `toml:"allowlist"`
735 QQ QQBotConfig `toml:"qq"`
736 Feishu FeishuBotConfig `toml:"feishu"`
737 Weixin WeixinBotConfig `toml:"weixin"`
738 Dingtalk DingtalkBotConfig `toml:"dingtalk"`
739 Routes []BotRouteConfig `toml:"routes"`
740 Connections []BotConnectionConfig `toml:"connections"`
741 // DesktopWatchers persists /desktop watch subscriptions so god-view
742 // notifications survive a desktop restart. Managed by the desktop bot
743 // bridge, not the settings UI.
744 DesktopWatchers []BotDesktopWatcherConfig `toml:"desktop_watchers"`
745 }
746
747 // BotDesktopWatcherConfig is one bot chat subscribed to desktop events
748 // (/desktop watch on).
749 type BotDesktopWatcherConfig struct {
750 Platform string `toml:"platform"`
751 ConnectionID string `toml:"connection_id"`
752 Domain string `toml:"domain"`
753 ChatType string `toml:"chat_type"`
754 ChatID string `toml:"chat_id"`
755 }
756
757 type BotSelfUserIDs struct {
758 QQ []string `toml:"qq"`
759 Feishu []string `toml:"feishu"`
760 Weixin []string `toml:"weixin"`
761 Dingtalk []string `toml:"dingtalk"`
762 }
763
764 type BotControlConfig struct {
765 Enabled bool `toml:"enabled"`
766 Addr string `toml:"addr"`
767 TokenEnv string `toml:"token_env"`
768 }
769
770 type BotRouteConfig struct {
771 ConnectionID string `toml:"connection_id"`
772 Platform string `toml:"platform"`
773 ChatType string `toml:"chat_type"`
774 ChatID string `toml:"chat_id"`
775 UserID string `toml:"user_id"`
776 ThreadID string `toml:"thread_id"`
777 Model string `toml:"model"`
778 ToolApprovalMode string `toml:"tool_approval_mode"`
779 WorkspaceRoot string `toml:"workspace_root"`
780 }
781
782 // BotAllowlist 控制哪些用户可以使用 bot。
783 type BotAllowlist struct {
784 Enabled bool `toml:"enabled"`
785 AllowAll bool `toml:"allow_all"`
786 QQUsers []string `toml:"qq_users"`
787 FeishuUsers []string `toml:"feishu_users"`
788 WeixinUsers []string `toml:"weixin_users"`
789 QQApprovers []string `toml:"qq_approvers"`
790 FeishuApprovers []string `toml:"feishu_approvers"`
791 WeixinApprovers []string `toml:"weixin_approvers"`
792 QQAdmins []string `toml:"qq_admins"`
793 FeishuAdmins []string `toml:"feishu_admins"`
794 WeixinAdmins []string `toml:"weixin_admins"`
795 QQGroups []string `toml:"qq_groups"`
796 FeishuGroups []string `toml:"feishu_groups"`
797 WeixinGroups []string `toml:"weixin_groups"`
798 DingtalkUsers []string `toml:"dingtalk_users"`
799 DingtalkApprovers []string `toml:"dingtalk_approvers"`
800 DingtalkAdmins []string `toml:"dingtalk_admins"`
801 DingtalkGroups []string `toml:"dingtalk_groups"`
802 }
803
804 type BotPairingConfig struct {
805 Enabled bool `toml:"enabled"`
806 RequestTTLMinutes int `toml:"request_ttl_minutes"`
807 MaxPendingPerPlatform int `toml:"max_pending_per_platform"`
808 }
809
810 // BotAccessConfig controls who may use one concrete bot connection.
811 type BotAccessConfig struct {
812 Enabled bool `toml:"enabled"`
813 AllowAll bool `toml:"allow_all"`
814 PairingEnabled bool `toml:"pairing_enabled"`
815 Users []string `toml:"users"`
816 Groups []string `toml:"groups"`
817 Approvers []string `toml:"approvers"`
818 Admins []string `toml:"admins"`
819 }
820
821 // QQBotConfig QQ 官方 Bot API v2 配置。
822 type QQBotConfig struct {
823 Enabled bool `toml:"enabled"`
824 AppID string `toml:"app_id"`
825 AppSecretEnv string `toml:"app_secret_env"` // 环境变量名,如 QQ_BOT_APP_SECRET
826 Sandbox bool `toml:"sandbox"` // true 使用 QQ 沙箱 API / gateway
827 Model string `toml:"model"`
828 ToolApprovalMode string `toml:"tool_approval_mode"`
829 WorkspaceRoot string `toml:"workspace_root"`
830 Access BotAccessConfig `toml:"access"`
831 }
832
833 // FeishuBotConfig 飞书自建应用 Bot 配置。
834 type FeishuBotConfig struct {
835 Enabled bool `toml:"enabled"`
836 Domain string `toml:"domain"` // feishu(默认)| lark
837 AppID string `toml:"app_id"`
838 AppSecretEnv string `toml:"app_secret_env"` // 如 FEISHU_BOT_APP_SECRET
839 VerificationToken string `toml:"verification_token"` // 事件订阅验证 token
840 Mode string `toml:"mode"` // webhook(默认)| websocket
841 WebhookPort int `toml:"webhook_port"` // webhook 模式端口
842 RequireMention bool `toml:"require_mention"`
843 // OutboundMediaRoots contains absolute local directories the loopback /send
844 // control API may attach files from. Media refs must be bare filenames and
845 // must exist in exactly one configured root. Empty (the default) disables
846 // outbound file sending.
847 OutboundMediaRoots []string `toml:"outbound_media_roots"`
848 }
849
850 // WeixinBotConfig 微信 iLink Bot 配置。
851 type WeixinBotConfig struct {
852 Enabled bool `toml:"enabled"`
853 AccountID string `toml:"account_id"`
854 TokenEnv string `toml:"token_env"` // 环境变量名,如 WEIXIN_BOT_TOKEN
855 APIBase string `toml:"api_base"` // iLink API base URL
856 }
857
858 // DingtalkBotConfig 钉钉企业内部应用机器人(Stream 模式)配置。
859 type DingtalkBotConfig struct {
860 Enabled bool `toml:"enabled"`
861 ClientID string `toml:"client_id"` // 钉钉应用 AppKey(ClientID)
862 ClientSecret string `toml:"client_secret"` // 钉钉应用 AppSecret(ClientSecret)
863 ClientIDEnv string `toml:"client_id_env"` // 环境变量名,如 DINGTALK_CLIENT_ID
864 SecretEnv string `toml:"secret_env"` // 环境变量名,如 DINGTALK_CLIENT_SECRET
865 BotName string `toml:"bot_name"` // 机器人昵称;群聊 @ 剥离时匹配
866 RequireMention bool `toml:"require_mention"` // 群聊是否必须 @ 机器人
867 Model string `toml:"model"` // 会话模型;空 = 全局默认
868 ToolApprovalMode string `toml:"tool_approval_mode"` // read-only|workspace-write|danger-full-access;空 = 全局默认
869 WorkspaceRoot string `toml:"workspace_root"` // 会话工作目录;空 = 启动 Bot 时的 cwd
870 Access BotAccessConfig `toml:"access"` // 该渠道访问控制(allowlist)
871 // SessionMappings 直配渠道的会话绑定(与 [[bot.connections]] 同构)。
872 // legacy [bot.dingtalk] 没有 connection 记录,/new 旋转后的新会话路径
873 // 持久化在这里,重启后仍能恢复(见 botruntime.rememberInbound)。
874 SessionMappings []BotConnectionSessionMapping `toml:"session_mappings"`
875 }
876
877 // BotConnectionConfig is the desktop-friendly connection record for IM bot
878 // channels. It keeps install/runtime state separate from legacy per-provider
879 // knobs so the UI can expose a simple "connect first" flow while old configs
880 // keep working.
881 type BotConnectionConfig struct {
882 ID string `toml:"id"`
883 Provider string `toml:"provider"` // qq|feishu|weixin
884 Domain string `toml:"domain"` // feishu|lark|weixin|qq
885 Label string `toml:"label"`
886 Enabled bool `toml:"enabled"`
887 Status string `toml:"status"` // disconnected|pending|connected|error
888 Model string `toml:"model"`
889 ToolApprovalMode string `toml:"tool_approval_mode"`
890 WorkspaceRoot string `toml:"workspace_root"`
891 Access BotAccessConfig `toml:"access"`
892 Credential BotConnectionCredential `toml:"credential"`
893 SessionMappings []BotConnectionSessionMapping `toml:"session_mappings"`
894 LastError string `toml:"last_error"`
895 CreatedAt string `toml:"created_at"`
896 UpdatedAt string `toml:"updated_at"`
897 }
898
899 type BotConnectionCredential struct {
900 AppID string `toml:"app_id"`
901 AppSecretEnv string `toml:"app_secret_env"`
902 AccountID string `toml:"account_id"`
903 TokenEnv string `toml:"token_env"`
904 }
905
906 type BotConnectionSessionMapping struct {
907 RemoteID string `toml:"remote_id"`
908 SessionID string `toml:"session_id"`
909 SessionSource string `toml:"session_source"`
910 ChatType string `toml:"chat_type"`
911 UserID string `toml:"user_id"`
912 ThreadID string `toml:"thread_id"`
913 Scope string `toml:"scope"`
914 WorkspaceRoot string `toml:"workspace_root"`
915 UpdatedAt string `toml:"updated_at"`
916 }
917
918 // ServeConfig controls the HTTP serve frontend security settings.
919 type ServeConfig struct {
920 // AuthMode selects the authentication mode for the HTTP serve frontend.
921 // "none" (default): no authentication.
922 // "token": a pre-shared token in the URL query string.
923 // "password": a login page with bcrypt password verification.
924 AuthMode string `toml:"auth_mode"`
925 // Token is a pre-shared token for auth_mode = "token". When empty, a
926 // cryptographically random token is generated at startup and printed.
927 Token string `toml:"token"`
928 // PasswordHash is a bcrypt hash of the password for auth_mode = "password".
929 // Generate one with: reasonix serve --hash-password --password '...'
930 PasswordHash string `toml:"password_hash"`
931 // BehindProxy indicates the server sits behind a trusted reverse proxy
932 // (nginx, Caddy, Cloudflare, etc.) that sets X-Forwarded-For and
933 // X-Forwarded-Proto headers. When true, those headers are used for
934 // rate-limiting and Secure-cookie decisions. When false (default), they
935 // are ignored — an attacker can otherwise forge them.
936 BehindProxy bool `toml:"behind_proxy"`
937 }
938
939 // NetworkConfig controls ordinary outbound HTTP traffic such as model providers,
940 // wallet-balance lookups, updater checks, CodeGraph downloads, and web_fetch.
941 // web_fetch reuses these proxy settings while keeping its own SSRF-guarded
942 // dialer.
943 type NetworkConfig struct {
944 // ProxyMode is "auto" (default; environment proxy for now), "env", "custom",
945 // or "off". auto leaves room for OS proxy detection later without changing the
946 // config shape.
947 ProxyMode string `toml:"proxy_mode"`
948 // ProxyURL is an advanced custom override such as "socks5://127.0.0.1:7890".
949 // When set and proxy_mode = "custom", it wins over the structured proxy table.
950 ProxyURL string `toml:"proxy_url"`
951 // NoProxy is honored for custom proxies. Env/auto modes use NO_PROXY from the
952 // process environment instead.
953 NoProxy string `toml:"no_proxy"`
954 Proxy NetworkProxyConfig `toml:"proxy"`
955 }
956
957 // NetworkProxyConfig is the structured custom-proxy editor shape. Password is
958 // optional and supports ${VAR} expansion, so users can avoid storing it literally.
959 type NetworkProxyConfig struct {
960 Type string `toml:"type"` // http|https|socks5|socks5h
961 Server string `toml:"server"`
962 Port int `toml:"port"`
963 Username string `toml:"username"`
964 Password string `toml:"password"`
965 }
966
967 // NetworkProxySpec returns the expanded proxy settings used by netclient. The
968 // settings are the user's, so ${VAR} expands from the process environment and
969 // never from a workspace .env.
970 func (c *Config) NetworkProxySpec() netclient.ProxySpec {
971 return netclient.ProxySpec{
972 Mode: c.Network.ProxyMode,
973 URL: ExpandVars(c.Network.ProxyURL),
974 NoProxy: ExpandVars(c.Network.NoProxy),
975 Type: c.Network.Proxy.Type,
976 Server: ExpandVars(c.Network.Proxy.Server),
977 Port: c.Network.Proxy.Port,
978 Username: ExpandVars(c.Network.Proxy.Username),
979 Password: ExpandVars(c.Network.Proxy.Password),
980 DirectHosts: c.directProxyHosts(),
981 }
982 }
983
984 // directProxyHosts collects the base_url hosts of providers marked no_proxy, so
985 // netclient bypasses the proxy for them without knowing any provider by name.
986 //
987 // Only for an auto-detected proxy (auto/env): that proxy is typically a
988 // GFW-circumvention one not meant for domestic endpoints (e.g. mimo), so keep
989 // them direct. An explicit proxy_mode = "custom" is the user saying "route
990 // everything through this" — e.g. a mandatory corporate proxy — so honor it for
991 // every provider; a custom-proxy user who wants a host direct uses
992 // network.no_proxy instead (#3635).
993 func (c *Config) directProxyHosts() []string {
994 if c.NetworkProxyMode() == netclient.ModeCustom {
995 return nil
996 }
997 seen := map[string]bool{}
998 var out []string
999 for _, p := range c.Providers {
1000 if !p.NoProxy {
1001 continue
1002 }
1003 u, err := url.Parse(strings.TrimSpace(p.BaseURL))
1004 if err != nil {
1005 continue
1006 }
1007 if h := u.Hostname(); h != "" && !seen[h] {
1008 seen[h] = true
1009 out = append(out, h)
1010 }
1011 }
1012 return out
1013 }
1014
1015 // NetworkProxyMode normalizes network.proxy_mode to a known value.
1016 func (c *Config) NetworkProxyMode() string {
1017 return netclient.NormalizeMode(c.Network.ProxyMode)
1018 }
1019
1020 // SkillsConfig configures skill discovery. Paths adds extra "custom"-scope skill
1021 // roots — each a directory of SKILL.md / <name>.md playbooks — scanned between
1022 // the project roots (.reasonix/.agents/.agent/.claude under the workspace) and
1023 // the global roots. ExcludedPaths hides matching discovery roots without deleting
1024 // folders. ~, relative paths, and ${VAR} expansion are supported. DisabledSkills
1025 // hides named skills from the agent prompt, slash invocation, and skill tools
1026 // while keeping them manageable. DisableImplicitInvocation keeps skills
1027 // discoverable to the host for explicit /skill use and management, but hides
1028 // their index and model-facing invocation tools.
1029 type SkillsConfig struct {
1030 Paths []string `toml:"paths"`
1031 ExcludedPaths []string `toml:"excluded_paths"`
1032 DisabledSkills []string `toml:"disabled_skills"`
1033 DisableImplicitInvocation bool `toml:"disable_implicit_invocation"`
1034 MaxDepth int `toml:"max_depth"`
1035 }
1036
1037 // ImplicitSkillInvocationEnabled reports whether the model may discover and
1038 // invoke skills without an explicit user slash command. The zero value keeps
1039 // the historical default enabled for old configs.
1040 func (c *Config) ImplicitSkillInvocationEnabled() bool {
1041 return c == nil || !c.Skills.DisableImplicitInvocation
1042 }
1043
1044 // SkillCustomPaths returns the configured custom skill roots with ${VAR}
1045 // expanded; empty entries are dropped.
1046 func (c *Config) SkillCustomPaths() []string {
1047 var out []string
1048 for _, p := range c.Skills.Paths {
1049 if p = c.expandVars(p); strings.TrimSpace(p) != "" {
1050 out = append(out, p)
1051 }
1052 }
1053 return out
1054 }
1055
1056 // SkillExcludedPaths returns configured skill roots that should be hidden from
1057 // discovery, with ${VAR} expanded and empty entries dropped.
1058 func (c *Config) SkillExcludedPaths() []string {
1059 var out []string
1060 for _, p := range c.Skills.ExcludedPaths {
1061 if p = c.expandVars(p); strings.TrimSpace(p) != "" {
1062 out = append(out, p)
1063 }
1064 }
1065 return out
1066 }
1067
1068 // SkillMaxDepth bounds nested skill discovery. Depth 3 favors bundled skill
1069 // packs while Store keeps nested markdown safe by requiring descriptions.
1070 func (c *Config) SkillMaxDepth() int {
1071 const (
1072 defaultDepth = 3
1073 maxDepth = 5
1074 )
1075 if c == nil || c.Skills.MaxDepth == 0 {
1076 return defaultDepth
1077 }
1078 if c.Skills.MaxDepth < 1 {
1079 return 1
1080 }
1081 if c.Skills.MaxDepth > maxDepth {
1082 return maxDepth
1083 }
1084 return c.Skills.MaxDepth
1085 }
1086
1087 // DisabledSkillNames returns valid disabled skill identifiers, preserving the
1088 // first spelling and dropping duplicates/empty entries.
1089 func (c *Config) DisabledSkillNames() []string {
1090 seen := map[string]bool{}
1091 var out []string
1092 for _, name := range c.Skills.DisabledSkills {
1093 name = strings.TrimSpace(name)
1094 if !IsValidSkillName(name) {
1095 continue
1096 }
1097 key := SkillNameKey(name)
1098 if seen[key] {
1099 continue
1100 }
1101 seen[key] = true
1102 out = append(out, name)
1103 }
1104 return out
1105 }
1106
1107 // IsSkillDisabled reports whether name is configured as disabled.
1108 func (c *Config) IsSkillDisabled(name string) bool {
1109 key := SkillNameKey(name)
1110 if key == "" {
1111 return false
1112 }
1113 for _, disabled := range c.DisabledSkillNames() {
1114 if SkillNameKey(disabled) == key {
1115 return true
1116 }
1117 }
1118 return false
1119 }
1120
1121 // SandboxConfig bounds the blast radius of tool calls (Phase 0: file-writer
1122 // confinement). WorkspaceRoot is the directory the built-in file writers
1123 // (write_file / edit_file / multi_edit / move_file) may modify; empty means the
1124 // current working directory, so writes stay inside the project by default.
1125 // AllowWrite lists extra directories writers may also touch (e.g. a sibling repo
1126 // or a temp dir). ForbidRead lists files or directories the agent may not read or list
1127 // (e.g. ~/.ssh for secrets). Both support ${VAR} / ${VAR:-default} expansion. Reads are
1128 // unrestricted; confining `bash` is Phase 1 (OS-level sandbox).
1129 type SandboxConfig struct {
1130 WorkspaceRoot string `toml:"workspace_root"`
1131 AllowWrite []string `toml:"allow_write"`
1132 ForbidRead []string `toml:"forbid_read"`
1133 // Bash is the OS-sandbox mode for the bash tool: "enforce" jails each
1134 // command when an OS sandbox is available and refuses bash otherwise; "off"
1135 // runs it unconfined. Empty uses the platform default.
1136 Bash string `toml:"bash"`
1137 // Network allows network egress from inside the bash sandbox. Defaults true
1138 // so module/package downloads keep working; the boundary is then writes.
1139 Network bool `toml:"network"`
1140 }
1141
1142 // WriteRoots returns the directories file-writer tools may modify: the
1143 // workspace root (defaulting to the current working directory when unset), plus
1144 // any AllowWrite extras, with ${VAR} expanded. The roots are returned as given
1145 // (relative or absolute); the confiner resolves them to absolute, symlink-free
1146 // paths. The result is always non-empty, so confinement is on by default.
1147 func (c *Config) WriteRoots() []string {
1148 return c.WriteRootsForRoot(".")
1149 }
1150
1151 // WriteRootsForRoot is like WriteRoots but falls back to fallbackRoot when the
1152 // config doesn't explicitly set a workspace_root. Desktop tabs pass their
1153 // project root here so tool confinement is correct without changing cwd.
1154 func (c *Config) WriteRootsForRoot(fallbackRoot string) []string {
1155 root := c.expandSandboxPath(c.Sandbox.WorkspaceRoot)
1156 if root == "" {
1157 root = fallbackRoot
1158 if root == "" || root == "." {
1159 if wd, err := os.Getwd(); err == nil {
1160 root = wd
1161 } else {
1162 root = "."
1163 }
1164 }
1165 }
1166 roots := []string{root}
1167 for _, d := range c.Sandbox.AllowWrite {
1168 if d = c.expandSandboxPath(d); d != "" {
1169 roots = append(roots, d)
1170 }
1171 }
1172 return roots
1173 }
1174
1175 // AllowWriteRoots returns only the configured [sandbox] allow_write extras with
1176 // ${VAR} expanded — the explicit escape-hatch entries, without the workspace
1177 // root that WriteRoots prepends. The session-data write guard treats these as
1178 // user-sanctioned raw access.
1179 func (c *Config) AllowWriteRoots() []string {
1180 var roots []string
1181 for _, d := range c.Sandbox.AllowWrite {
1182 if d = c.expandSandboxPath(d); d != "" {
1183 roots = append(roots, d)
1184 }
1185 }
1186 return roots
1187 }
1188
1189 // ForbidReadRoots returns the paths the agent is forbidden from reading
1190 // or listing, with ${VAR} expanded. Relative roots are resolved against the
1191 // current working directory; the confiner resolves them to symlink-free paths.
1192 // Empty when no forbid_read entries are configured.
1193 func (c *Config) ForbidReadRoots() []string {
1194 return c.ForbidReadRootsForRoot(".")
1195 }
1196
1197 // ForbidReadRootsForRoot is like ForbidReadRoots but uses fallbackRoot when
1198 // resolving relative paths (for desktop tabs that pass their project root).
1199 func (c *Config) ForbidReadRootsForRoot(fallbackRoot string) []string {
1200 root := fallbackRoot
1201 if root == "" || root == "." {
1202 if wd, err := os.Getwd(); err == nil {
1203 root = wd
1204 } else {
1205 root = "."
1206 }
1207 }
1208 roots := make([]string, 0, len(c.Sandbox.ForbidRead))
1209 for _, d := range c.Sandbox.ForbidRead {
1210 if d = c.expandSandboxPath(d); d != "" {
1211 if !filepath.IsAbs(d) {
1212 d = filepath.Join(root, d)
1213 }
1214 roots = append(roots, d)
1215 }
1216 }
1217 return roots
1218 }
1219
1220 // BashMode normalises the bash-sandbox mode for the current host.
1221 func (c *Config) BashMode() string {
1222 return c.BashModeForGOOS(runtimeGOOS)
1223 }
1224
1225 // BashModeForGOOS normalises the bash-sandbox mode for tests and cross-platform
1226 // rendering. macOS and Linux default to enforcement; backend capability is
1227 // checked at launch and restricted presets fail closed when it is unavailable.
1228 // Windows has no OS-level shell sandbox, so every value resolves to "off":
1229 // an explicit "enforce" stays readable (doctor reports it as ignored) but
1230 // never turns into a fail-closed launch.
1231 func (c *Config) BashModeForGOOS(goos string) string {
1232 if goos == "windows" {
1233 return "off"
1234 }
1235 switch strings.TrimSpace(c.Sandbox.Bash) {
1236 case "enforce":
1237 return "enforce"
1238 case "off":
1239 return "off"
1240 case "":
1241 return "enforce"
1242 default:
1243 return "enforce"
1244 }
1245 }
1246
1247 // AgentConfig configures the harness loop. PlannerModel is optional: when set
1248 // to another provider's name it enables two-model collaboration, where the
1249 // planner handles low-frequency planning in its own session (kept separate so
1250 // each model's prompt prefix stays cache-stable). SubagentModel is the optional
1251 // default for runAs=subagent skills; SubagentModels overrides it per skill name.
1252 type AgentConfig struct {
1253 SystemPrompt string `toml:"system_prompt"`
1254 SystemPromptFile string `toml:"system_prompt_file"`
1255 // Deprecated compatibility fields. Old TOML and desktop clients may still
1256 // send them, but config loading normalizes both to zero and rendering omits
1257 // them. One-off CLI and unattended bot limits remain separate controls.
1258 MaxSteps int `toml:"max_steps"`
1259 PlannerMaxSteps int `toml:"planner_max_steps"`
1260 Temperature float64 `toml:"temperature"`
1261 PlannerModel string `toml:"planner_model"`
1262 WebSearchModel string `toml:"web_search_model"` // empty or auto preserves automatic search selection
1263 // VisionModel is empty (off), "auto", or a canonical provider/model ref
1264 // used to summarize images before a text-only executor turn.
1265 VisionModel string `toml:"vision_model"`
1266 GuardianModel string `toml:"guardian_model"`
1267 GuardianTemperature float64 `toml:"guardian_temperature"`
1268 // RecoveryModel is decoded from old configurations for compatibility. The
1269 // Auto Guard reviewer is retired, so runtime and renderers ignore it.
1270 RecoveryModel string `toml:"recovery_model"`
1271 // RecoveryTemperature is accepted from older configs but ignored. Auto
1272 // Guard review is deterministic at temperature zero.
1273 RecoveryTemperature float64 `toml:"recovery_temperature"`
1274 SubagentModel string `toml:"subagent_model"`
1275 SubagentModels map[string]string `toml:"subagent_models"`
1276 SubagentEffort string `toml:"subagent_effort"`
1277 SubagentEfforts map[string]string `toml:"subagent_efforts"`
1278 MaxSubagentDepth int `toml:"max_subagent_depth"`
1279 // TaskCostBudget lands a task on one summary once it spends this much.
1280 TaskCostBudget float64 `toml:"task_cost_budget"`
1281 // TaskTimeBudgetMinutes is the same gate on wall clock. Both ship off.
1282 TaskTimeBudgetMinutes float64 `toml:"task_time_budget_minutes"`
1283 // GoalTokenBudget bounds an unattended Goal loop by cumulative tokens.
1284 // Off unless set: a Goal runs until it finishes or you stop it.
1285 GoalTokenBudget int `toml:"goal_token_budget"`
1286 // MaxSubagentConcurrency bounds how many sub-agents (task, fleet items,
1287 // profile skills, nested children) may run at once in one session.
1288 // 0 means the default (6). Values outside 1–32 are clamped on load.
1289 MaxSubagentConcurrency int `toml:"max_subagent_concurrency"`
1290 // MaxParallelWriters bounds concurrent writer-capable sub-agents that
1291 // declare non-overlapping write_paths. 0 means the default (3). Must not
1292 // exceed MaxSubagentConcurrency after normalization.
1293 MaxParallelWriters int `toml:"max_parallel_writers"`
1294 // OutputStyle selects a persona/tone block folded into the system prompt at
1295 // startup (a built-in like "explanatory"/"learning"/"concise", or a custom
1296 // .reasonix/output-styles/<name>.md). Empty = the unmodified prompt.
1297 OutputStyle string `toml:"output_style"`
1298 // Deprecated compatibility field. Automatic plan mode was retired in config
1299 // version 5; old TOML remains readable, but loading normalizes it to "off"
1300 // and rendering omits it. Plan mode remains available as an explicit user
1301 // choice.
1302 AutoPlan string `toml:"auto_plan"`
1303 // ReasoningLanguage controls the preferred language for visible reasoning
1304 // text. Empty/auto follows the conversation language. Applied as transient
1305 // turn context, not the stable prompt.
1306 ReasoningLanguage string `toml:"reasoning_language"`
1307 // Deprecated compatibility field paired with AutoPlan. Old TOML remains
1308 // readable, but loading clears it and rendering omits it.
1309 AutoPlanClassifier string `toml:"auto_plan_classifier"`
1310 // Soft/snip/force are retired compatibility keys; only CompactRatio is active.
1311 SoftCompactRatio float64 `toml:"soft_compact_ratio"`
1312 ToolResultSnipRatio float64 `toml:"tool_result_snip_ratio"`
1313 CompactRatio float64 `toml:"compact_ratio"`
1314 CompactForceRatio float64 `toml:"compact_force_ratio"`
1315 // ContextEditing is retired; native tool clearing is no longer an auto path.
1316 ContextEditing string `toml:"context_editing"`
1317 // Keep and RecentKeep are deprecated compatibility fields. They remain
1318 // readable and writable but Harness-style compaction ignores them.
1319 Keep []string `toml:"keep"`
1320 RecentKeep int `toml:"recent_keep"`
1321 // ColdResumePrune elides stale tool results when a session reopens past the
1322 // provider cache window. nil = default enabled.
1323 ColdResumePrune *bool `toml:"cold_resume_prune"`
1324 // PlanModeReadOnlyCommands is retained for old config/session round trips. Main
1325 // Plan bash calls now use the ordinary Permissions classifier and Sandbox.
1326 PlanModeReadOnlyCommands []string `toml:"plan_mode_read_only_commands"`
1327 LegacyAnchorSafetyGate bool `toml:"legacy_anchor_safety_gate"` // retired; decoded for compatibility and ignored
1328 CompletionValidation string `toml:"completion_validation"` // retired; retained for old config reads
1329 CompletionEvaluatorModel string `toml:"completion_evaluator_model"` // retired; ignored
1330 }
1331
1332 // ProviderEntry declares a model provider instance. ContextWindow is the model's
1333 // token budget; the harness compacts older history as a turn's prompt approaches
1334 // it (see agent compaction). 0 disables compaction for the instance.
1335 type ProviderEntry struct {
1336 DisplayName string `toml:"display_name,omitempty"` // UI label; Name remains the stable routing identity.
1337 Name string `toml:"name"`
1338 Kind string `toml:"kind"`
1339 BaseURL string `toml:"base_url"`
1340 ChatURL string `toml:"chat_url"` // legacy OpenAI chat endpoint override; retained with its historical semantics
1341 RequestURL string `toml:"request_url"` // exact provider request URL written by current settings UI
1342 Model string `toml:"model"` // a single model (back-compat)
1343 Models []string `toml:"models"` // a vendor's model list (one base_url/key, many models)
1344 ModelsURL string `toml:"models_url"` // auto-fetch models from this URL on startup
1345 Default string `toml:"default"` // default model when Models is set (else Models[0])
1346 APIKeyEnv string `toml:"api_key_env"`
1347 PresetID string `toml:"preset_id"` // curated preset identity; UI-only metadata, not sent to model providers.
1348 PresetVersion int `toml:"preset_version"` // curated preset schema version for future migrations.
1349 Headers map[string]string `toml:"headers"` // optional extra HTTP headers for compatible gateways; secrets should stay in api_key_env.
1350 ExtraBody map[string]any `toml:"extra_body"` // optional extra top-level JSON request body fields for OpenAI-compatible gateways.
1351 AuthHeader bool `toml:"auth_header"` // for Anthropic-compatible gateways that expect Authorization: Bearer instead of x-api-key.
1352 // ResponsesMode selects the Responses API context strategy. Empty preserves
1353 // vendor detection; DeepSeek is stateless while compatible endpoints may use
1354 // stateful previous_response_id continuation.
1355 ResponsesMode string `toml:"responses_mode"`
1356 // ResponsesStateful is the legacy boolean form retained for config
1357 // compatibility. ResponsesMode wins when both are present.
1358 ResponsesStateful *bool `toml:"responses_stateful"`
1359 resolvedAPIKey string
1360 credentialsFrozen bool
1361 credentialProxyURL string // runtime-only loopback transport, never persisted
1362 resolvedSource CredentialSource
1363 BalanceURL string `toml:"balance_url"` // optional; a provider-specific wallet-balance endpoint (DeepSeek: https://api.deepseek.com/user/balance). Empty = no balance readout.
1364 ContextWindow int `toml:"context_window"`
1365 // MaxOutputTokens is a protocol-neutral total output budget for one turn.
1366 // Zero means official DeepSeek omits the field (server 384K ceiling) and
1367 // other vendors keep their own defaults. Effort selects thinking depth only.
1368 // A positive value is an explicit cost cap. A negative value omits optional
1369 // wire limits when the protocol allows; official DeepSeek Anthropic still
1370 // sends 384K because max_tokens is mandatory. Never feeds compact_ratio.
1371 MaxOutputTokens int `toml:"max_output_tokens"`
1372 Price *provider.Pricing `toml:"price"` // legacy/provider-wide fallback
1373 Prices map[string]*provider.Pricing `toml:"prices"` // optional per-model prices; keys are model ids
1374 // BillingCurrency is the frozen list-price currency (ISO-4217). Independent
1375 // of [billing].display_currency; switching display never rewrites this.
1376 BillingCurrency string `toml:"billing_currency"`
1377 // BillingMode is payg (default) or subscription_equivalent (e.g. MiMo Token Plan).
1378 BillingMode string `toml:"billing_mode"`
1379
1380 persistedOfficialCurrency string
1381
1382 // Thinking / Effort are provider-kind-specific knobs forwarded to the provider
1383 // via Config.Extra. The anthropic provider reads Thinking="adaptive" to enable
1384 // extended thinking and Effort ("low".."max") to tune depth. The
1385 // openai-compatible provider forwards Effort as reasoning_effort for
1386 // thinking-capable models; DeepSeek V4 Flash accepts low|high|max while
1387 // other DeepSeek models retain their model-specific capability mapping.
1388 // Empty = provider default.
1389 Thinking string `toml:"thinking"`
1390 Effort string `toml:"effort"`
1391 // Vision marks the model as accepting image input. When set, images the user
1392 // attaches are embedded in the request (image_url for openai-kind, base64
1393 // blocks for anthropic). Off by default: text-only models 400 on image input,
1394 // and image tokens are heavy — gating keeps text-only flows cheap (the prompt
1395 // prefix is byte-identical with no image, so the cache is unaffected either way).
1396 Vision bool `toml:"vision"`
1397 // VisionModels is legacy; new settings use model-level ModelOverrides.Vision.
1398 // Keep this field readable for existing configurations.
1399 VisionModels []string `toml:"vision_models"`
1400 // VisionDetail sets the openai image_url detail hint (low|high); empty = auto
1401 // (the field is omitted). "low" caps an image to a fixed ~85 tokens for cheap
1402 // coarse reads; ignored by providers without the knob (e.g. anthropic).
1403 VisionDetail string `toml:"vision_detail"`
1404 // WebSearch enables independent search with this account. Nil uses the
1405 // official DeepSeek default; explicit values and legacy native search
1406 // history survive config rewrites.
1407 WebSearch *bool `toml:"web_search"`
1408 // ReasoningProtocol selects the request shape for OpenAI-compatible reasoning
1409 // models. Empty/auto uses the model capability registry plus endpoint
1410 // heuristics. Explicit values select DeepSeek, GLM, Kimi K3, or standard
1411 // OpenAI reasoning contracts; none disables automatic reasoning controls.
1412 ReasoningProtocol string `toml:"reasoning_protocol"`
1413 // SupportedEfforts lists the /effort levels this provider/model exposes.
1414 // Non-empty values override built-in Kind/BaseURL defaults except for fixed
1415 // Kimi K3 reasoning. "auto" is the implicit prefix — always accepted.
1416 // DefaultEffort resolves it; omit DefaultEffort (or set one outside this
1417 // list) to fall back to SupportedEfforts[0].
1418 SupportedEfforts []string `toml:"supported_efforts"`
1419 // DefaultEffort is the /effort level used when the user picks "auto" or
1420 // has not set Effort. Ignored for empty SupportedEfforts or fixed Kimi K3.
1421 DefaultEffort string `toml:"default_effort"`
1422 reasoningAutomatic bool // runtime-only vocabulary provenance; never persisted
1423 reasoningProtocolAutomatic bool
1424 reasoningDefaultAutomatic bool
1425 ReasoningMetadataUnknown bool `toml:"-" json:"-"` // resolver-backed metadata only
1426 // ModelOverrides customizes capability metadata after ResolveModel selects a
1427 // concrete model from a multi-model provider. Use it when a gateway exposes
1428 // mixed DeepSeek/OpenAI/no-reasoning or mixed vision/text models under one
1429 // base_url/key.
1430 ModelOverrides map[string]ProviderModelOverride `toml:"model_overrides"`
1431 visionOverride *bool
1432 // NoProxy reaches this provider's base_url directly, never through the proxy.
1433 // For China-only endpoints a foreign-exit proxy resets the TLS handshake (#2803).
1434 NoProxy bool `toml:"no_proxy"`
1435 // CacheTTLMinutes overrides the vendor-default prefix-cache retention used by
1436 // cold-resume prune. Zero uses the vendor default (DeepSeek/unknown 24h, DashScope/Anthropic 5m).
1437 CacheTTLMinutes int `toml:"cache_ttl_minutes"`
1438 }
1439
1440 // ModelList returns the models this provider exposes: the explicit `models` list,
1441 // or the single `model` as a one-element list (back-compat). Empty if neither set.
1442 func (e *ProviderEntry) ModelList() []string {
1443 if len(e.Models) > 0 {
1444 return e.Models
1445 }
1446 if e.Model != "" {
1447 return []string{e.Model}
1448 }
1449 return nil
1450 }
1451
1452 // IsLikelyChatModel reports whether a model ID looks like a chat/completion
1453 // model rather than a specialised audio/vision/embedding model. It applies a
1454 // conservative name-based heuristic — the OpenAI-compatible /models API does
1455 // not return capability/modality metadata, so this is the most reliable
1456 // fallback until providers add such fields.
1457 //
1458 // The heuristic works in two passes:
1459 // 1. Multi-word substring check for compound terms that span separators
1460 // (e.g. "text-embedding", "text-to-speech").
1461 // 2. Token-level check: the model ID is split on common separators (- _ . / :)
1462 // and each token is compared against a set of known non-chat keywords.
1463 //
1464 // "voice" is intentionally absent from the non-chat set because it is too
1465 // broad — legitimate future chat models may include it in their name.
1466 func IsLikelyChatModel(model string) bool {
1467 model = strings.TrimSpace(model)
1468 if model == "" {
1469 return false
1470 }
1471 lower := strings.ToLower(model)
1472
1473 // Pass 1: compound terms that span separator boundaries.
1474 var compoundNonChat = []string{
1475 "text-embedding", "text-to-speech", "speech-to-text",
1476 }
1477 for _, c := range compoundNonChat {
1478 if strings.Contains(lower, c) {
1479 return false
1480 }
1481 }
1482
1483 // Pass 2: token-level check.
1484 tokens := strings.FieldsFunc(lower, func(r rune) bool {
1485 return r == '-' || r == '_' || r == '.' || r == '/' || r == ':'
1486 })
1487 var nonChatTokens = map[string]bool{
1488 "asr": true, "stt": true, "tts": true,
1489 "whisper": true, "embedding": true,
1490 "moderation": true, "rerank": true, "dall": true,
1491 "transcription": true,
1492 }
1493 for _, tok := range tokens {
1494 if nonChatTokens[tok] {
1495 return false
1496 }
1497 }
1498 return true
1499 }
1500
1501 // ChatModelList returns ModelList filtered to likely chat/completion models.
1502 // Non-chat models (TTS, STT, ASR, embedding, etc.) are excluded so they do
1503 // not appear in the chat model picker. Use ModelList() only when the full
1504 // raw provider model list is needed, such as config serialization, provider
1505 // diagnostics, or model-fetch editing.
1506 func (e *ProviderEntry) ChatModelList() []string {
1507 raw := e.ModelList()
1508 if len(raw) == 0 {
1509 return nil
1510 }
1511 out := make([]string, 0, len(raw))
1512 for _, m := range raw {
1513 if IsLikelyChatModel(m) {
1514 out = append(out, m)
1515 }
1516 }
1517 return out
1518 }
1519
1520 // DefaultModel returns the provider's default model: the explicit `default`, else
1521 // the first of ModelList.
1522 func (e *ProviderEntry) DefaultModel() string {
1523 if e.Default != "" {
1524 return e.Default
1525 }
1526 if l := e.ModelList(); len(l) > 0 {
1527 return l[0]
1528 }
1529 return ""
1530 }
1531
1532 // HasModel reports whether m is one of the provider's models.
1533 func (e *ProviderEntry) HasModel(m string) bool {
1534 return slices.Contains(e.ModelList(), m)
1535 }
1536
1537 // PriceForModel returns the configured per-1M-token price for model. Per-model
1538 // prices win; the legacy provider-wide price is a fallback for older configs.
1539 func (e *ProviderEntry) PriceForModel(model string) *provider.Pricing {
1540 if e == nil {
1541 return nil
1542 }
1543 if e.Prices != nil {
1544 if p := e.Prices[strings.TrimSpace(model)]; p != nil {
1545 return clonePricing(p)
1546 }
1547 }
1548 return clonePricing(e.Price)
1549 }
1550
1551 func (e *ProviderEntry) applyModelPrice() {
1552 if e == nil {
1553 return
1554 }
1555 e.Price = e.PriceForModel(e.Model)
1556 }
1557
1558 func (e *ProviderEntry) applyModelOverride() {
1559 if e == nil || len(e.ModelOverrides) == 0 {
1560 return
1561 }
1562 ov, ok := e.modelOverrideForModel(e.Model)
1563 if !ok {
1564 return
1565 }
1566 if ov.ReasoningProtocol != "" {
1567 e.reasoningProtocolAutomatic = false
1568 e.ReasoningProtocol = ov.ReasoningProtocol
1569 }
1570 if ov.SupportedEfforts != nil {
1571 e.reasoningAutomatic = false
1572 e.SupportedEfforts = append([]string(nil), ov.SupportedEfforts...)
1573 }
1574 if ov.DefaultEffort != "" || ov.SupportedEfforts != nil {
1575 e.reasoningDefaultAutomatic = false
1576 e.DefaultEffort = ov.DefaultEffort
1577 }
1578 if ov.Vision != nil {
1579 e.visionOverride = ov.Vision
1580 }
1581 if ov.ContextWindow > 0 {
1582 e.ContextWindow = ov.ContextWindow
1583 }
1584 if ov.MaxOutputTokens != 0 {
1585 e.MaxOutputTokens = ov.MaxOutputTokens
1586 }
1587 }
1588
1589 func (e *ProviderEntry) modelOverrideForModel(model string) (ProviderModelOverride, bool) {
1590 model = strings.TrimSpace(model)
1591 if e == nil || model == "" || len(e.ModelOverrides) == 0 {
1592 return ProviderModelOverride{}, false
1593 }
1594 if ov, ok := e.ModelOverrides[model]; ok {
1595 return explicitModelReasoning(ov), true
1596 }
1597 return ProviderModelOverride{}, false
1598 }
1599
1600 func clonePricing(p *provider.Pricing) *provider.Pricing {
1601 if p == nil {
1602 return nil
1603 }
1604 cp := *p
1605 return &cp
1606 }
1607
1608 // ToolsConfig selects which built-in tools are enabled. Empty means all of them.
1609 type ToolsConfig struct {
1610 Enabled []string `toml:"enabled"`
1611 BashTimeoutSeconds *int `toml:"bash_timeout_seconds"`
1612 MCPStartupTimeoutSeconds *int `toml:"mcp_startup_timeout_seconds"`
1613 MCPCallTimeoutSeconds *int `toml:"mcp_call_timeout_seconds"`
1614 BackgroundJobs BackgroundJobsConfig `toml:"background_jobs"`
1615 Search SearchConfig `toml:"search"`
1616 Shell ShellConfig `toml:"shell"`
1617 }
1618
1619 const (
1620 defaultBashTimeoutSeconds = 120
1621 defaultMCPStartupTimeoutSeconds = 30
1622 defaultMCPCallTimeoutSeconds = 300
1623 defaultBackgroundJobStalledWarningSec = 900
1624 maxBackgroundJobStalledWarningSec = 86400
1625 )
1626
1627 // BashTimeoutSeconds returns the foreground bash timeout in seconds. An omitted
1628 // config keeps the historical 120s safety cap, explicit 0 disables the
1629 // tool-local cap, and positive values set a custom cap. Negative values fall
1630 // back to the default so a typo cannot silently remove the safety net.
1631 func (c *Config) BashTimeoutSeconds() int {
1632 if c.Tools.BashTimeoutSeconds == nil || *c.Tools.BashTimeoutSeconds < 0 {
1633 return defaultBashTimeoutSeconds
1634 }
1635 return *c.Tools.BashTimeoutSeconds
1636 }
1637
1638 // MCPCallTimeoutSeconds returns the default MCP JSON-RPC call timeout in
1639 // seconds. Omitted, zero, and negative values keep the built-in safety cap so a
1640 // hung MCP server cannot block a turn indefinitely.
1641 func (c *Config) MCPCallTimeoutSeconds() int {
1642 if c.Tools.MCPCallTimeoutSeconds == nil || *c.Tools.MCPCallTimeoutSeconds <= 0 {
1643 return defaultMCPCallTimeoutSeconds
1644 }
1645 return *c.Tools.MCPCallTimeoutSeconds
1646 }
1647
1648 // MCPStartupTimeoutSeconds returns the background initialize + tools/list
1649 // safety cap. Omitted, zero, and negative values keep the built-in default so
1650 // a slow but healthy MCP can outlive the short interactive wait without running
1651 // indefinitely.
1652 func (c *Config) MCPStartupTimeoutSeconds() int {
1653 if c.Tools.MCPStartupTimeoutSeconds == nil || *c.Tools.MCPStartupTimeoutSeconds <= 0 {
1654 return defaultMCPStartupTimeoutSeconds
1655 }
1656 return *c.Tools.MCPStartupTimeoutSeconds
1657 }
1658
1659 // BackgroundJobsConfig tunes parent-created background jobs.
1660 type BackgroundJobsConfig struct {
1661 StalledWarningSeconds *int `toml:"stalled_warning_seconds"`
1662 }
1663
1664 // BackgroundJobStalledWarningSeconds returns the stalled warning threshold in
1665 // seconds. Omitted/negative values keep the default, explicit 0 disables the
1666 // notice, and oversized values clamp to one day so a typo cannot become
1667 // effectively invisible.
1668 func (c *Config) BackgroundJobStalledWarningSeconds() int {
1669 if c.Tools.BackgroundJobs.StalledWarningSeconds == nil || *c.Tools.BackgroundJobs.StalledWarningSeconds < 0 {
1670 return defaultBackgroundJobStalledWarningSec
1671 }
1672 if *c.Tools.BackgroundJobs.StalledWarningSeconds > maxBackgroundJobStalledWarningSec {
1673 return maxBackgroundJobStalledWarningSec
1674 }
1675 return *c.Tools.BackgroundJobs.StalledWarningSeconds
1676 }
1677
1678 // SearchConfig tunes the grep tool's engine. Engine is "auto" (default — use
1679 // ripgrep when it's on PATH, else the native Go scanner), "native" (always Go),
1680 // or "rg" (require ripgrep; warn at startup and fall back to native if absent).
1681 // RgPath optionally points at a specific ripgrep binary instead of a PATH lookup.
1682 type SearchConfig struct {
1683 Engine string `toml:"engine"`
1684 RgPath string `toml:"rg_path"`
1685 }
1686
1687 // ShellConfig chooses the interpreter the bash tool runs commands under. Prefer
1688 // is "auto" (default — real bash when present, else PowerShell on Windows),
1689 // "bash", or "powershell"/"pwsh" (force it; warn at startup and fall back to
1690 // auto if absent). Path optionally points at a specific shell executable.
1691 type ShellConfig struct {
1692 Prefer string `toml:"prefer"`
1693 Path string `toml:"path"`
1694 }
1695
1696 // PermissionsConfig declares the per-call permission policy (see
1697 // internal/permission). Mode is the fallback decision for writer tools when no
1698 // rule matches ("ask" | "allow" | "deny"; default "ask"); read-only tools always
1699 // fall back to allow. Allow/Ask/Deny are rule lists of the form "ToolName" or
1700 // "ToolName(glob)". Precedence: deny > ask > allow > fallback.
1701 type PermissionsConfig struct {
1702 Mode string `toml:"mode"`
1703 Allow []string `toml:"allow"`
1704 Ask []string `toml:"ask"`
1705 Deny []string `toml:"deny"`
1706 AllowDynamicBash bool `toml:"allow_dynamic_bash"`
1707 }
1708
1709 // MCPConfigSource records where a merged MCP entry came from. It is runtime
1710 // provenance only and is never serialized back into TOML or .mcp.json.
1711 type MCPConfigSource string
1712
1713 const (
1714 MCPSourceUnknown MCPConfigSource = ""
1715 MCPSourceUserConfig MCPConfigSource = "user_config"
1716 MCPSourceProjectConfig MCPConfigSource = "project_config"
1717 MCPSourceProjectMCPJSON MCPConfigSource = "project_mcp_json"
1718 MCPSourceLegacyUser MCPConfigSource = "legacy_user_config"
1719 MCPSourcePluginPackage MCPConfigSource = "plugin_package"
1720 )
1721
1722 func (s MCPConfigSource) UserAuthorized() bool {
1723 switch s {
1724 case MCPSourceUserConfig, MCPSourceLegacyUser, MCPSourcePluginPackage,
1725 MCPSourceProjectConfig, MCPSourceProjectMCPJSON:
1726 return true
1727 default:
1728 return false
1729 }
1730 }
1731
1732 // ProjectScoped reports whether an MCP entry belongs to one workspace. Its
1733 // activation is keyed per workspace, and it stays disabled until the user
1734 // records a decision there.
1735 func (s MCPConfigSource) ProjectScoped() bool {
1736 return s == MCPSourceProjectConfig || s == MCPSourceProjectMCPJSON
1737 }
1738
1739 func (e PluginEntry) ShouldAutoStart() bool {
1740 return e.AutoStart == nil || *e.AutoStart
1741 }
1742
1743 // ResolvedTier returns the normalized tier ("eager"|"background") with the
1744 // project default applied. Legacy lazy and unknown values fall back to
1745 // background so enabled MCPs are available without manual connection.
1746 //
1747 // Tier no longer changes runtime process start timing; it remains for config
1748 // compatibility and diagnostics only.
1749 func (e PluginEntry) ResolvedTier() string {
1750 return resolvedMCPTier(e.Tier)
1751 }
1752
1753 func resolvedMCPTier(tier string) string {
1754 switch strings.ToLower(strings.TrimSpace(tier)) {
1755 case "eager":
1756 return "eager"
1757 case "background", "lazy":
1758 return "background"
1759 case "":
1760 return "background"
1761 default:
1762 return "background"
1763 }
1764 }
1765
1766 // AutoStartPlugins returns enabled MCP entries for the catalog. Durable
1767 // overrides in mcp-activation.json win over auto_start; without one a
1768 // project-declared server is disabled. Enabled servers register cached tools
1769 // and start on the first real tool call, not at session boot.
1770 func (c *Config) AutoStartPlugins() []PluginEntry {
1771 return c.EnabledPlugins("", DefaultMCPActivationStore())
1772 }
1773
1774 // EnabledPlugins returns catalog-enabled MCP entries for workspace, consulting
1775 // the activation store when provided.
1776 func (c *Config) EnabledPlugins(workspace string, activation *MCPActivationStore) []PluginEntry {
1777 if c == nil {
1778 return nil
1779 }
1780 out := make([]PluginEntry, 0, len(c.Plugins))
1781 for _, p := range c.Plugins {
1782 enabled := DeclaredDefaultOn(p)
1783 if activation != nil {
1784 if resolved, err := activation.IsEnabled(p, workspace); err == nil {
1785 enabled = resolved
1786 }
1787 }
1788 if enabled {
1789 out = append(out, p)
1790 }
1791 }
1792 return out
1793 }
1794
1795 // DefaultSystemPrompt is used when config provides none.
1796 const DefaultSystemPrompt = `You are Reasonix, a coding agent.
1797 Use the available tools when they help you complete the user's request.
1798 Keep changes focused and responses concise.`
1799
1800 // UserDecisionPolicy is appended to every system prompt, including user-custom
1801 // prompts, so custom personas cannot accidentally remove the `ask` UI contract.
1802 const UserDecisionPolicy = `User-owned choices: when a consequential decision has no safe, obvious default, call the ask tool so the user can choose. Otherwise proceed with a sensible reversible default. Do not ask in prose when ask is available. In non-interactive runs, state the assumption and take the safest reversible path.`
1803
1804 // LanguagePolicy is the auto fallback appended to the system prompt when no
1805 // concrete UI language is resolved. It is static English text, so it stays part
1806 // of the cache-stable prefix and avoids per-turn language injection.
1807 const LanguagePolicy = `Reply in the same language the user is using in their most recent message: ` +
1808 `if they write in Chinese answer in Chinese, in English answer in English, and switch ` +
1809 `whenever they switch. Let this also guide the language you think in. Always keep code, ` +
1810 `identifiers, file paths, shell commands, and technical terms in their original form — never translate them.`
1811
1812 // Default returns the built-in default configuration.
1813 func Default() *Config {
1814 return &Config{
1815 ConfigVersion: openCodeGoInferenceUpgradeVersion,
1816 DefaultModel: "deepseek-flash",
1817 CredentialsStore: CredentialsStoreAuto,
1818 UI: UIConfig{Theme: "auto", ShowTurnUsage: true},
1819 Desktop: DesktopConfig{DefaultToolApprovalMode: "workspace-write", ConversationWidth: "standard"},
1820 Billing: BillingConfig{},
1821 Notifications: NotificationsConfig{
1822 Enabled: false,
1823 TurnDone: true,
1824 ApprovalRequest: true,
1825 AskRequest: true,
1826 },
1827 Agent: AgentConfig{
1828 SystemPrompt: DefaultSystemPrompt,
1829 // Normal interactive execution has no configurable total round cap. It
1830 // is bounded by adaptive progress guards and context compaction instead.
1831 MaxSteps: 0,
1832 PlannerMaxSteps: 0,
1833 AutoPlan: "off",
1834 // Soft/snip/force are load-only compatibility; CompactRatio alone drives maintenance.
1835 SoftCompactRatio: 0,
1836 ToolResultSnipRatio: 0,
1837 CompactRatio: 0.80,
1838 CompactForceRatio: 0,
1839 ContextEditing: "",
1840 MaxSubagentDepth: 2,
1841 MaxSubagentConcurrency: 6,
1842 MaxParallelWriters: 3,
1843 },
1844 // The policy fallback remains an internal rule-engine input. The active
1845 // PermissionPreset supplies the user-facing execution posture, while
1846 // explicit deny/ask/allow rules remain authoritative refinements.
1847 Permissions: PermissionsConfig{Mode: "ask"},
1848 // Restricted permission presets select the platform sandbox at runtime:
1849 // Seatbelt on macOS, bubblewrap on Linux, and the restricted-token helper
1850 // on Windows. Network=true preserves normal egress inside that boundary.
1851 Sandbox: SandboxConfig{Network: true},
1852 // LSP tools on by default, but dormant until a language server is on PATH;
1853 // a missing server yields an install hint rather than an error.
1854 LSP: LSPConfig{Enabled: true},
1855 Network: NetworkConfig{ProxyMode: netclient.ModeAuto},
1856 Bot: BotConfig{
1857 ToolApprovalMode: "workspace-write",
1858 MaxSteps: 0,
1859 DebounceMs: 1500,
1860 QueueMode: "steer",
1861 QueueCap: 20,
1862 QueueDrop: "summarize",
1863 IgnoreSelfMessages: true,
1864 Control: BotControlConfig{Addr: "127.0.0.1:37913", TokenEnv: "REASONIX_BOT_CONTROL_TOKEN"},
1865 Pairing: BotPairingConfig{Enabled: true, RequestTTLMinutes: 60, MaxPendingPerPlatform: 3},
1866 Allowlist: BotAllowlist{Enabled: true},
1867 QQ: QQBotConfig{AppSecretEnv: "QQ_BOT_APP_SECRET"},
1868 Feishu: FeishuBotConfig{Domain: "feishu", AppSecretEnv: "FEISHU_BOT_APP_SECRET", Mode: "webhook", WebhookPort: 8080, RequireMention: true},
1869 Dingtalk: DingtalkBotConfig{RequireMention: true},
1870 Weixin: WeixinBotConfig{AccountID: "default", TokenEnv: "WEIXIN_BOT_TOKEN", APIBase: "https://ilinkai.weixin.qq.com"},
1871 },
1872 // Main conversations use Chat Completions; independent web_search uses
1873 // the official Messages endpoint with the same account.
1874 Providers: []ProviderEntry{
1875 {
1876 Name: "deepseek-flash", Kind: "openai", BaseURL: "https://api.deepseek.com",
1877 Model: "deepseek-flash", APIKeyEnv: "DEEPSEEK_API_KEY",
1878 BalanceURL: "https://api.deepseek.com/user/balance", Thinking: "enabled",
1879 WebSearch: boolPointer(true), SupportedEfforts: []string{"disabled", "low", "high", "max"}, DefaultEffort: "high",
1880 ContextWindow: 1_000_000, Price: deepSeekV4FlashPriceUSD(),
1881 BillingCurrency: "USD", BillingMode: "payg",
1882 },
1883 {
1884 Name: "deepseek-pro", Kind: "openai", BaseURL: "https://api.deepseek.com",
1885 Model: "deepseek-v4-pro", APIKeyEnv: "DEEPSEEK_API_KEY",
1886 BalanceURL: "https://api.deepseek.com/user/balance", Thinking: "enabled",
1887 WebSearch: boolPointer(true), SupportedEfforts: []string{"disabled", "low", "high", "max"}, DefaultEffort: "high",
1888 ContextWindow: 1_000_000, Price: deepSeekV4ProPriceUSD(),
1889 BillingCurrency: "USD", BillingMode: "payg",
1890 },
1891 },
1892 }
1893 }
1894
1895 // WriteFile writes the configuration to path as annotated TOML. The write is
1896 // atomic + fsynced so an interrupted write or power loss can never truncate the
1897 // main config into an unparseable state that leaves the app with no usable
1898 // models (#4615, #4708).
1899 func (c *Config) WriteFile(path string) error {
1900 return atomicWriteToConfigFile(path, RenderTOMLForScope(c, renderScopeForPath(path)), configFilePerm(path))
1901 }
1902
1903 // Provider returns the named provider entry.
1904 func (c *Config) Provider(name string) (*ProviderEntry, bool) {
1905 for i := range c.Providers {
1906 if c.Providers[i].Name == name {
1907 return &c.Providers[i], true
1908 }
1909 }
1910 return nil, false
1911 }
1912
1913 // ResolveModel resolves a model reference to a provider entry whose Model is the
1914 // selected model string (a copy, so the config's lists stay intact). It accepts:
1915 // - "provider/model" — that exact model under that provider;
1916 // - a provider name — the provider's default model;
1917 // - a bare model name — the (first) provider that lists it.
1918 //
1919 // The returned entry is ready to build a provider from (NewProvider reads .Model),
1920 // so a single "vendor with many models" entry yields one instance per model
1921 // without duplicating base_url/api_key_env. Single-`model` entries still resolve
1922 // by provider name, keeping older configs working unchanged.
1923 func (c *Config) ResolveModel(ref string) (*ProviderEntry, bool) {
1924 if entry, ok := c.resolveCurrentModel(ref); ok {
1925 return entry, true
1926 }
1927 target, err := c.resolveOpenCodeGoAlias(ref, false)
1928 if err != nil || target == ref {
1929 return nil, false
1930 }
1931 return c.resolveCurrentModel(target)
1932 }
1933
1934 func (c *Config) resolveCurrentModel(ref string) (*ProviderEntry, bool) {
1935 if ref == "" {
1936 return nil, false
1937 }
1938 if access := desktopProviderAccessMap(c.Desktop.ProviderAccess); len(access) > 0 {
1939 if access["deepseek"] && !canCanonicalizeLegacyDeepSeekProviders(c) {
1940 delete(access, "deepseek")
1941 }
1942 ref = retargetDesktopOfficialRef(ref, access)
1943 }
1944 // "provider/model"
1945 if prov, model, ok := strings.Cut(ref, "/"); ok {
1946 if e, found := c.Provider(prov); found && acceptsDeepSeekModelReference(e, model) {
1947 cp := *e
1948 cp.Model = model
1949 cp.applyModelPrice()
1950 cp.applyModelOverride()
1951 return ResolveReasoningEntry(&cp), true
1952 }
1953 }
1954 // a provider name → its default model
1955 if e, found := c.Provider(ref); found {
1956 cp := *e
1957 cp.Model = e.DefaultModel()
1958 cp.applyModelPrice()
1959 cp.applyModelOverride()
1960 return ResolveReasoningEntry(&cp), true
1961 }
1962 // a bare model name → the provider that lists it
1963 for i := range c.Providers {
1964 if acceptsDeepSeekModelReference(&c.Providers[i], ref) {
1965 cp := c.Providers[i]
1966 cp.Model = ref
1967 cp.applyModelPrice()
1968 cp.applyModelOverride()
1969 return ResolveReasoningEntry(&cp), true
1970 }
1971 }
1972 return nil, false
1973 }
1974
1975 // ResolveModelWithFallback resolves a model reference to the canonical
1976 // "provider/model" form used by the desktop runtime. If ref is stale or empty,
1977 // it tries the user's configured default_model before falling back to the first
1978 // configured provider — so preference isn't overwritten by iteration order.
1979 func (c *Config) ResolveModelWithFallback(ref string) (resolvedRef string, fallback bool, ok bool) {
1980 ref = strings.TrimSpace(ref)
1981 if c.ModelReferenceError(ref) != nil {
1982 return "", false, false
1983 }
1984 if ref != "" {
1985 if e, found := c.ResolveModel(ref); found {
1986 return e.Name + "/" + e.Model, false, true
1987 }
1988 }
1989 // Before falling back to the first configured provider (which may not be the
1990 // user's preferred choice), try the configured default_model. Skip when ref
1991 // already WAS the DefaultModel (it already failed above, so retrying won't
1992 // help) or when the default provider has no API key configured.
1993 if ref != c.DefaultModel && c.DefaultModel != "" {
1994 if e, found := c.ResolveModel(c.DefaultModel); found && e.Configured() {
1995 return e.Name + "/" + e.Model, true, true
1996 }
1997 }
1998 for i := range c.Providers {
1999 p := &c.Providers[i]
2000 // Skip providers with no models or no API key: falling back onto a keyless
2001 // provider just boots the tab onto something that fails on first use. Mirrors
2002 // the Configured() gate the provider-removal/selection paths already apply.
2003 if len(p.ModelList()) == 0 || !p.Configured() {
2004 continue
2005 }
2006 return p.Name + "/" + p.DefaultModel(), true, true
2007 }
2008 return "", false, false
2009 }
2010
2011 // ResolveNewSessionChatModel selects the model for a newly-created chat
2012 // session. Configured candidates win; if every chat candidate is keyless, the
2013 // valid default (or first chat model) is preserved so callers can surface their
2014 // existing missing-key recovery UI. An unknown default is also preserved for
2015 // the CLI's actionable configuration error. Provider order is otherwise stable.
2016 func (c *Config) ResolveNewSessionChatModel() (resolvedRef string, fallback bool, ok bool) {
2017 return c.resolveNewSessionChatModel(nil, true)
2018 }
2019
2020 func (c *Config) resolveNewSessionChatModel(providerAllowed func(string) bool, preserveUnknownDefault bool) (resolvedRef string, fallback bool, ok bool) {
2021 if c == nil {
2022 return "", false, false
2023 }
2024 if providerAllowed == nil {
2025 providerAllowed = func(string) bool { return true }
2026 }
2027
2028 def := strings.TrimSpace(c.DefaultModel)
2029 keylessDefault := ""
2030 if def != "" {
2031 if entry, found := c.ResolveModel(def); found {
2032 if providerAllowed(entry.Name) && IsLikelyChatModel(entry.Model) {
2033 if entry.Configured() {
2034 return def, false, true
2035 }
2036 keylessDefault = def
2037 }
2038 } else if preserveUnknownDefault {
2039 // CLI/boot callers need the stale value intact so their existing
2040 // unknown-model error can name it and explain the providers that
2041 // replaced it. Desktop uses its recovery UI and does not preserve it.
2042 return def, false, true
2043 }
2044 }
2045
2046 keylessFallback := ""
2047 for i := range c.Providers {
2048 p := &c.Providers[i]
2049 if !providerAllowed(p.Name) {
2050 continue
2051 }
2052 chatModels := p.ChatModelList()
2053 if len(chatModels) == 0 {
2054 continue
2055 }
2056 model := chatModels[0]
2057 for _, candidate := range chatModels {
2058 if candidate == p.DefaultModel() {
2059 model = candidate
2060 break
2061 }
2062 }
2063 resolved := p.Name + "/" + model
2064 if p.Configured() {
2065 return resolved, true, true
2066 }
2067 if keylessFallback == "" {
2068 keylessFallback = resolved
2069 }
2070 }
2071 if keylessDefault != "" {
2072 return keylessDefault, false, true
2073 }
2074 if keylessFallback != "" {
2075 return keylessFallback, true, true
2076 }
2077 return "", false, false
2078 }
2079
2080 // ResolveDesktopNewSessionModel selects the model for a newly-created desktop
2081 // session. It shares the chat-model fallback policy with other frontends while
2082 // limiting candidates to providers exposed by the desktop access catalog.
2083 func (c *Config) ResolveDesktopNewSessionModel() (resolvedRef string, fallback bool, ok bool) {
2084 if c == nil {
2085 return "", false, false
2086 }
2087 access := desktopProviderAccessMap(c.Desktop.ProviderAccess)
2088 return c.resolveNewSessionChatModel(func(name string) bool {
2089 return c.Desktop.ProviderAccess == nil || access[strings.TrimSpace(name)]
2090 }, false)
2091 }
2092
2093 // APIKey resolves the entry's API key from its api_key_env.
2094 func (e *ProviderEntry) APIKey() string {
2095 if e == nil {
2096 return ""
2097 }
2098 if e.credentialsFrozen || e.resolvedAPIKey != "" {
2099 return e.resolvedAPIKey
2100 }
2101 if e.APIKeyEnv == "" {
2102 return ""
2103 }
2104 value, _, ok := storedCredentialValue(e.APIKeyEnv)
2105 if !ok {
2106 return ""
2107 }
2108 return value
2109 }
2110
2111 // ResolveAPIKeyFromProcessEnvForProbe pins a setup-time, user-entered key onto
2112 // this entry for an immediate connectivity probe. Normal runtime resolution does
2113 // not call this; loaded provider entries still resolve only from Reasonix's
2114 // global .env.
2115 func (e *ProviderEntry) ResolveAPIKeyFromProcessEnvForProbe() {
2116 if e == nil {
2117 return
2118 }
2119 key := strings.TrimSpace(e.APIKeyEnv)
2120 if key == "" {
2121 return
2122 }
2123 value := strings.TrimSpace(os.Getenv(key))
2124 if value == "" {
2125 return
2126 }
2127 e.resolvedAPIKey = value
2128 e.resolvedSource = CredentialSource{Kind: CredentialSourceEnvironment, Label: "setup prompt"}
2129 }
2130
2131 func (e *ProviderEntry) APIKeySourceLabel() string {
2132 if e == nil || strings.TrimSpace(e.APIKeyEnv) == "" {
2133 return ""
2134 }
2135 if e.resolvedAPIKey != "" {
2136 return credentialSourceLabel(e.resolvedSource)
2137 }
2138 return ResolveCredentialForRootGlobalFirst(".", e.APIKeyEnv).Source.Label
2139 }
2140
2141 // RequiresAPIKey reports whether this provider should be hidden/validated when
2142 // its configured api_key_env is empty. A blank api_key_env means the provider is
2143 // intentionally no-auth. Local OpenAI-compatible gateways often keep a legacy
2144 // api_key_env in config even though they accept unauthenticated requests, so
2145 // loopback/private endpoints are also allowed to run without a resolved key.
2146 func (e *ProviderEntry) RequiresAPIKey() bool {
2147 if e == nil {
2148 return false
2149 }
2150 if strings.TrimSpace(e.APIKeyEnv) == "" {
2151 return providerBaseURLRequiresAPIKey(e.BaseURL)
2152 }
2153 return !providerBaseURLAllowsMissingAPIKey(e.BaseURL)
2154 }
2155
2156 func providerBaseURLRequiresAPIKey(raw string) bool {
2157 switch officialProviderHost(raw) {
2158 case "api.deepseek.com", "api.xiaomimimo.com", "token-plan-cn.xiaomimimo.com", "api.minimaxi.com", "api.openai.com":
2159 return true
2160 default:
2161 return false
2162 }
2163 }
2164
2165 func providerBaseURLAllowsMissingAPIKey(raw string) bool {
2166 u, err := url.Parse(strings.TrimSpace(raw))
2167 if err != nil {
2168 return false
2169 }
2170 host := strings.Trim(strings.ToLower(u.Hostname()), "[]")
2171 if host == "localhost" || strings.HasSuffix(host, ".localhost") {
2172 return true
2173 }
2174 addr, err := netip.ParseAddr(host)
2175 if err != nil {
2176 return false
2177 }
2178 return addr.IsLoopback() || addr.IsPrivate() || addr.IsLinkLocalUnicast()
2179 }
2180
2181 // Configured reports whether the provider is selectable. Providers that do not
2182 // require an API key are configured by definition; providers that name an env var
2183 // require that variable to resolve unless their endpoint is local/private.
2184 func (e *ProviderEntry) Configured() bool {
2185 return e != nil && (!e.RequiresAPIKey() || e.APIKey() != "")
2186 }
2187
2188 // ResolveSystemPrompt returns the system prompt, reading system_prompt_file if set.
2189 func (c *Config) ResolveSystemPrompt() (string, error) {
2190 return c.ResolveSystemPromptForRoot(".")
2191 }
2192
2193 // ResolveSystemPromptForRoot is like ResolveSystemPrompt but resolves a relative
2194 // system_prompt_file against root. Desktop tabs pass their workspace root here so
2195 // prompt files are project-scoped even when the process cwd is elsewhere. A path
2196 // inherited from user config may fall back to Reasonix home, while a path chosen
2197 // by project config is confined to the workspace and never probes user files.
2198 func (c *Config) ResolveSystemPromptForRoot(root string) (string, error) {
2199 path := c.Agent.SystemPromptFile
2200 if path == "" {
2201 return c.InlineSystemPrompt(), nil
2202 }
2203
2204 if c.systemPromptFileSource == promptFileSourceProject {
2205 if filepath.IsAbs(path) || !filepath.IsLocal(filepath.Clean(path)) {
2206 return "", fmt.Errorf("project system_prompt_file %q must be a relative path within the workspace", path)
2207 }
2208 candidate := filepath.Join(resolveRoot(root), path)
2209 b, err := readProjectSystemPromptFile(root, path)
2210 if err != nil {
2211 return "", newSystemPromptFileError(path, []string{candidate}, []error{err})
2212 }
2213 return strings.TrimSpace(string(b)), nil
2214 }
2215
2216 if filepath.IsAbs(path) {
2217 b, err := fileencoding.ReadFileUTF8(path)
2218 if err != nil {
2219 return "", newSystemPromptFileError(path, []string{path}, []error{err})
2220 }
2221 return strings.TrimSpace(string(b)), nil
2222 }
2223
2224 candidates := []string{filepath.Join(resolveRoot(root), path)}
2225 if home := ReasonixHomeDir(); home != "" {
2226 homeCandidate := filepath.Join(home, path)
2227 if filepath.Clean(homeCandidate) != filepath.Clean(candidates[0]) {
2228 candidates = append(candidates, homeCandidate)
2229 }
2230 }
2231 readErrors := make([]error, 0, len(candidates))
2232 for _, candidate := range candidates {
2233 b, err := fileencoding.ReadFileUTF8(candidate)
2234 if err == nil {
2235 return strings.TrimSpace(string(b)), nil
2236 }
2237 readErrors = append(readErrors, fmt.Errorf("%s: %w", candidate, err))
2238 }
2239 return "", newSystemPromptFileError(path, candidates, readErrors)
2240 }
2241
2242 func readProjectSystemPromptFile(root, path string) ([]byte, error) {
2243 workspace, err := filepath.Abs(resolveRoot(root))
2244 if err != nil {
2245 return nil, fmt.Errorf("resolve workspace root: %w", err)
2246 }
2247 rootHandle, err := os.OpenRoot(workspace)
2248 if err != nil {
2249 return nil, fmt.Errorf("open workspace root %q: %w", workspace, err)
2250 }
2251 defer rootHandle.Close()
2252 f, err := rootHandle.Open(filepath.Clean(path))
2253 if err != nil {
2254 return nil, err
2255 }
2256 defer f.Close()
2257 b, err := io.ReadAll(f)
2258 if err != nil {
2259 return nil, err
2260 }
2261 return fileencoding.DecodeToUTF8(b), nil
2262 }
2263
2264 func newSystemPromptFileError(configured string, candidates []string, readErrors []error) error {
2265 allMissing := len(readErrors) > 0
2266 for _, err := range readErrors {
2267 if !errors.Is(err, fs.ErrNotExist) {
2268 allMissing = false
2269 break
2270 }
2271 }
2272 return &systemPromptFileError{
2273 configured: configured,
2274 candidates: append([]string(nil), candidates...),
2275 errors: append([]error(nil), readErrors...),
2276 allMissing: allMissing,
2277 }
2278 }
2279
2280 // InlineSystemPrompt returns the configured system_prompt, or DefaultSystemPrompt
2281 // when unset. It is the fallback when system_prompt_file cannot be read.
2282 func (c *Config) InlineSystemPrompt() string {
2283 if strings.TrimSpace(c.Agent.SystemPrompt) == "" {
2284 return DefaultSystemPrompt
2285 }
2286 return c.Agent.SystemPrompt
2287 }
2288
2289 // Validate checks that the selected model's provider is usable.
2290 func (c *Config) Validate(model string) error {
2291 e, ok := c.ResolveModel(model)
2292 if !ok {
2293 return fmt.Errorf("unknown model %q (configured: %s)", model, c.providerNames())
2294 }
2295 if e.Kind == "" {
2296 return fmt.Errorf("provider %q: kind is required", model)
2297 }
2298 if e.BaseURL == "" {
2299 return fmt.Errorf("provider %q: base_url is required", model)
2300 }
2301 if strings.TrimSpace(e.APIKeyEnv) != "" && !IsValidCredentialKey(e.APIKeyEnv) {
2302 return fmt.Errorf("provider %q: api_key_env %q is invalid; use letters, numbers, and underscores, not a model name", model, e.APIKeyEnv)
2303 }
2304 if e.RequiresAPIKey() && e.APIKey() == "" {
2305 return fmt.Errorf("provider %q: missing env %s", model, e.APIKeyEnv)
2306 }
2307 return nil
2308 }
2309
2310 func (c *Config) providerNames() string {
2311 names := make([]string, len(c.Providers))
2312 for i, p := range c.Providers {
2313 names[i] = p.Name
2314 }
2315 return strings.Join(names, ", ")
2316 }
2317
2317 lines GO