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