返回 DeepSeek-Reasonix
render.go
根目录 / internal / config / render.go
1 package config
2
3 import (
4 "fmt"
5 "reflect"
6 "sort"
7 "strconv"
8 "strings"
9
10 "reasonix/internal/billing"
11 "reasonix/internal/provider"
12 )
13
14 type RenderScope string
15
16 const (
17 RenderScopeFull RenderScope = "full"
18 RenderScopeUser RenderScope = "user"
19 RenderScopeProject RenderScope = "project"
20 )
21
22 // RenderTOML renders the config as annotated TOML in the `reasonix setup` house style:
23 // comments preserved, system_prompt as a multi-line string, helpful hints. The
24 // output round-trips back through Load (see render_test.go).
25 func RenderTOML(c *Config) string {
26 return RenderTOMLForScope(c, RenderScopeFull)
27 }
28
29 // RenderTOMLForScope renders an annotated TOML file for a specific persistence
30 // target. User configs can carry desktop and account-level preferences; project
31 // reasonix.toml stays focused on project behavior and intentionally excludes
32 // desktop-only preferences.
33 func RenderTOMLForScope(c *Config, scope RenderScope) string {
34 if c == nil {
35 c = Default()
36 }
37 switch scope {
38 case RenderScopeUser, RenderScopeProject:
39 default:
40 scope = RenderScopeFull
41 }
42 if scope == RenderScopeProject {
43 c = projectScopedConfigForRender(c)
44 }
45 defaults := Default()
46 var b strings.Builder
47
48 b.WriteString("# Reasonix configuration.\n")
49 fmt.Fprintf(&b, "# Resolution order: flag > ./reasonix.toml > %s > built-in defaults.\n", userConfigDisplayPath())
50 b.WriteString("# Fields marked user/global only are not overridden by ./reasonix.toml.\n")
51 b.WriteString("# Secrets are named via api_key_env and stored in Reasonix's global .env; never put keys here.\n\n")
52
53 fmt.Fprintf(&b, "config_version = %d # schema marker for diagnostics; old versions may ignore it\n", configVersion(c))
54 fmt.Fprintf(&b, "default_model = %q\n", c.DefaultModel)
55 if c.Language != "" {
56 fmt.Fprintf(&b, "language = %q # ui/model language; empty = auto-detect from $LANG / $REASONIX_LANG\n", c.Language)
57 } else {
58 b.WriteString("# language = \"zh\" # ui/model language; empty = auto-detect from $LANG / $REASONIX_LANG\n")
59 }
60 if scope != RenderScopeProject {
61 fmt.Fprintf(&b, "credentials_store = %q # legacy compatibility; provider keys are saved in Reasonix's global .env\n", normalizeCredentialsStore(c.CredentialsStore))
62 }
63 b.WriteString("\n")
64
65 if shouldRenderUI(c, defaults, scope) {
66 b.WriteString("[ui]\n")
67 fmt.Fprintf(&b, "theme = %q # auto|dark|light; CLI colors only; REASONIX_THEME can override per run\n", c.UITheme())
68 if style := c.UIThemeStyle(); style != "" {
69 fmt.Fprintf(&b, "theme_style = %q # CLI accent palette; REASONIX_THEME_STYLE can override per run\n", style)
70 } else {
71 b.WriteString("# theme_style = \"graphite\" # graphite|aurora|slate|carbon|nocturne|amber and legacy aliases\n")
72 }
73 if layout := c.UIShortcutLayout(); layout != "classic" {
74 fmt.Fprintf(&b, "shortcut_layout = %q # classic|desktop; compatibility setting; Shift+Tab cycles read-only/workspace/YOLO/plan; Ctrl+Y toggles YOLO\n", layout)
75 } else {
76 b.WriteString("# shortcut_layout = \"desktop\" # classic|desktop; compatibility setting; Shift+Tab cycles read-only/workspace/YOLO/plan; Ctrl+Y toggles YOLO\n")
77 }
78 if strings.TrimSpace(c.UI.CursorShape) != "" {
79 fmt.Fprintf(&b, "cursor_shape = %q # block|underline|bar; text input cursor shape\n", c.UICursorShape())
80 } else {
81 b.WriteString("# cursor_shape = \"bar\" # block|underline|bar; text input cursor shape\n")
82 }
83 if strings.TrimSpace(c.UI.CloseBehavior) != "" && scope == RenderScopeProject {
84 fmt.Fprintf(&b, "close_behavior = %q # legacy desktop close behavior; prefer [desktop].close_behavior in user config\n", c.DesktopCloseBehavior())
85 }
86 if c.UI.ShowReasoning {
87 b.WriteString("show_reasoning = true # CLI: show thinking text by default; false = collapsed (toggle with Ctrl+O)\n")
88 } else {
89 b.WriteString("# show_reasoning = true # CLI: show thinking text by default; false = collapsed (toggle with Ctrl+O)\n")
90 }
91 fmt.Fprintf(&b, "show_turn_usage = %v # CLI/TUI: show per-request token and cost receipts in the transcript\n", c.UI.ShowTurnUsage)
92 b.WriteString("\n")
93 }
94
95 if scope != RenderScopeProject {
96 b.WriteString("[desktop]\n")
97 if lang := c.DesktopLanguage(); lang != "" {
98 fmt.Fprintf(&b, "language = %q # desktop UI language; empty/auto = browser/OS auto-detect\n", lang)
99 } else {
100 b.WriteString("# language = \"zh\" # desktop UI language; empty/auto = browser/OS auto-detect\n")
101 }
102 // Legacy desktop.currency is still emitted when set so older binaries keep
103 // reading the preference; new writers also own [billing].display_currency.
104 if currency := c.DesktopCurrency(); currency != "" {
105 fmt.Fprintf(&b, "currency = %q # legacy display currency; prefer [billing].display_currency\n", currency)
106 }
107 fmt.Fprintf(&b, "layout_style = %q # desktop layout: workbench|creation; legacy classic migrates to workbench\n", c.DesktopLayoutStyle())
108 fmt.Fprintf(&b, "theme = %q # desktop only: auto|dark|light\n", c.DesktopTheme())
109 fmt.Fprintf(&b, "terminal_theme = %q # integrated terminal: auto|dark|light; auto follows the desktop app\n", c.DesktopTerminalTheme())
110 if style := c.DesktopThemeStyle(); style != "" {
111 fmt.Fprintf(&b, "theme_style = %q # desktop accent palette\n", style)
112 } else {
113 b.WriteString("# theme_style = \"graphite\" # graphite|aurora|slate|carbon|nocturne|amber and legacy aliases\n")
114 }
115 if opener := c.DesktopExternalOpener(); opener != "" {
116 fmt.Fprintf(&b, "external_opener = %q # desktop Open control: installed application id\n", opener)
117 } else {
118 b.WriteString("# external_opener = \"vscode\" # desktop Open control: installed application id\n")
119 }
120 fmt.Fprintf(&b, "close_behavior = %q # desktop: quit|background when the window close button is clicked\n", c.DesktopCloseBehavior())
121 fmt.Fprintf(&b, "status_bar_style = %q # desktop: icon|text metric labels in the bottom status bar\n", c.DesktopStatusBarStyle())
122 b.WriteString("status_bar_style_initialized = true # icon default upgrade applied; preserve later user choices\n")
123 fmt.Fprintf(&b, "status_bar_items = %s # desktop: ordered visible bottom status bar items\n", renderStringArray(c.DesktopStatusBarItems()))
124 fmt.Fprintf(&b, "default_tool_approval_mode = %q # desktop: read-only/workspace-write/danger-full-access default for new sessions\n", c.DesktopDefaultToolApprovalMode())
125 fmt.Fprintf(&b, "check_updates = %v # desktop: check for new versions on startup\n", c.DesktopCheckUpdates())
126 fmt.Fprintf(&b, "telemetry = %v # desktop: anonymous launch ping + scrubbed next-launch native crash diagnostics; never content\n", c.DesktopTelemetry())
127 fmt.Fprintf(&b, "metrics = %v # desktop: aggregate quality/lifecycle metrics (anonymous signal/bucket counts); never content\n", c.DesktopMetrics())
128 // A non-nil empty slice is intentional: provider_access = [] means the
129 // user removed every desktop access entry. Omitting it would make the next
130 // load treat the config as legacy and infer access again.
131 if c.Desktop.ProviderAccess != nil {
132 fmt.Fprintf(&b, "provider_access = %s # desktop settings: providers shown on Settings > Model > Access\n", renderStringArray(c.Desktop.ProviderAccess))
133 }
134 renderDesktopSessionExperience(&b, c)
135 renderDesktopReasoningDisplayMode(&b, c)
136 fmt.Fprintf(&b, "display_mode = %q # desktop: standard|compact transcript display mode\n", c.DesktopDisplayMode())
137 if width := c.DesktopConversationWidth(); width == "full" {
138 fmt.Fprintf(&b, "conversation_width = %q # desktop: standard|full transcript width; empty = standard\n", width)
139 }
140 b.WriteString("\n")
141 b.WriteString("[billing]\n")
142 if pref := c.DisplayCurrencyPref(); pref != "" {
143 fmt.Fprintf(&b, "display_currency = %q # auto|CNY|USD; display only — does not rewrite provider list prices\n", pref)
144 } else {
145 b.WriteString("# display_currency = \"auto\" # auto|CNY|USD; display only — does not rewrite provider list prices\n")
146 }
147 b.WriteString("\n")
148 } else if c.Desktop.ProviderAccess != nil {
149 // provider_access is intentionally mergeable across user and project
150 // configs. It is the only desktop field written to reasonix.toml: local
151 // providers then appear in that workspace's desktop model switcher without
152 // copying user-global appearance or security preferences into the project.
153 b.WriteString("[desktop]\n")
154 fmt.Fprintf(&b, "provider_access = %s # providers available to this workspace in the desktop model switcher\n\n", renderStringArray(c.Desktop.ProviderAccess))
155 }
156
157 if scope != RenderScopeProject {
158 if c.CLITelemetryConfigured() {
159 b.WriteString("[telemetry]\n")
160 fmt.Fprintf(&b, "cli_metrics = %q # CLI content-free usage metrics: auto|on|off; auto requires a local interactive terminal\n\n", c.CLITelemetryMode())
161 }
162 if c.Attachments.MaxStreamBytes != nil {
163 b.WriteString("[attachments]\n")
164 fmt.Fprintf(&b, "max_stream_bytes = %d # user/global only; ordinary streamed file bytes; 0 = unlimited; unset = 1 GiB\n\n", *c.Attachments.MaxStreamBytes)
165 }
166
167 b.WriteString("[notifications]\n")
168 fmt.Fprintf(&b, "enabled = %v # system notifications for CLI and desktop turns; default off\n", c.Notifications.Enabled)
169 fmt.Fprintf(&b, "turn_done = %v # notify when a turn finishes\n", c.Notifications.TurnDone)
170 fmt.Fprintf(&b, "approval_request = %v # notify when a tool approval is waiting\n", c.Notifications.ApprovalRequest)
171 fmt.Fprintf(&b, "ask_request = %v # notify when a question is waiting\n", c.Notifications.AskRequest)
172 b.WriteString("\n")
173 }
174
175 if shouldRenderNetwork(c, defaults, scope) {
176 b.WriteString("[network]\n")
177 fmt.Fprintf(&b, "proxy_mode = %q # auto|env|custom|off; auto currently uses env proxy\n", c.NetworkProxyMode())
178 if c.Network.ProxyURL != "" {
179 fmt.Fprintf(&b, "proxy_url = %q # custom override, e.g. socks5://127.0.0.1:7890\n", c.Network.ProxyURL)
180 } else {
181 b.WriteString("# proxy_url = \"socks5://127.0.0.1:7890\" # optional custom override\n")
182 }
183 if c.Network.NoProxy != "" {
184 fmt.Fprintf(&b, "no_proxy = %q # honored for proxy_mode = \"custom\"\n", c.Network.NoProxy)
185 } else {
186 b.WriteString("# no_proxy = \"localhost,127.0.0.1,.local\" # honored for proxy_mode = \"custom\"\n")
187 }
188 b.WriteString("\n[network.proxy]\n")
189 proxyType := c.Network.Proxy.Type
190 if proxyType == "" {
191 proxyType = "socks5"
192 }
193 fmt.Fprintf(&b, "type = %q # http|https|socks5|socks5h\n", proxyType)
194 if c.Network.Proxy.Server != "" {
195 fmt.Fprintf(&b, "server = %q\n", c.Network.Proxy.Server)
196 } else {
197 b.WriteString("# server = \"127.0.0.1\"\n")
198 }
199 if c.Network.Proxy.Port > 0 {
200 fmt.Fprintf(&b, "port = %d\n", c.Network.Proxy.Port)
201 } else {
202 b.WriteString("# port = 7890\n")
203 }
204 if c.Network.Proxy.Username != "" {
205 fmt.Fprintf(&b, "username = %q\n", c.Network.Proxy.Username)
206 } else {
207 b.WriteString("# username = \"\"\n")
208 }
209 if c.Network.Proxy.Password != "" {
210 fmt.Fprintf(&b, "password = %q # supports ${VAR} expansion\n", c.Network.Proxy.Password)
211 } else {
212 b.WriteString("# password = \"${REASONIX_PROXY_PASSWORD}\" # optional; supports ${VAR} expansion\n")
213 }
214 b.WriteString("\n")
215 }
216 if shouldRenderEnvironment(c, defaults, scope) {
217 renderEnvironmentConfig(&b, c.Environment)
218 }
219
220 b.WriteString("[agent]\n")
221 if shouldRenderSystemPrompt(c, defaults, scope) {
222 b.WriteString("system_prompt = \"\"\"\n")
223 b.WriteString(c.Agent.SystemPrompt)
224 b.WriteString("\"\"\"\n")
225 } else {
226 b.WriteString("# system_prompt = \"\"\"...\"\"\" # omit to use the built-in prompt for this version\n")
227 }
228 if c.Agent.SystemPromptFile != "" {
229 fmt.Fprintf(&b, "system_prompt_file = %q\n", c.Agent.SystemPromptFile)
230 } else {
231 b.WriteString("# system_prompt_file = \"prompts/system.md\" # project paths stay in <workspace>; user paths may fall back to <reasonix home>\n")
232 }
233 fmt.Fprintf(&b, "temperature = %s\n", formatFloat(c.Agent.Temperature))
234 renderRecoveryAndCompletionValidation(&b, c)
235 if lang := c.ReasoningLanguage(); lang != "auto" {
236 fmt.Fprintf(&b, "reasoning_language = %q # visible reasoning language: auto|zh|en\n", lang)
237 } else {
238 b.WriteString("# reasoning_language = \"zh\" # visible reasoning language: auto|zh|en\n")
239 }
240 fmt.Fprintf(&b, "compact_ratio = %s # sole auto trigger; presets 0.70/0.80/0.85 (default 0.80)\n", formatFloat(c.Agent.CompactRatio))
241 if c.Agent.Keep != nil {
242 fmt.Fprintf(&b, "keep = %s # deprecated compatibility field; ignored at runtime\n", renderStringArray(c.Agent.Keep))
243 } else {
244 b.WriteString("# keep = [\"errors\"] # deprecated compatibility field; ignored at runtime\n")
245 }
246 if c.Agent.RecentKeep > 0 {
247 fmt.Fprintf(&b, "recent_keep = %d # deprecated compatibility field; ignored at runtime\n", c.Agent.RecentKeep)
248 } else {
249 b.WriteString("# recent_keep = 2 # deprecated compatibility field; ignored at runtime\n")
250 }
251 renderAgentSafetyControls(&b, c, scope)
252 renderAgentModelAssignments(&b, c)
253 if c.Agent.SubagentEffort != "" {
254 fmt.Fprintf(&b, "subagent_effort = %q # default effort for subagent entry points\n", c.Agent.SubagentEffort)
255 } else {
256 b.WriteString("# subagent_effort = \"high\" # optional default effort for subagents\n")
257 }
258 if len(c.Agent.SubagentEfforts) > 0 {
259 fmt.Fprintf(&b, "subagent_efforts = %s # per-tool/skill effort overrides\n", renderStringMap(c.Agent.SubagentEfforts))
260 } else {
261 b.WriteString("# subagent_efforts = { review = \"max\", task = \"high\" } # per-tool/skill effort overrides\n")
262 }
263 if c.Agent.MaxSubagentDepth != defaults.Agent.MaxSubagentDepth {
264 fmt.Fprintf(&b, "max_subagent_depth = %d # nested subagent delegation depth; 1 restores the old single-layer boundary\n", c.Agent.MaxSubagentDepth)
265 } else {
266 b.WriteString("# max_subagent_depth = 2 # nested subagent delegation depth; set 1 to disable nested delegation\n")
267 }
268 if c.Agent.MaxSubagentConcurrency != defaults.Agent.MaxSubagentConcurrency {
269 fmt.Fprintf(&b, "max_subagent_concurrency = %d # session-wide sub-agent concurrency (task/fleet/skills)\n", c.Agent.MaxSubagentConcurrency)
270 } else {
271 b.WriteString("# max_subagent_concurrency = 6 # session-wide sub-agent concurrency (task/fleet/skills)\n")
272 }
273 if c.Agent.MaxParallelWriters != defaults.Agent.MaxParallelWriters {
274 fmt.Fprintf(&b, "max_parallel_writers = %d # concurrent writers with non-overlapping write_paths\n", c.Agent.MaxParallelWriters)
275 } else {
276 b.WriteString("# max_parallel_writers = 3 # concurrent writers with non-overlapping write_paths\n")
277 }
278 if c.Agent.OutputStyle != "" {
279 fmt.Fprintf(&b, "output_style = %q # persona/tone folded into the prompt\n", c.Agent.OutputStyle)
280 } else {
281 b.WriteString("# output_style = \"explanatory\" # explanatory | learning | concise | custom; empty = default\n")
282 }
283 b.WriteString("\n")
284
285 if shouldRenderProviders(c, defaults, scope) {
286 for _, p := range reasoningCompatibilitySnapshots(c.Providers) {
287 b.WriteString("[[providers]]\n")
288 fmt.Fprintf(&b, "name = %q\n", p.Name)
289 fmt.Fprintf(&b, "kind = %q\n", p.Kind)
290 fmt.Fprintf(&b, "base_url = %q\n", p.BaseURL)
291 if p.ChatURL != "" {
292 fmt.Fprintf(&b, "chat_url = %q # legacy OpenAI chat endpoint override\n", p.ChatURL)
293 }
294 if p.RequestURL != "" {
295 fmt.Fprintf(&b, "request_url = %q # exact provider request URL; no path completion\n", p.RequestURL)
296 }
297 if len(p.Models) > 0 {
298 fmt.Fprintf(&b, "models = %s\n", renderStringArray(p.Models))
299 if p.Default != "" {
300 fmt.Fprintf(&b, "default = %q\n", p.Default)
301 }
302 } else if p.Model != "" {
303 fmt.Fprintf(&b, "model = %q\n", p.Model)
304 }
305 if p.ModelsURL != "" {
306 fmt.Fprintf(&b, "models_url = %q # auto-fetch models from this URL on startup\n", p.ModelsURL)
307 }
308 renderProviderIdentity(&b, p.APIKeyEnv, p.DisplayName)
309 if p.PresetID != "" {
310 fmt.Fprintf(&b, "preset_id = %q # curated preset identity; settings UI uses it to avoid duplicate installs\n", p.PresetID)
311 }
312 if p.PresetVersion > 0 {
313 fmt.Fprintf(&b, "preset_version = %d\n", p.PresetVersion)
314 }
315 if len(p.Headers) > 0 {
316 fmt.Fprintf(&b, "headers = %s # extra static request headers; keep secrets in api_key_env\n", renderStringMap(p.Headers))
317 }
318 if len(p.ExtraBody) > 0 {
319 fmt.Fprintf(&b, "extra_body = %s # extra top-level JSON request body fields for compatible gateways\n", renderAnyMap(p.ExtraBody))
320 }
321 if p.AuthHeader {
322 b.WriteString("auth_header = true # Anthropic-compatible: send Authorization: Bearer <api_key> instead of x-api-key\n")
323 }
324 if p.ResponsesMode != "" {
325 fmt.Fprintf(&b, "responses_mode = %q # responses provider: stateless|stateful\n", p.ResponsesMode)
326 }
327 if p.ResponsesStateful != nil {
328 fmt.Fprintf(&b, "responses_stateful = %t # legacy responses mode switch\n", *p.ResponsesStateful)
329 }
330 if p.BalanceURL != "" {
331 fmt.Fprintf(&b, "balance_url = %q # optional; wallet-balance endpoint shown in the status bar\n", p.BalanceURL)
332 }
333 if p.ContextWindow > 0 {
334 fmt.Fprintf(&b, "context_window = %d # tokens; compaction triggers near this limit\n", p.ContextWindow)
335 }
336 if p.MaxOutputTokens != 0 {
337 fmt.Fprintf(&b, "max_output_tokens = %d # per-turn total output; 0 = provider auto (official DeepSeek 384K, omit when safe); positive = cost cap; negative = force-omit; never affects compact_ratio\n", p.MaxOutputTokens)
338 } else {
339 b.WriteString("# max_output_tokens = 0 # recommended: official DeepSeek omits the field (server 384K ceiling)\n")
340 b.WriteString("# max_output_tokens = 32768 # optional cost cap\n")
341 b.WriteString("# max_output_tokens = 65536 # optional cost cap\n")
342 b.WriteString("# max_output_tokens = 131072 # optional cost cap\n")
343 }
344 if p.Price != nil {
345 fmt.Fprintf(&b, "price = %s # provider-wide fallback, per 1M tokens\n", renderPricingInline(p.Price))
346 }
347 if len(p.Prices) > 0 {
348 fmt.Fprintf(&b, "prices = %s # per-model prices, per 1M tokens\n", renderPricingMap(p.Prices))
349 }
350 if cur := strings.TrimSpace(p.BillingCurrency); cur != "" {
351 fmt.Fprintf(&b, "billing_currency = %q # frozen list-price currency; independent of display_currency\n", billing.NormalizeCurrency(cur))
352 }
353 if mode := strings.TrimSpace(p.BillingMode); mode != "" && mode != "payg" {
354 fmt.Fprintf(&b, "billing_mode = %q # payg|subscription_equivalent\n", mode)
355 }
356 if p.Thinking != "" {
357 fmt.Fprintf(&b, "thinking = %q\n", p.Thinking)
358 }
359 if p.Effort != "" {
360 fmt.Fprintf(&b, "effort = %q\n", p.Effort)
361 }
362 if p.Vision {
363 b.WriteString("vision = true # provider accepts image input for all listed models\n")
364 }
365 if p.VisionModels != nil {
366 fmt.Fprintf(&b, "vision_models = %s # models in this provider that accept image input\n", renderStringArray(p.VisionModels))
367 }
368 if p.VisionDetail != "" {
369 fmt.Fprintf(&b, "vision_detail = %q # openai image detail hint: low|high; empty = auto\n", p.VisionDetail)
370 }
371 if p.WebSearch != nil {
372 fmt.Fprintf(&b, "web_search = %t # independent web_search tool; omitted defaults on for supported official DeepSeek APIs\n", *p.WebSearch)
373 }
374 if p.ReasoningProtocol != "" {
375 fmt.Fprintf(&b, "reasoning_protocol = %q # auto|deepseek|glm|kimi-k3|openai|none; overrides model/endpoint reasoning detection\n", p.ReasoningProtocol)
376 }
377 if len(p.SupportedEfforts) > 0 {
378 fmt.Fprintf(&b, "supported_efforts = %s # custom /effort levels exposed by this provider; overrides the built-in Kind/BaseURL default\n", renderStringArray(p.SupportedEfforts))
379 }
380 if p.DefaultEffort != "" {
381 fmt.Fprintf(&b, "default_effort = %q # used when /effort is auto or unset; must be one of supported_efforts\n", p.DefaultEffort)
382 }
383 if len(p.ModelOverrides) > 0 {
384 fmt.Fprintf(&b, "model_overrides = %s # per-model context/output/reasoning/vision overrides for mixed gateways\n", renderModelOverrides(p.ModelOverrides))
385 }
386 if p.NoProxy {
387 b.WriteString("no_proxy = true # reach this base_url directly, never via the proxy\n")
388 }
389 b.WriteString("\n")
390 }
391 }
392
393 renderCheckpointsConfig(&b, c.Checkpoints)
394 b.WriteString("[tools]\n")
395 if len(c.Tools.Enabled) == 0 {
396 b.WriteString("enabled = [] # empty = all built-in tools\n")
397 } else {
398 b.WriteString("enabled = [")
399 for i, t := range c.Tools.Enabled {
400 if i > 0 {
401 b.WriteString(", ")
402 }
403 fmt.Fprintf(&b, "%q", t)
404 }
405 b.WriteString("]\n")
406 }
407 fmt.Fprintf(&b, "bash_timeout_seconds = %d # foreground safety cap; set 0 for no tool-local cap\n", c.BashTimeoutSeconds())
408 fmt.Fprintf(&b, "mcp_startup_timeout_seconds = %d # background initialize + tools/list safety cap; per-plugin overrides may raise it\n", c.MCPStartupTimeoutSeconds())
409 fmt.Fprintf(&b, "mcp_call_timeout_seconds = %d # default MCP call safety cap; per-plugin/tool overrides may raise it\n\n", c.MCPCallTimeoutSeconds())
410
411 b.WriteString("[tools.background_jobs]\n")
412 fmt.Fprintf(&b, "stalled_warning_seconds = %d # heads-up once per background job after this many quiet seconds; a quiet job is not necessarily stuck; 0 disables\n\n", c.BackgroundJobStalledWarningSeconds())
413
414 b.WriteString("[tools.shell]\n")
415 if c.Tools.Shell.Prefer != "" {
416 fmt.Fprintf(&b, "prefer = %q # auto|bash|powershell|pwsh; empty/default = auto-detect\n", c.Tools.Shell.Prefer)
417 } else {
418 b.WriteString("# prefer = \"auto\" # auto|bash|powershell|pwsh; empty/default = auto-detect\n")
419 }
420 if c.Tools.Shell.Path != "" {
421 fmt.Fprintf(&b, "path = %q # absolute path to the shell executable; empty = PATH lookup\n\n", c.Tools.Shell.Path)
422 } else {
423 b.WriteString("# path = \"/opt/homebrew/bin/bash\" # absolute path to the shell executable; empty = PATH lookup\n\n")
424 }
425
426 renderLSPConfig(&b, c.LSP)
427 renderBrowserConfig(&b, c.Browser)
428
429 b.WriteString("[skills]\n")
430 if len(c.Skills.Paths) > 0 {
431 fmt.Fprintf(&b, "paths = %s # extra custom skill roots\n", renderStringArray(c.Skills.Paths))
432 } else {
433 b.WriteString("# paths = [\"~/my-skills\", \"../shared/skills\"] # extra custom skill roots\n")
434 }
435 if len(c.Skills.ExcludedPaths) > 0 {
436 fmt.Fprintf(&b, "excluded_paths = %s # skill roots hidden from discovery\n", renderStringArray(c.Skills.ExcludedPaths))
437 } else {
438 b.WriteString("# excluded_paths = [\"~/.agents/skills\"] # hide convention roots without deleting folders\n")
439 }
440 if c.Skills.DisableImplicitInvocation {
441 b.WriteString("disable_implicit_invocation = true # keep /skill explicit; hide skill discovery and tools from the model\n")
442 } else {
443 b.WriteString("# disable_implicit_invocation = false # keep skills available for automatic model invocation\n")
444 }
445 if c.Skills.MaxDepth != 0 {
446 fmt.Fprintf(&b, "max_depth = %d # nested scan depth; default 3, set 1 for legacy root-only discovery\n", c.SkillMaxDepth())
447 } else {
448 b.WriteString("# max_depth = 3 # nested scan depth; set 1 for legacy root-only discovery\n")
449 }
450 if disabled := c.DisabledSkillNames(); len(disabled) > 0 {
451 fmt.Fprintf(&b, "disabled_skills = %s # hidden from the prompt, slash invocation, and skill tools\n\n", renderStringArray(disabled))
452 } else {
453 b.WriteString("# disabled_skills = [\"review\"] # hide noisy or unwanted skills\n\n")
454 }
455
456 b.WriteString("[permissions]\n")
457 b.WriteString("# Per-call gating. mode = writer fallback when no rule matches: ask|allow|deny.\n")
458 b.WriteString("# Readers always default to allow. Precedence: deny > ask > allow > fallback.\n")
459 b.WriteString("# Rules are \"Tool\" or \"Tool(specifier)\"; e.g. Bash(go test:*), Edit(src/**).\n")
460 mode := c.Permissions.Mode
461 if mode == "" {
462 mode = "ask"
463 }
464 fmt.Fprintf(&b, "mode = %q\n", mode)
465 b.WriteString(renderRuleList("deny", c.Permissions.Deny, `["Bash(rm -rf*)", "Bash(git push*)"] # hard-blocked in every mode`))
466 b.WriteString(renderRuleList("allow", c.Permissions.Allow, `["Bash(go test:*)", "Bash(git status:*)"] # never prompted`))
467 b.WriteString(renderRuleList("ask", c.Permissions.Ask, `["Edit(src/**)"] # force a prompt even if otherwise allowed`))
468 b.WriteString("\n")
469
470 b.WriteString("[sandbox]\n")
471 b.WriteString("# Confine tool blast radius. File-writers (write_file/edit_file/multi_edit/move_file)\n")
472 b.WriteString("# may only write under workspace_root (empty = current dir) and allow_write extras.\n")
473 b.WriteString("# bash = \"enforce\" jails each command in an OS sandbox when available;\n")
474 b.WriteString("# without one, restricted permission modes refuse bash execution. Empty defaults to enforce.\n")
475 b.WriteString("# macOS uses Seatbelt, Linux uses bubblewrap, and Windows uses a restricted token/AppContainer.\n")
476 b.WriteString("# network allows sandboxed bash egress.\n")
477 if c.Sandbox.WorkspaceRoot != "" {
478 fmt.Fprintf(&b, "workspace_root = %q\n", c.Sandbox.WorkspaceRoot)
479 } else {
480 b.WriteString("# workspace_root = \"\" # default: current working directory\n")
481 }
482 if len(c.Sandbox.AllowWrite) > 0 {
483 fmt.Fprintf(&b, "allow_write = %s\n", renderStringArray(c.Sandbox.AllowWrite))
484 } else {
485 b.WriteString("# allow_write = [\"/tmp\"] # extra dirs writers may also modify\n")
486 }
487 if len(c.Sandbox.ForbidRead) > 0 {
488 fmt.Fprintf(&b, "forbid_read = %s\n", renderStringArray(c.Sandbox.ForbidRead))
489 } else {
490 b.WriteString("# forbid_read = [] # dirs the agent cannot read or list\n")
491 }
492 fmt.Fprintf(&b, "bash = %q\n", c.BashMode())
493 fmt.Fprintf(&b, "network = %v\n", c.Sandbox.Network)
494 b.WriteString("\n")
495
496 if scope != RenderScopeProject {
497 b.WriteString("[statusline] # user/global only, ./reasonix.toml cannot set it\n")
498 b.WriteString("# A custom status line: a command whose first stdout line replaces the built-in\n")
499 b.WriteString("# data row. It receives {\"model\",\"contextUsed\",\"contextWindow\",\"cwd\"} as JSON on stdin.\n")
500 if c.Statusline.Command != "" {
501 fmt.Fprintf(&b, "command = %q\n", c.Statusline.Command)
502 } else {
503 b.WriteString("# command = \"my-statusline.sh\"\n")
504 }
505 b.WriteString("\n")
506 }
507
508 if shouldRenderBot(c, defaults, scope) {
509 b.WriteString("# Bot gateway: multi-channel IM bot for QQ, Feishu/Lark, and WeChat.\n")
510 b.WriteString("[bot]\n")
511 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.Enabled)
512 if c.Bot.Model != "" {
513 fmt.Fprintf(&b, "model = %q\n", c.Bot.Model)
514 } else {
515 b.WriteString("# model = \"\" # empty = default_model\n")
516 }
517 if c.Bot.ToolApprovalMode != "" {
518 fmt.Fprintf(&b, "tool_approval_mode = %q # read-only|workspace-write|danger-full-access\n", NormalizeToolApprovalMode(c.Bot.ToolApprovalMode))
519 } else {
520 b.WriteString("# tool_approval_mode = \"workspace-write\" # default permission for bot sessions\n")
521 }
522 fmt.Fprintf(&b, "max_steps = %d\n", c.Bot.MaxSteps)
523 fmt.Fprintf(&b, "debounce_ms = %d\n", c.Bot.DebounceMs)
524 if c.Bot.QueueMode != "" {
525 fmt.Fprintf(&b, "queue_mode = %q # steer|followup|collect|interrupt\n", c.Bot.QueueMode)
526 } else {
527 b.WriteString("# queue_mode = \"steer\" # steer|followup|collect|interrupt\n")
528 }
529 if c.Bot.QueueCap > 0 {
530 fmt.Fprintf(&b, "queue_cap = %d\n", c.Bot.QueueCap)
531 } else {
532 b.WriteString("# queue_cap = 20\n")
533 }
534 if c.Bot.QueueDrop != "" {
535 fmt.Fprintf(&b, "queue_drop = %q # summarize|old|new\n", c.Bot.QueueDrop)
536 } else {
537 b.WriteString("# queue_drop = \"summarize\" # summarize|old|new\n")
538 }
539 fmt.Fprintf(&b, "ignore_self_messages = %v # ignore bot echo by returned message_id and configured self user ids\n", c.Bot.IgnoreSelfMessages)
540 b.WriteString("\n[bot.self_user_ids]\n")
541 fmt.Fprintf(&b, "qq = %s\n", renderStringArray(c.Bot.SelfUserIDs.QQ))
542 fmt.Fprintf(&b, "feishu = %s\n", renderStringArray(c.Bot.SelfUserIDs.Feishu))
543 fmt.Fprintf(&b, "weixin = %s\n", renderStringArray(c.Bot.SelfUserIDs.Weixin))
544 fmt.Fprintf(&b, "dingtalk = %s\n", renderStringArray(c.Bot.SelfUserIDs.Dingtalk))
545 b.WriteString("\n[bot.control]\n")
546 fmt.Fprintf(&b, "enabled = %v # local loopback HTTP API for status/send; requires Bearer token\n", c.Bot.Control.Enabled)
547 if strings.TrimSpace(c.Bot.Control.Addr) != "" {
548 fmt.Fprintf(&b, "addr = %q\n", c.Bot.Control.Addr)
549 } else {
550 b.WriteString("# addr = \"127.0.0.1:37913\"\n")
551 }
552 if strings.TrimSpace(c.Bot.Control.TokenEnv) != "" {
553 fmt.Fprintf(&b, "token_env = %q\n", c.Bot.Control.TokenEnv)
554 } else {
555 b.WriteString("# token_env = \"REASONIX_BOT_CONTROL_TOKEN\"\n")
556 }
557 if len(c.Bot.Routes) > 0 {
558 for _, route := range c.Bot.Routes {
559 b.WriteString("\n[[bot.routes]]\n")
560 renderBotRoute(&b, route)
561 }
562 }
563 if len(c.Bot.DesktopWatchers) > 0 {
564 for _, watcher := range c.Bot.DesktopWatchers {
565 b.WriteString("\n[[bot.desktop_watchers]]\n")
566 renderBotDesktopWatcher(&b, watcher)
567 }
568 }
569 b.WriteString("\n[bot.pairing]\n")
570 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.Pairing.Enabled)
571 if c.Bot.Pairing.RequestTTLMinutes > 0 {
572 fmt.Fprintf(&b, "request_ttl_minutes = %d\n", c.Bot.Pairing.RequestTTLMinutes)
573 } else {
574 b.WriteString("# request_ttl_minutes = 60\n")
575 }
576 if c.Bot.Pairing.MaxPendingPerPlatform > 0 {
577 fmt.Fprintf(&b, "max_pending_per_platform = %d\n", c.Bot.Pairing.MaxPendingPerPlatform)
578 } else {
579 b.WriteString("# max_pending_per_platform = 3\n")
580 }
581 b.WriteString("\n[bot.allowlist]\n")
582 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.Allowlist.Enabled)
583 fmt.Fprintf(&b, "allow_all = %v\n", c.Bot.Allowlist.AllowAll)
584 fmt.Fprintf(&b, "qq_users = %s\n", renderStringArray(c.Bot.Allowlist.QQUsers))
585 fmt.Fprintf(&b, "feishu_users = %s\n", renderStringArray(c.Bot.Allowlist.FeishuUsers))
586 fmt.Fprintf(&b, "weixin_users = %s\n", renderStringArray(c.Bot.Allowlist.WeixinUsers))
587 fmt.Fprintf(&b, "dingtalk_users = %s\n", renderStringArray(c.Bot.Allowlist.DingtalkUsers))
588 fmt.Fprintf(&b, "qq_approvers = %s\n", renderStringArray(c.Bot.Allowlist.QQApprovers))
589 fmt.Fprintf(&b, "feishu_approvers = %s\n", renderStringArray(c.Bot.Allowlist.FeishuApprovers))
590 fmt.Fprintf(&b, "weixin_approvers = %s\n", renderStringArray(c.Bot.Allowlist.WeixinApprovers))
591 fmt.Fprintf(&b, "dingtalk_approvers = %s\n", renderStringArray(c.Bot.Allowlist.DingtalkApprovers))
592 fmt.Fprintf(&b, "qq_admins = %s\n", renderStringArray(c.Bot.Allowlist.QQAdmins))
593 fmt.Fprintf(&b, "feishu_admins = %s\n", renderStringArray(c.Bot.Allowlist.FeishuAdmins))
594 fmt.Fprintf(&b, "weixin_admins = %s\n", renderStringArray(c.Bot.Allowlist.WeixinAdmins))
595 fmt.Fprintf(&b, "dingtalk_admins = %s\n", renderStringArray(c.Bot.Allowlist.DingtalkAdmins))
596 fmt.Fprintf(&b, "qq_groups = %s\n", renderStringArray(c.Bot.Allowlist.QQGroups))
597 fmt.Fprintf(&b, "feishu_groups = %s\n", renderStringArray(c.Bot.Allowlist.FeishuGroups))
598 fmt.Fprintf(&b, "weixin_groups = %s\n", renderStringArray(c.Bot.Allowlist.WeixinGroups))
599 fmt.Fprintf(&b, "dingtalk_groups = %s\n", renderStringArray(c.Bot.Allowlist.DingtalkGroups))
600 b.WriteString("\n[bot.qq]\n")
601 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.QQ.Enabled)
602 fmt.Fprintf(&b, "app_id = %q\n", c.Bot.QQ.AppID)
603 fmt.Fprintf(&b, "app_secret_env = %q\n", c.Bot.QQ.AppSecretEnv)
604 fmt.Fprintf(&b, "sandbox = %v\n", c.Bot.QQ.Sandbox)
605 if strings.TrimSpace(c.Bot.QQ.Model) != "" {
606 fmt.Fprintf(&b, "model = %q\n", strings.TrimSpace(c.Bot.QQ.Model))
607 }
608 if strings.TrimSpace(c.Bot.QQ.ToolApprovalMode) != "" {
609 fmt.Fprintf(&b, "tool_approval_mode = %q\n", NormalizeToolApprovalMode(c.Bot.QQ.ToolApprovalMode))
610 }
611 if strings.TrimSpace(c.Bot.QQ.WorkspaceRoot) != "" {
612 fmt.Fprintf(&b, "workspace_root = %q\n", strings.TrimSpace(c.Bot.QQ.WorkspaceRoot))
613 }
614 if parts := renderBotAccess(c.Bot.QQ.Access); parts != "" {
615 fmt.Fprintf(&b, "access = %s\n", parts)
616 }
617 b.WriteString("\n[bot.feishu]\n")
618 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.Feishu.Enabled)
619 fmt.Fprintf(&b, "app_id = %q\n", c.Bot.Feishu.AppID)
620 fmt.Fprintf(&b, "domain = %q\n", c.Bot.Feishu.Domain)
621 fmt.Fprintf(&b, "app_secret_env = %q\n", c.Bot.Feishu.AppSecretEnv)
622 fmt.Fprintf(&b, "verification_token = %q\n", c.Bot.Feishu.VerificationToken)
623 fmt.Fprintf(&b, "mode = %q\n", c.Bot.Feishu.Mode)
624 fmt.Fprintf(&b, "webhook_port = %d\n", c.Bot.Feishu.WebhookPort)
625 fmt.Fprintf(&b, "require_mention = %v\n", c.Bot.Feishu.RequireMention)
626 if len(c.Bot.Feishu.OutboundMediaRoots) > 0 {
627 fmt.Fprintf(&b, "outbound_media_roots = %s\n", renderStringArray(c.Bot.Feishu.OutboundMediaRoots))
628 }
629 b.WriteString("\n[bot.weixin]\n")
630 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.Weixin.Enabled)
631 fmt.Fprintf(&b, "account_id = %q\n", c.Bot.Weixin.AccountID)
632 fmt.Fprintf(&b, "token_env = %q\n", c.Bot.Weixin.TokenEnv)
633 fmt.Fprintf(&b, "api_base = %q\n", c.Bot.Weixin.APIBase)
634 b.WriteString("\n[bot.dingtalk]\n")
635 fmt.Fprintf(&b, "enabled = %v\n", c.Bot.Dingtalk.Enabled)
636 fmt.Fprintf(&b, "client_id = %q\n", c.Bot.Dingtalk.ClientID)
637 fmt.Fprintf(&b, "client_secret = %q\n", c.Bot.Dingtalk.ClientSecret)
638 fmt.Fprintf(&b, "client_id_env = %q\n", c.Bot.Dingtalk.ClientIDEnv)
639 fmt.Fprintf(&b, "secret_env = %q\n", c.Bot.Dingtalk.SecretEnv)
640 fmt.Fprintf(&b, "bot_name = %q\n", c.Bot.Dingtalk.BotName)
641 fmt.Fprintf(&b, "require_mention = %v\n", c.Bot.Dingtalk.RequireMention)
642 if strings.TrimSpace(c.Bot.Dingtalk.Model) != "" {
643 fmt.Fprintf(&b, "model = %q\n", strings.TrimSpace(c.Bot.Dingtalk.Model))
644 }
645 if strings.TrimSpace(c.Bot.Dingtalk.ToolApprovalMode) != "" {
646 fmt.Fprintf(&b, "tool_approval_mode = %q\n", NormalizeToolApprovalMode(c.Bot.Dingtalk.ToolApprovalMode))
647 }
648 if strings.TrimSpace(c.Bot.Dingtalk.WorkspaceRoot) != "" {
649 fmt.Fprintf(&b, "workspace_root = %q\n", strings.TrimSpace(c.Bot.Dingtalk.WorkspaceRoot))
650 }
651 if parts := renderBotAccess(c.Bot.Dingtalk.Access); parts != "" {
652 fmt.Fprintf(&b, "access = %s\n", parts)
653 }
654 if len(c.Bot.Dingtalk.SessionMappings) > 0 {
655 fmt.Fprintf(&b, "session_mappings = %s\n", renderBotSessionMappings(c.Bot.Dingtalk.SessionMappings))
656 }
657 for _, conn := range c.Bot.Connections {
658 b.WriteString("\n[[bot.connections]]\n")
659 fmt.Fprintf(&b, "id = %q\n", conn.ID)
660 fmt.Fprintf(&b, "provider = %q\n", conn.Provider)
661 fmt.Fprintf(&b, "domain = %q\n", conn.Domain)
662 fmt.Fprintf(&b, "label = %q\n", conn.Label)
663 fmt.Fprintf(&b, "enabled = %v\n", conn.Enabled)
664 fmt.Fprintf(&b, "status = %q\n", conn.Status)
665 if conn.Model != "" {
666 fmt.Fprintf(&b, "model = %q\n", conn.Model)
667 }
668 if conn.ToolApprovalMode != "" {
669 fmt.Fprintf(&b, "tool_approval_mode = %q\n", NormalizeToolApprovalMode(conn.ToolApprovalMode))
670 }
671 if conn.WorkspaceRoot != "" {
672 fmt.Fprintf(&b, "workspace_root = %q\n", conn.WorkspaceRoot)
673 }
674 if parts := renderBotAccess(conn.Access); parts != "" {
675 fmt.Fprintf(&b, "access = %s\n", parts)
676 }
677 if conn.LastError != "" {
678 fmt.Fprintf(&b, "last_error = %q\n", conn.LastError)
679 }
680 if conn.CreatedAt != "" {
681 fmt.Fprintf(&b, "created_at = %q\n", conn.CreatedAt)
682 }
683 if conn.UpdatedAt != "" {
684 fmt.Fprintf(&b, "updated_at = %q\n", conn.UpdatedAt)
685 }
686 if parts := renderBotCredential(conn.Credential); parts != "" {
687 fmt.Fprintf(&b, "credential = %s\n", parts)
688 }
689 if len(conn.SessionMappings) > 0 {
690 fmt.Fprintf(&b, "session_mappings = %s\n", renderBotSessionMappings(conn.SessionMappings))
691 }
692 }
693 b.WriteString("\n")
694 }
695
696 // [secrets] is user/global only: LoadForRoot discards project values, so
697 // the project scope never renders it. Rendering it here is what lets a
698 // user's saved toggles survive config rewrites (WriteFile re-renders the
699 // whole file from the struct).
700 if scope != RenderScopeProject {
701 b.WriteString("[secrets] # credential protection; user/global only, ./reasonix.toml cannot override\n")
702 if c.Secrets.FilterSubprocessEnv {
703 b.WriteString("filter_subprocess_env = true # strip credential-named env vars from tool/hook/LSP/MCP subprocesses\n")
704 } else {
705 b.WriteString("# filter_subprocess_env = false # opt-in; stripping tokens breaks gh, HTTPS git push, npm publish\n")
706 }
707 if c.Secrets.ProtectSensitiveFiles {
708 b.WriteString("protect_sensitive_files = true # hide .env/.git-credentials/key files/~/.ssh from read tools\n")
709 } else {
710 b.WriteString("# protect_sensitive_files = false # opt-in; hiding credential files can break legitimate edit workflows\n")
711 }
712 b.WriteString("\n")
713 }
714
715 renderRemoteConfig(&b, c, scope)
716
717 b.WriteString("# External MCP servers. type: \"stdio\" (default, a subprocess) | \"http\" | \"sse\".\n")
718 b.WriteString("# ${VAR} / ${VAR:-default} are expanded from the environment in command/args/env/url/headers.\n")
719 plugins := tomlPluginsForScope(c.Plugins, scope)
720 if len(plugins) == 0 {
721 b.WriteString("# [[plugins]]\n")
722 b.WriteString("# name = \"example\"\n")
723 b.WriteString("# command = \"reasonix-plugin-example\"\n")
724 b.WriteString("# startup_timeout_seconds = 60 # optional initialize + tools/list cap\n")
725 b.WriteString("# call_timeout_seconds = 600 # optional per-server MCP call timeout\n")
726 b.WriteString("# tool_timeout_seconds = { \"generate_video\" = 1800 } # raw MCP tool names\n")
727 b.WriteString("# [[plugins]] # a remote server over Streamable HTTP\n")
728 b.WriteString("# name = \"stripe\"\n")
729 b.WriteString("# type = \"http\"\n")
730 b.WriteString("# url = \"https://mcp.stripe.com\"\n")
731 b.WriteString("# headers = { Authorization = \"Bearer ${STRIPE_KEY}\" }\n")
732 } else {
733 for _, pl := range plugins {
734 b.WriteString("\n[[plugins]]\n")
735 fmt.Fprintf(&b, "name = %q\n", pl.Name)
736 if pl.Type != "" {
737 fmt.Fprintf(&b, "type = %q\n", pl.Type)
738 }
739 if pl.Command != "" {
740 fmt.Fprintf(&b, "command = %q\n", pl.Command)
741 }
742 if len(pl.Args) > 0 {
743 fmt.Fprintf(&b, "args = %s\n", renderStringArray(pl.Args))
744 }
745 if pl.URL != "" {
746 fmt.Fprintf(&b, "url = %q\n", pl.URL)
747 }
748 if len(pl.Headers) > 0 {
749 fmt.Fprintf(&b, "headers = %s\n", renderStringMap(pl.Headers))
750 }
751 if len(pl.Env) > 0 {
752 fmt.Fprintf(&b, "env = %s\n", renderStringMap(pl.Env))
753 }
754 if pl.StartupTimeoutSeconds > 0 {
755 b.WriteString("# Per-server MCP initialize + tools/list timeout; 0 keeps the global/default cap.\n")
756 fmt.Fprintf(&b, "startup_timeout_seconds = %d\n", pl.StartupTimeoutSeconds)
757 }
758 if pl.CallTimeoutSeconds > 0 {
759 b.WriteString("# Per-server MCP call timeout; 0 keeps the global/default cap.\n")
760 fmt.Fprintf(&b, "call_timeout_seconds = %d\n", pl.CallTimeoutSeconds)
761 }
762 if hasPositiveIntMap(pl.ToolTimeoutSeconds) {
763 b.WriteString("# Raw MCP tool names with per-tool call timeouts.\n")
764 fmt.Fprintf(&b, "tool_timeout_seconds = %s\n", renderIntMap(pl.ToolTimeoutSeconds))
765 }
766 renderPluginPolicy(&b, pl)
767 }
768 }
769
770 return b.String()
771 }
772
773 // tomlPluginsForScope keeps merged runtime entries in their owning config
774 // source. Unknown provenance is retained for callers that construct a Config
775 // directly before saving it to a specific target.
776 func tomlPluginsForScope(plugins []PluginEntry, scope RenderScope) []PluginEntry {
777 if scope == RenderScopeFull {
778 return plugins
779 }
780 out := make([]PluginEntry, 0, len(plugins))
781 for _, pl := range plugins {
782 switch pl.Source {
783 case MCPSourceUnknown:
784 out = append(out, pl)
785 case MCPSourceUserConfig:
786 if scope == RenderScopeUser {
787 out = append(out, pl)
788 }
789 case MCPSourceProjectConfig:
790 if scope == RenderScopeProject {
791 out = append(out, pl)
792 }
793 }
794 }
795 return out
796 }
797
798 // RenderTOMLProjectDelta generates TOML containing only the sections and fields
799 // that differ from built-in defaults. Unlike RenderTOMLForScope (which renders
800 // the full config with comments), this emits clean TOML that can be surgically
801 // merged into an existing project config file via replaceTOMLSection.
802 func RenderTOMLProjectDelta(c *Config) string {
803 if c == nil {
804 return ""
805 }
806 d := Default()
807 var b strings.Builder
808
809 // Top-level scalar fields
810 if v := configVersion(c); v != d.ConfigVersion {
811 fmt.Fprintf(&b, "config_version = %d\n", v)
812 }
813 if c.DefaultModel != d.DefaultModel {
814 fmt.Fprintf(&b, "default_model = %q\n", c.DefaultModel)
815 }
816 if c.Language != "" && c.Language != d.Language {
817 fmt.Fprintf(&b, "language = %q\n", c.Language)
818 }
819
820 // [ui] section — whole-section comparison
821 if !reflect.DeepEqual(c.UI, d.UI) {
822 b.WriteString("[ui]\n")
823 if c.UI.Theme != d.UI.Theme {
824 fmt.Fprintf(&b, "theme = %q\n", c.UITheme())
825 }
826 if s := c.UIThemeStyle(); s != "" && s != d.UIThemeStyle() {
827 fmt.Fprintf(&b, "theme_style = %q\n", s)
828 }
829 if l := c.UIShortcutLayout(); l != "classic" {
830 fmt.Fprintf(&b, "shortcut_layout = %q\n", l)
831 }
832 if strings.TrimSpace(c.UI.CursorShape) != "" {
833 fmt.Fprintf(&b, "cursor_shape = %q\n", c.UICursorShape())
834 }
835 if c.UI.CloseBehavior != d.UI.CloseBehavior {
836 fmt.Fprintf(&b, "close_behavior = %q\n", c.DesktopCloseBehavior())
837 }
838 if c.UI.ShowReasoning != d.UI.ShowReasoning {
839 fmt.Fprintf(&b, "show_reasoning = %v\n", c.UI.ShowReasoning)
840 }
841 if c.UI.ShowTurnUsage != d.UI.ShowTurnUsage {
842 fmt.Fprintf(&b, "show_turn_usage = %v\n", c.UI.ShowTurnUsage)
843 }
844 b.WriteString("\n")
845 }
846
847 // [network] section
848 if !reflect.DeepEqual(c.Network, d.Network) {
849 b.WriteString("[network]\n")
850 if c.Network.ProxyMode != d.Network.ProxyMode {
851 fmt.Fprintf(&b, "proxy_mode = %q\n", c.NetworkProxyMode())
852 }
853 if c.Network.ProxyURL != "" {
854 fmt.Fprintf(&b, "proxy_url = %q\n", c.Network.ProxyURL)
855 }
856 if c.Network.NoProxy != "" {
857 fmt.Fprintf(&b, "no_proxy = %q\n", c.Network.NoProxy)
858 }
859 if c.Network.Proxy.Type != "" || c.Network.Proxy.Server != "" || c.Network.Proxy.Port > 0 || c.Network.Proxy.Username != "" || c.Network.Proxy.Password != "" {
860 b.WriteString("[network.proxy]\n")
861 pt := c.Network.Proxy.Type
862 if pt == "" {
863 pt = "socks5"
864 }
865 fmt.Fprintf(&b, "type = %q\n", pt)
866 if c.Network.Proxy.Server != "" {
867 fmt.Fprintf(&b, "server = %q\n", c.Network.Proxy.Server)
868 }
869 if c.Network.Proxy.Port > 0 {
870 fmt.Fprintf(&b, "port = %d\n", c.Network.Proxy.Port)
871 }
872 if c.Network.Proxy.Username != "" {
873 fmt.Fprintf(&b, "username = %q\n", c.Network.Proxy.Username)
874 }
875 if c.Network.Proxy.Password != "" {
876 fmt.Fprintf(&b, "password = %q\n", c.Network.Proxy.Password)
877 }
878 }
879 b.WriteString("\n")
880 }
881
882 // [agent] section — per-field comparison
883 var agentBuf strings.Builder
884 anyAgent := false
885
886 if sp := strings.TrimSpace(c.Agent.SystemPrompt); sp != "" && sp != d.Agent.SystemPrompt {
887 agentBuf.WriteString("system_prompt = \"\"\"\n")
888 agentBuf.WriteString(sp)
889 agentBuf.WriteString("\"\"\"\n")
890 anyAgent = true
891 }
892 if c.Agent.SystemPromptFile != "" && c.Agent.SystemPromptFile != d.Agent.SystemPromptFile {
893 fmt.Fprintf(&agentBuf, "system_prompt_file = %q\n", c.Agent.SystemPromptFile)
894 anyAgent = true
895 }
896 if c.Agent.Temperature != d.Agent.Temperature {
897 fmt.Fprintf(&agentBuf, "temperature = %s\n", formatFloat(c.Agent.Temperature))
898 anyAgent = true
899 }
900 diffRecoveryAndCompletionValidation(&agentBuf, *c, *d, &anyAgent)
901 if c.Agent.ReasoningLanguage != d.Agent.ReasoningLanguage {
902 if l := c.ReasoningLanguage(); l != "auto" {
903 fmt.Fprintf(&agentBuf, "reasoning_language = %q\n", l)
904 anyAgent = true
905 }
906 }
907 if c.Agent.CompactRatio != d.Agent.CompactRatio {
908 fmt.Fprintf(&agentBuf, "compact_ratio = %s\n", formatFloat(c.Agent.CompactRatio))
909 anyAgent = true
910 }
911 if c.Agent.Keep != nil && !reflect.DeepEqual(c.Agent.Keep, d.Agent.Keep) {
912 fmt.Fprintf(&agentBuf, "keep = %s\n", renderStringArray(c.Agent.Keep))
913 anyAgent = true
914 }
915 if c.Agent.RecentKeep > 0 && c.Agent.RecentKeep != d.Agent.RecentKeep {
916 fmt.Fprintf(&agentBuf, "recent_keep = %d\n", c.Agent.RecentKeep)
917 anyAgent = true
918 }
919 if len(c.Agent.PlanModeReadOnlyCommands) > 0 && !reflect.DeepEqual(c.Agent.PlanModeReadOnlyCommands, d.Agent.PlanModeReadOnlyCommands) {
920 fmt.Fprintf(&agentBuf, "plan_mode_read_only_commands = %s\n", renderStringArray(c.Agent.PlanModeReadOnlyCommands))
921 anyAgent = true
922 }
923 renderAgentModelAssignmentDelta(&agentBuf, c, d, &anyAgent)
924 if c.Agent.SubagentEffort != "" && c.Agent.SubagentEffort != d.Agent.SubagentEffort {
925 fmt.Fprintf(&agentBuf, "subagent_effort = %q\n", c.Agent.SubagentEffort)
926 anyAgent = true
927 }
928 if len(c.Agent.SubagentEfforts) > 0 && !reflect.DeepEqual(c.Agent.SubagentEfforts, d.Agent.SubagentEfforts) {
929 fmt.Fprintf(&agentBuf, "subagent_efforts = %s\n", renderStringMap(c.Agent.SubagentEfforts))
930 anyAgent = true
931 }
932 if c.Agent.MaxSubagentDepth != d.Agent.MaxSubagentDepth {
933 fmt.Fprintf(&agentBuf, "max_subagent_depth = %d\n", c.Agent.MaxSubagentDepth)
934 anyAgent = true
935 }
936 if c.Agent.OutputStyle != "" && c.Agent.OutputStyle != d.Agent.OutputStyle {
937 fmt.Fprintf(&agentBuf, "output_style = %q\n", c.Agent.OutputStyle)
938 anyAgent = true
939 }
940
941 if anyAgent {
942 b.WriteString("[agent]\n")
943 b.WriteString(agentBuf.String())
944 b.WriteString("\n")
945 }
946
947 // [[providers]] — include user-defined providers that aren't built-in
948 proj := projectScopedConfigForRender(c)
949 if proj != nil && len(proj.Providers) > 0 && !reflect.DeepEqual(proj.Providers, d.Providers) {
950 for _, p := range reasoningCompatibilitySnapshots(proj.Providers) {
951 b.WriteString("[[providers]]\n")
952 fmt.Fprintf(&b, "name = %q\n", p.Name)
953 fmt.Fprintf(&b, "kind = %q\n", p.Kind)
954 fmt.Fprintf(&b, "base_url = %q\n", p.BaseURL)
955 if p.ChatURL != "" {
956 fmt.Fprintf(&b, "chat_url = %q\n", p.ChatURL)
957 }
958 if p.RequestURL != "" {
959 fmt.Fprintf(&b, "request_url = %q\n", p.RequestURL)
960 }
961 if len(p.Models) > 0 {
962 fmt.Fprintf(&b, "models = %s\n", renderStringArray(p.Models))
963 if p.Default != "" {
964 fmt.Fprintf(&b, "default = %q\n", p.Default)
965 }
966 } else if p.Model != "" {
967 fmt.Fprintf(&b, "model = %q\n", p.Model)
968 }
969 if p.ModelsURL != "" {
970 fmt.Fprintf(&b, "models_url = %q\n", p.ModelsURL)
971 }
972 renderProviderIdentity(&b, p.APIKeyEnv, p.DisplayName)
973 if p.PresetID != "" {
974 fmt.Fprintf(&b, "preset_id = %q\n", p.PresetID)
975 }
976 if p.PresetVersion > 0 {
977 fmt.Fprintf(&b, "preset_version = %d\n", p.PresetVersion)
978 }
979 if len(p.Headers) > 0 {
980 fmt.Fprintf(&b, "headers = %s\n", renderStringMap(p.Headers))
981 }
982 if len(p.ExtraBody) > 0 {
983 fmt.Fprintf(&b, "extra_body = %s\n", renderAnyMap(p.ExtraBody))
984 }
985 if p.AuthHeader {
986 b.WriteString("auth_header = true\n")
987 }
988 if p.ResponsesMode != "" {
989 fmt.Fprintf(&b, "responses_mode = %q\n", p.ResponsesMode)
990 }
991 if p.ResponsesStateful != nil {
992 fmt.Fprintf(&b, "responses_stateful = %t\n", *p.ResponsesStateful)
993 }
994 if p.BalanceURL != "" {
995 fmt.Fprintf(&b, "balance_url = %q\n", p.BalanceURL)
996 }
997 if p.ContextWindow > 0 {
998 fmt.Fprintf(&b, "context_window = %d\n", p.ContextWindow)
999 }
1000 if p.MaxOutputTokens != 0 {
1001 fmt.Fprintf(&b, "max_output_tokens = %d\n", p.MaxOutputTokens)
1002 }
1003 if p.Price != nil {
1004 fmt.Fprintf(&b, "price = %s\n", renderPricingInline(p.Price))
1005 }
1006 if len(p.Prices) > 0 {
1007 fmt.Fprintf(&b, "prices = %s\n", renderPricingMap(p.Prices))
1008 }
1009 if cur := strings.TrimSpace(p.BillingCurrency); cur != "" {
1010 fmt.Fprintf(&b, "billing_currency = %q\n", billing.NormalizeCurrency(cur))
1011 }
1012 if mode := strings.TrimSpace(p.BillingMode); mode != "" && mode != "payg" {
1013 fmt.Fprintf(&b, "billing_mode = %q\n", mode)
1014 }
1015 if p.Thinking != "" {
1016 fmt.Fprintf(&b, "thinking = %q\n", p.Thinking)
1017 }
1018 if p.Effort != "" {
1019 fmt.Fprintf(&b, "effort = %q\n", p.Effort)
1020 }
1021 if p.Vision {
1022 b.WriteString("vision = true\n")
1023 }
1024 if p.VisionModels != nil {
1025 fmt.Fprintf(&b, "vision_models = %s\n", renderStringArray(p.VisionModels))
1026 }
1027 if p.VisionDetail != "" {
1028 fmt.Fprintf(&b, "vision_detail = %q\n", p.VisionDetail)
1029 }
1030 if p.WebSearch != nil {
1031 fmt.Fprintf(&b, "web_search = %t\n", *p.WebSearch)
1032 }
1033 if p.ReasoningProtocol != "" {
1034 fmt.Fprintf(&b, "reasoning_protocol = %q\n", p.ReasoningProtocol)
1035 }
1036 if len(p.SupportedEfforts) > 0 {
1037 fmt.Fprintf(&b, "supported_efforts = %s\n", renderStringArray(p.SupportedEfforts))
1038 }
1039 if p.DefaultEffort != "" {
1040 fmt.Fprintf(&b, "default_effort = %q\n", p.DefaultEffort)
1041 }
1042 if len(p.ModelOverrides) > 0 {
1043 fmt.Fprintf(&b, "model_overrides = %s\n", renderModelOverrides(p.ModelOverrides))
1044 }
1045 if p.NoProxy {
1046 b.WriteString("no_proxy = true\n")
1047 }
1048 b.WriteString("\n")
1049 }
1050 }
1051
1052 renderCheckpointsConfig(&b, c.Checkpoints)
1053 // [tools]
1054 if len(c.Tools.Enabled) > 0 ||
1055 (c.Tools.BashTimeoutSeconds != nil && *c.Tools.BashTimeoutSeconds != 0) ||
1056 (c.Tools.MCPStartupTimeoutSeconds != nil && *c.Tools.MCPStartupTimeoutSeconds > 0) ||
1057 (c.Tools.MCPCallTimeoutSeconds != nil && *c.Tools.MCPCallTimeoutSeconds > 0) {
1058 b.WriteString("[tools]\n")
1059 if len(c.Tools.Enabled) > 0 {
1060 fmt.Fprintf(&b, "enabled = %s\n", renderStringArray(c.Tools.Enabled))
1061 }
1062 if c.Tools.BashTimeoutSeconds != nil && *c.Tools.BashTimeoutSeconds != 0 {
1063 fmt.Fprintf(&b, "bash_timeout_seconds = %d\n", *c.Tools.BashTimeoutSeconds)
1064 }
1065 if c.Tools.MCPStartupTimeoutSeconds != nil && *c.Tools.MCPStartupTimeoutSeconds > 0 {
1066 fmt.Fprintf(&b, "mcp_startup_timeout_seconds = %d\n", *c.Tools.MCPStartupTimeoutSeconds)
1067 }
1068 if c.Tools.MCPCallTimeoutSeconds != nil && *c.Tools.MCPCallTimeoutSeconds > 0 {
1069 fmt.Fprintf(&b, "mcp_call_timeout_seconds = %d\n", *c.Tools.MCPCallTimeoutSeconds)
1070 }
1071 b.WriteString("\n")
1072 }
1073
1074 // [tools.background_jobs]
1075 if c.Tools.BackgroundJobs != d.Tools.BackgroundJobs {
1076 if c.Tools.BackgroundJobs.StalledWarningSeconds != nil && *c.Tools.BackgroundJobs.StalledWarningSeconds > 0 {
1077 b.WriteString("[tools.background_jobs]\n")
1078 fmt.Fprintf(&b, "stalled_warning_seconds = %d\n", *c.Tools.BackgroundJobs.StalledWarningSeconds)
1079 b.WriteString("\n")
1080 }
1081 }
1082
1083 // [tools.shell]
1084 if !reflect.DeepEqual(c.Tools.Shell, d.Tools.Shell) {
1085 b.WriteString("[tools.shell]\n")
1086 if c.Tools.Shell.Prefer != d.Tools.Shell.Prefer {
1087 fmt.Fprintf(&b, "prefer = %q\n", c.Tools.Shell.Prefer)
1088 }
1089 if c.Tools.Shell.Path != d.Tools.Shell.Path {
1090 fmt.Fprintf(&b, "path = %q\n", c.Tools.Shell.Path)
1091 }
1092 b.WriteString("\n")
1093 }
1094
1095 // [lsp]
1096 if !reflect.DeepEqual(c.LSP, d.LSP) {
1097 renderLSPConfig(&b, c.LSP)
1098 }
1099
1100 // [browser]
1101 if !reflect.DeepEqual(c.Browser, d.Browser) {
1102 renderBrowserConfig(&b, c.Browser)
1103 }
1104
1105 // [skills]
1106 if !reflect.DeepEqual(c.Skills, d.Skills) || len(c.explicitProjectSkillKeys) > 0 {
1107 b.WriteString("[skills]\n")
1108 if len(c.Skills.Paths) > 0 || c.keepsProjectSkillKey("paths") {
1109 fmt.Fprintf(&b, "paths = %s\n", renderStringArray(c.Skills.Paths))
1110 }
1111 if len(c.Skills.ExcludedPaths) > 0 || c.keepsProjectSkillKey("excluded_paths") {
1112 fmt.Fprintf(&b, "excluded_paths = %s\n", renderStringArray(c.Skills.ExcludedPaths))
1113 }
1114 if c.Skills.DisableImplicitInvocation || c.keepsProjectSkillKey("disable_implicit_invocation") {
1115 fmt.Fprintf(&b, "disable_implicit_invocation = %t\n", c.Skills.DisableImplicitInvocation)
1116 }
1117 if c.Skills.MaxDepth != 0 || c.keepsProjectSkillKey("max_depth") {
1118 depth := c.Skills.MaxDepth
1119 if depth != 0 {
1120 depth = c.SkillMaxDepth()
1121 }
1122 fmt.Fprintf(&b, "max_depth = %d\n", depth)
1123 }
1124 if disabled := c.DisabledSkillNames(); len(disabled) > 0 || c.keepsProjectSkillKey("disabled_skills") {
1125 fmt.Fprintf(&b, "disabled_skills = %s\n\n", renderStringArray(disabled))
1126 }
1127 }
1128
1129 // [permissions]
1130 if !reflect.DeepEqual(c.Permissions, d.Permissions) {
1131 b.WriteString("[permissions]\n")
1132 mode := c.Permissions.Mode
1133 if mode == "" {
1134 mode = "ask"
1135 }
1136 if mode != "ask" {
1137 fmt.Fprintf(&b, "mode = %q\n", mode)
1138 }
1139 if len(c.Permissions.Deny) > 0 {
1140 fmt.Fprintf(&b, "deny = %s\n", renderStringArray(c.Permissions.Deny))
1141 }
1142 if len(c.Permissions.Allow) > 0 {
1143 fmt.Fprintf(&b, "allow = %s\n", renderStringArray(c.Permissions.Allow))
1144 }
1145 if len(c.Permissions.Ask) > 0 {
1146 fmt.Fprintf(&b, "ask = %s\n", renderStringArray(c.Permissions.Ask))
1147 }
1148 b.WriteString("\n")
1149 }
1150
1151 // [sandbox]
1152 if !reflect.DeepEqual(c.Sandbox, d.Sandbox) {
1153 var sandboxBuf strings.Builder
1154 if c.Sandbox.WorkspaceRoot != "" {
1155 fmt.Fprintf(&sandboxBuf, "workspace_root = %q\n", c.Sandbox.WorkspaceRoot)
1156 }
1157 if len(c.Sandbox.AllowWrite) > 0 {
1158 fmt.Fprintf(&sandboxBuf, "allow_write = %s\n", renderStringArray(c.Sandbox.AllowWrite))
1159 }
1160 // Only persist a bash mode when its effective value differs from the
1161 // cross-platform default.
1162 if strings.TrimSpace(c.Sandbox.Bash) != "" && c.BashMode() != d.BashModeForGOOS(runtimeGOOS) {
1163 fmt.Fprintf(&sandboxBuf, "bash = %q\n", c.BashMode())
1164 }
1165 if c.Sandbox.Network != d.Sandbox.Network {
1166 fmt.Fprintf(&sandboxBuf, "network = %v\n", c.Sandbox.Network)
1167 }
1168 if sandboxBuf.Len() > 0 {
1169 b.WriteString("[sandbox]\n")
1170 b.WriteString(sandboxBuf.String())
1171 b.WriteString("\n")
1172 }
1173 }
1174
1175 // [[plugins]] — always include when set; replaces all existing entries
1176 for _, pl := range tomlPluginsForScope(c.Plugins, RenderScopeProject) {
1177 b.WriteString("[[plugins]]\n")
1178 fmt.Fprintf(&b, "name = %q\n", pl.Name)
1179 if pl.Type != "" {
1180 fmt.Fprintf(&b, "type = %q\n", pl.Type)
1181 }
1182 if pl.Command != "" {
1183 fmt.Fprintf(&b, "command = %q\n", pl.Command)
1184 }
1185 if len(pl.Args) > 0 {
1186 fmt.Fprintf(&b, "args = %s\n", renderStringArray(pl.Args))
1187 }
1188 if pl.URL != "" {
1189 fmt.Fprintf(&b, "url = %q\n", pl.URL)
1190 }
1191 if len(pl.Headers) > 0 {
1192 fmt.Fprintf(&b, "headers = %s\n", renderStringMap(pl.Headers))
1193 }
1194 if len(pl.Env) > 0 {
1195 fmt.Fprintf(&b, "env = %s\n", renderStringMap(pl.Env))
1196 }
1197 if pl.StartupTimeoutSeconds > 0 {
1198 fmt.Fprintf(&b, "startup_timeout_seconds = %d\n", pl.StartupTimeoutSeconds)
1199 }
1200 if pl.CallTimeoutSeconds > 0 {
1201 b.WriteString("# Per-server MCP call timeout; 0 keeps the global/default cap.\n")
1202 fmt.Fprintf(&b, "call_timeout_seconds = %d\n", pl.CallTimeoutSeconds)
1203 }
1204 if hasPositiveIntMap(pl.ToolTimeoutSeconds) {
1205 b.WriteString("# Raw MCP tool names with per-tool call timeouts.\n")
1206 fmt.Fprintf(&b, "tool_timeout_seconds = %s\n", renderIntMap(pl.ToolTimeoutSeconds))
1207 }
1208 renderPluginPolicy(&b, pl)
1209 b.WriteString("\n")
1210 }
1211
1212 return b.String()
1213 }
1214
1215 func renderPricingInline(p *provider.Pricing) string {
1216 if p == nil {
1217 return "{}"
1218 }
1219 return fmt.Sprintf("{ cache_hit = %v, input = %v, output = %v, currency = %q }",
1220 p.CacheHit, p.Input, p.Output, p.Symbol())
1221 }
1222
1223 func renderPricingMap(prices map[string]*provider.Pricing) string {
1224 if len(prices) == 0 {
1225 return "{}"
1226 }
1227 keys := make([]string, 0, len(prices))
1228 for model := range prices {
1229 if strings.TrimSpace(model) != "" && prices[model] != nil {
1230 keys = append(keys, model)
1231 }
1232 }
1233 if len(keys) == 0 {
1234 return "{}"
1235 }
1236 sort.Strings(keys)
1237 var b strings.Builder
1238 b.WriteString("{ ")
1239 for i, model := range keys {
1240 if i > 0 {
1241 b.WriteString(", ")
1242 }
1243 fmt.Fprintf(&b, "%s = %s", strconv.Quote(model), renderPricingInline(prices[model]))
1244 }
1245 b.WriteString(" }")
1246 return b.String()
1247 }
1248
1249 func configVersion(c *Config) int {
1250 if c != nil && c.ConfigVersion > 0 {
1251 return c.ConfigVersion
1252 }
1253 return Default().ConfigVersion
1254 }
1255
1256 func shouldRenderUI(c, defaults *Config, scope RenderScope) bool {
1257 if scope != RenderScopeProject {
1258 return true
1259 }
1260 return !reflect.DeepEqual(c.UI, defaults.UI)
1261 }
1262
1263 func shouldRenderNetwork(c, defaults *Config, scope RenderScope) bool {
1264 if scope != RenderScopeProject {
1265 return true
1266 }
1267 return !reflect.DeepEqual(c.Network, defaults.Network)
1268 }
1269
1270 func shouldRenderEnvironment(c, defaults *Config, scope RenderScope) bool {
1271 if scope != RenderScopeProject {
1272 return true
1273 }
1274 return !reflect.DeepEqual(c.Environment, defaults.Environment)
1275 }
1276
1277 func renderEnvironmentConfig(b *strings.Builder, cfg EnvironmentConfig) {
1278 b.WriteString("[environment]\n")
1279 enabled := true
1280 if cfg.Enabled != nil {
1281 enabled = *cfg.Enabled
1282 }
1283 fmt.Fprintf(b, "enabled = %v # inject a stable startup environment summary into the model prompt\noffline = %v # declare that outbound network access is unavailable; prevents futile retries\n", enabled, cfg.Offline)
1284 if len(cfg.Tools) == 0 {
1285 b.WriteString("# [environment.tools]\n")
1286 b.WriteString("# go = \"/opt/homebrew/bin/go\" # trusted executable path; workspace-local paths are not auto-executed\n\n")
1287 return
1288 }
1289 b.WriteString("\n[environment.tools]\n")
1290 names := make([]string, 0, len(cfg.Tools))
1291 for name := range cfg.Tools {
1292 names = append(names, name)
1293 }
1294 sort.Strings(names)
1295 for _, name := range names {
1296 fmt.Fprintf(b, "%s = %q\n", renderTOMLKeyPart(name), cfg.Tools[name])
1297 }
1298 b.WriteString("\n")
1299 }
1300
1301 func shouldRenderProviders(c, defaults *Config, scope RenderScope) bool {
1302 if scope != RenderScopeProject {
1303 return true
1304 }
1305 return !reflect.DeepEqual(c.Providers, defaults.Providers)
1306 }
1307
1308 func projectScopedConfigForRender(c *Config) *Config {
1309 if c == nil || len(c.providerSources) == 0 {
1310 return c
1311 }
1312 cp := *c
1313 cp.Providers = make([]ProviderEntry, 0, len(c.Providers))
1314 for _, p := range c.Providers {
1315 if c.providerSources[providerMergeKey(p)] == providerSourceUser {
1316 continue
1317 }
1318 cp.Providers = append(cp.Providers, p)
1319 }
1320 cp.Providers = append(cp.Providers, c.shadowedProjectProviders...)
1321 return &cp
1322 }
1323
1324 func shouldRenderBot(c, defaults *Config, scope RenderScope) bool {
1325 if scope != RenderScopeProject {
1326 return true
1327 }
1328 return !reflect.DeepEqual(c.Bot, defaults.Bot)
1329 }
1330
1331 func shouldRenderSystemPrompt(c, defaults *Config, scope RenderScope) bool {
1332 if scope == RenderScopeFull {
1333 return true
1334 }
1335 return strings.TrimSpace(c.Agent.SystemPrompt) != "" && c.Agent.SystemPrompt != defaults.Agent.SystemPrompt
1336 }
1337
1338 func renderLSPConfig(b *strings.Builder, cfg LSPConfig) {
1339 b.WriteString("[lsp]\n")
1340 fmt.Fprintf(b, "enabled = %v # language server tools; servers launch lazily when used\n", cfg.Enabled)
1341 if len(cfg.Servers) == 0 {
1342 b.WriteString("# [lsp.servers.go]\n")
1343 b.WriteString("# command = \"gopls\"\n")
1344 b.WriteString("# args = []\n")
1345 b.WriteString("# extensions = [\".go\"]\n\n")
1346 return
1347 }
1348 b.WriteString("\n")
1349
1350 langs := make([]string, 0, len(cfg.Servers))
1351 for lang := range cfg.Servers {
1352 langs = append(langs, lang)
1353 }
1354 sort.Strings(langs)
1355 for _, lang := range langs {
1356 srv := cfg.Servers[lang]
1357 fmt.Fprintf(b, "[%s]\n", renderTOMLTablePath("lsp", "servers", lang))
1358 if srv.Command != "" {
1359 fmt.Fprintf(b, "command = %q\n", srv.Command)
1360 }
1361 if len(srv.Args) > 0 {
1362 fmt.Fprintf(b, "args = %s\n", renderStringArray(srv.Args))
1363 }
1364 if len(srv.Env) > 0 {
1365 fmt.Fprintf(b, "env = %s\n", renderStringMap(srv.Env))
1366 }
1367 if srv.LanguageID != "" {
1368 fmt.Fprintf(b, "language_id = %q\n", srv.LanguageID)
1369 }
1370 if len(srv.Extensions) > 0 {
1371 fmt.Fprintf(b, "extensions = %s\n", renderStringArray(srv.Extensions))
1372 }
1373 if srv.InstallHint != "" {
1374 fmt.Fprintf(b, "install_hint = %q\n", srv.InstallHint)
1375 }
1376 b.WriteString("\n")
1377 }
1378 }
1379
1380 func renderTOMLKeyPart(key string) string {
1381 if isBareTOMLKey(key) {
1382 return key
1383 }
1384 return strconv.Quote(key)
1385 }
1386
1387 func renderTOMLTablePath(parts ...string) string {
1388 rendered := make([]string, 0, len(parts))
1389 for _, part := range parts {
1390 rendered = append(rendered, renderTOMLKeyPart(part))
1391 }
1392 return strings.Join(rendered, ".")
1393 }
1394
1395 func isBareTOMLKey(key string) bool {
1396 if key == "" {
1397 return false
1398 }
1399 for _, r := range key {
1400 if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-' {
1401 continue
1402 }
1403 return false
1404 }
1405 return true
1406 }
1407
1408 // renderStringArray renders a []string as a TOML inline array.
1409 func renderStringArray(ss []string) string {
1410 var b strings.Builder
1411 b.WriteByte('[')
1412 for i, s := range ss {
1413 if i > 0 {
1414 b.WriteString(", ")
1415 }
1416 fmt.Fprintf(&b, "%q", s)
1417 }
1418 b.WriteByte(']')
1419 return b.String()
1420 }
1421
1422 // renderStringMap renders a map[string]string as a TOML inline table with keys
1423 // in sorted order so output is deterministic (round-trips cleanly).
1424 func renderStringMap(m map[string]string) string {
1425 keys := make([]string, 0, len(m))
1426 for k := range m {
1427 keys = append(keys, k)
1428 }
1429 sort.Strings(keys)
1430 var b strings.Builder
1431 b.WriteString("{ ")
1432 for i, k := range keys {
1433 if i > 0 {
1434 b.WriteString(", ")
1435 }
1436 fmt.Fprintf(&b, "%s = %q", renderTOMLKeyPart(k), m[k])
1437 }
1438 b.WriteString(" }")
1439 return b.String()
1440 }
1441
1442 func renderAnyMap(m map[string]any) string {
1443 keys := make([]string, 0, len(m))
1444 for k, v := range m {
1445 if strings.TrimSpace(k) == "" {
1446 continue
1447 }
1448 if _, ok := renderAnyValue(v); ok {
1449 keys = append(keys, k)
1450 }
1451 }
1452 sort.Strings(keys)
1453 var b strings.Builder
1454 b.WriteString("{ ")
1455 for i, k := range keys {
1456 if i > 0 {
1457 b.WriteString(", ")
1458 }
1459 value, _ := renderAnyValue(m[k])
1460 fmt.Fprintf(&b, "%s = %s", strconv.Quote(k), value)
1461 }
1462 b.WriteString(" }")
1463 return b.String()
1464 }
1465
1466 func renderAnyValue(v any) (string, bool) {
1467 switch x := v.(type) {
1468 case nil:
1469 return "", false
1470 case string:
1471 return strconv.Quote(x), true
1472 case bool:
1473 if x {
1474 return "true", true
1475 }
1476 return "false", true
1477 case int:
1478 return strconv.Itoa(x), true
1479 case int8:
1480 return strconv.FormatInt(int64(x), 10), true
1481 case int16:
1482 return strconv.FormatInt(int64(x), 10), true
1483 case int32:
1484 return strconv.FormatInt(int64(x), 10), true
1485 case int64:
1486 return strconv.FormatInt(x, 10), true
1487 case uint:
1488 return strconv.FormatUint(uint64(x), 10), true
1489 case uint8:
1490 return strconv.FormatUint(uint64(x), 10), true
1491 case uint16:
1492 return strconv.FormatUint(uint64(x), 10), true
1493 case uint32:
1494 return strconv.FormatUint(uint64(x), 10), true
1495 case uint64:
1496 return strconv.FormatUint(x, 10), true
1497 case float32:
1498 return formatFloat(float64(x)), true
1499 case float64:
1500 return formatFloat(x), true
1501 case []any:
1502 parts := make([]string, 0, len(x))
1503 for _, item := range x {
1504 part, ok := renderAnyValue(item)
1505 if !ok {
1506 return "", false
1507 }
1508 parts = append(parts, part)
1509 }
1510 return "[" + strings.Join(parts, ", ") + "]", true
1511 case []string:
1512 return renderStringArray(x), true
1513 case map[string]any:
1514 return renderAnyMap(x), true
1515 case map[string]string:
1516 return renderStringMap(x), true
1517 default:
1518 return "", false
1519 }
1520 }
1521
1522 func hasPositiveIntMap(m map[string]int) bool {
1523 for k, v := range m {
1524 if strings.TrimSpace(k) != "" && v > 0 {
1525 return true
1526 }
1527 }
1528 return false
1529 }
1530
1531 // renderIntMap renders a map[string]int as a TOML inline table with positive
1532 // values only, preserving deterministic key order.
1533 func renderIntMap(m map[string]int) string {
1534 keys := make([]string, 0, len(m))
1535 for k, v := range m {
1536 if strings.TrimSpace(k) != "" && v > 0 {
1537 keys = append(keys, k)
1538 }
1539 }
1540 sort.Strings(keys)
1541 var b strings.Builder
1542 b.WriteString("{ ")
1543 for i, k := range keys {
1544 if i > 0 {
1545 b.WriteString(", ")
1546 }
1547 fmt.Fprintf(&b, "%q = %d", k, m[k])
1548 }
1549 b.WriteString(" }")
1550 return b.String()
1551 }
1552
1553 func renderBotCredential(cred BotConnectionCredential) string {
1554 parts := make(map[string]string)
1555 if cred.AppID != "" {
1556 parts["app_id"] = cred.AppID
1557 }
1558 if cred.AppSecretEnv != "" {
1559 parts["app_secret_env"] = cred.AppSecretEnv
1560 }
1561 if cred.AccountID != "" {
1562 parts["account_id"] = cred.AccountID
1563 }
1564 if cred.TokenEnv != "" {
1565 parts["token_env"] = cred.TokenEnv
1566 }
1567 if len(parts) == 0 {
1568 return ""
1569 }
1570 return renderStringMap(parts)
1571 }
1572
1573 func renderBotAccess(access BotAccessConfig) string {
1574 hasList := len(access.Users) > 0 || len(access.Groups) > 0 || len(access.Approvers) > 0 || len(access.Admins) > 0
1575 if !access.Enabled && !access.AllowAll && !access.PairingEnabled && !hasList {
1576 return ""
1577 }
1578 var parts []string
1579 parts = append(parts, fmt.Sprintf("enabled = %v", access.Enabled))
1580 parts = append(parts, fmt.Sprintf("allow_all = %v", access.AllowAll))
1581 parts = append(parts, fmt.Sprintf("pairing_enabled = %v", access.PairingEnabled))
1582 if len(access.Users) > 0 {
1583 parts = append(parts, "users = "+renderStringArray(access.Users))
1584 }
1585 if len(access.Groups) > 0 {
1586 parts = append(parts, "groups = "+renderStringArray(access.Groups))
1587 }
1588 if len(access.Approvers) > 0 {
1589 parts = append(parts, "approvers = "+renderStringArray(access.Approvers))
1590 }
1591 if len(access.Admins) > 0 {
1592 parts = append(parts, "admins = "+renderStringArray(access.Admins))
1593 }
1594 return "{ " + strings.Join(parts, ", ") + " }"
1595 }
1596
1597 func renderBotSessionMappings(mappings []BotConnectionSessionMapping) string {
1598 var b strings.Builder
1599 b.WriteByte('[')
1600 for i, mapping := range mappings {
1601 if i > 0 {
1602 b.WriteString(", ")
1603 }
1604 parts := map[string]string{
1605 "remote_id": mapping.RemoteID,
1606 "session_id": mapping.SessionID,
1607 }
1608 if mapping.SessionSource != "" {
1609 parts["session_source"] = mapping.SessionSource
1610 }
1611 if mapping.ChatType != "" {
1612 parts["chat_type"] = mapping.ChatType
1613 }
1614 if mapping.UserID != "" {
1615 parts["user_id"] = mapping.UserID
1616 }
1617 if mapping.ThreadID != "" {
1618 parts["thread_id"] = mapping.ThreadID
1619 }
1620 if mapping.Scope != "" {
1621 parts["scope"] = mapping.Scope
1622 }
1623 if mapping.WorkspaceRoot != "" {
1624 parts["workspace_root"] = mapping.WorkspaceRoot
1625 }
1626 if mapping.UpdatedAt != "" {
1627 parts["updated_at"] = mapping.UpdatedAt
1628 }
1629 b.WriteString(renderStringMap(parts))
1630 }
1631 b.WriteByte(']')
1632 return b.String()
1633 }
1634
1635 func renderBotRoute(b *strings.Builder, route BotRouteConfig) {
1636 if strings.TrimSpace(route.ConnectionID) != "" {
1637 fmt.Fprintf(b, "connection_id = %q\n", strings.TrimSpace(route.ConnectionID))
1638 }
1639 if strings.TrimSpace(route.Platform) != "" {
1640 fmt.Fprintf(b, "platform = %q\n", strings.TrimSpace(route.Platform))
1641 }
1642 if strings.TrimSpace(route.ChatType) != "" {
1643 fmt.Fprintf(b, "chat_type = %q\n", strings.TrimSpace(route.ChatType))
1644 }
1645 if strings.TrimSpace(route.ChatID) != "" {
1646 fmt.Fprintf(b, "chat_id = %q\n", strings.TrimSpace(route.ChatID))
1647 }
1648 if strings.TrimSpace(route.UserID) != "" {
1649 fmt.Fprintf(b, "user_id = %q\n", strings.TrimSpace(route.UserID))
1650 }
1651 if strings.TrimSpace(route.ThreadID) != "" {
1652 fmt.Fprintf(b, "thread_id = %q\n", strings.TrimSpace(route.ThreadID))
1653 }
1654 if strings.TrimSpace(route.Model) != "" {
1655 fmt.Fprintf(b, "model = %q\n", strings.TrimSpace(route.Model))
1656 }
1657 if strings.TrimSpace(route.ToolApprovalMode) != "" {
1658 fmt.Fprintf(b, "tool_approval_mode = %q\n", NormalizeToolApprovalMode(route.ToolApprovalMode))
1659 }
1660 if strings.TrimSpace(route.WorkspaceRoot) != "" {
1661 fmt.Fprintf(b, "workspace_root = %q\n", strings.TrimSpace(route.WorkspaceRoot))
1662 }
1663 }
1664
1665 func renderBotDesktopWatcher(b *strings.Builder, watcher BotDesktopWatcherConfig) {
1666 if strings.TrimSpace(watcher.Platform) != "" {
1667 fmt.Fprintf(b, "platform = %q\n", strings.TrimSpace(watcher.Platform))
1668 }
1669 if strings.TrimSpace(watcher.ConnectionID) != "" {
1670 fmt.Fprintf(b, "connection_id = %q\n", strings.TrimSpace(watcher.ConnectionID))
1671 }
1672 if strings.TrimSpace(watcher.Domain) != "" {
1673 fmt.Fprintf(b, "domain = %q\n", strings.TrimSpace(watcher.Domain))
1674 }
1675 if strings.TrimSpace(watcher.ChatType) != "" {
1676 fmt.Fprintf(b, "chat_type = %q\n", strings.TrimSpace(watcher.ChatType))
1677 }
1678 if strings.TrimSpace(watcher.ChatID) != "" {
1679 fmt.Fprintf(b, "chat_id = %q\n", strings.TrimSpace(watcher.ChatID))
1680 }
1681 }
1682
1683 // renderRuleList emits a permission rule list. A populated list renders as an
1684 // active TOML array; an empty one renders as a commented example so `reasonix setup`
1685 // scaffolds discoverable guidance without imposing surprising rules.
1686 func renderRuleList(key string, rules []string, example string) string {
1687 if len(rules) == 0 {
1688 return fmt.Sprintf("# %s = %s\n", key, example)
1689 }
1690 var b strings.Builder
1691 fmt.Fprintf(&b, "%s = [", key)
1692 for i, r := range rules {
1693 if i > 0 {
1694 b.WriteString(", ")
1695 }
1696 fmt.Fprintf(&b, "%q", r)
1697 }
1698 b.WriteString("]\n")
1699 return b.String()
1700 }
1701
1702 // formatFloat ensures a float renders with a decimal point so TOML types it as a
1703 // float, not an integer (e.g. 0 -> "0.0").
1704 func formatFloat(f float64) string {
1705 s := strconv.FormatFloat(f, 'f', -1, 64)
1706 if !strings.Contains(s, ".") {
1707 s += ".0"
1708 }
1709 return s
1710 }
1711
1711 lines GO