magi-code 0.96.1

Repository-aware CLI coding agent for terminal work
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use std::{collections::BTreeMap, net::IpAddr};

use super::{
    agent::{
        AutoCompactionSettings, CompactionSettings, MAX_SUBAGENT_SCHEMA_VALIDATION_MAX_RETRIES,
        MAX_TUI_SUBAGENT_CARD_ROWS, MIN_TUI_SUBAGENT_CARD_ROWS, SubagentsSettings, TuiSettings,
    },
    core::Settings,
    providers::{MAX_PROVIDER_STREAM_SEMANTIC_PROGRESS_TIMEOUT_SECONDS, ProviderStreamSettings},
    services::{
        LspSettings, MAX_LSP_DIAGNOSTICS_WAIT_MS, MAX_LSP_IDLE_SHUTDOWN_MINUTES,
        MAX_MCP_TIMEOUT_SECONDS, McpHttpServerConfig, McpOAuthConfig, McpServerConfig,
        McpServersSettings,
    },
};
use crate::config::custom_provider_config::validate_custom_provider_settings;

pub(crate) fn validate_settings(settings: &Settings) -> anyhow::Result<()> {
    validate_custom_provider_settings(settings)?;
    validate_context_model_overrides(settings.context.as_ref())?;
    validate_mcp_servers_settings(&settings.mcp_servers)?;
    validate_lsp_settings(&settings.lsp)?;
    settings.compaction.validate()?;
    settings.summarizer.validate()?;
    settings.side.validate()?;
    settings.provider_stream.validate()?;
    settings.subagents.validate()?;
    settings.tui.validate()?;
    settings.tools.code_mode.validate()?;
    anyhow::ensure!(
        !settings
            .tools
            .disabled
            .iter()
            .any(|name| name.trim() == "code_mode"),
        "use capabilities.tools.code_mode.enabled instead of disabling code_mode in tools.disabled"
    );
    for (name, threshold) in [
        (
            "internal_tooling.jev.humanize_protection.content_threshold",
            settings.jev.humanize_protection.content_threshold,
        ),
        (
            "internal_tooling.jev.humanize_protection.humanized_threshold",
            settings.jev.humanize_protection.humanized_threshold,
        ),
        (
            "internal_tooling.jev.skill_suggestion.gate_threshold",
            settings.jev.skill_suggestion.gate_threshold,
        ),
        (
            "internal_tooling.jev.skill_suggestion.fit_threshold",
            settings.jev.skill_suggestion.fit_threshold,
        ),
        (
            "internal_tooling.jev.compaction_timing.threshold",
            settings.jev.compaction_timing.threshold,
        ),
    ] {
        anyhow::ensure!(
            (0.0..=1.0).contains(&threshold),
            "{name} must be between 0 and 1"
        );
    }
    anyhow::ensure!(
        (1..=99).contains(&settings.jev.compaction_timing.soft_threshold_percent),
        "internal_tooling.jev.compaction_timing.soft_threshold_percent must be between 1 and 99"
    );
    let completion = &settings.jev.completion_verification;
    anyhow::ensure!(
        (0.0..=1.0).contains(&completion.threshold),
        "internal_tooling.jev.completion_verification.threshold must be between 0 and 1"
    );
    anyhow::ensure!(
        completion.max_state_bytes > 0,
        "internal_tooling.jev.completion_verification.max_state_bytes must be positive"
    );
    anyhow::ensure!(
        settings.jev.enabled || !completion.enabled,
        "internal_tooling.jev.completion_verification.enabled requires internal_tooling.jev.enabled"
    );

    anyhow::ensure!(
        settings.jev.prompt_injection_protection.max_assessed_bytes > 0,
        "internal_tooling.jev.prompt_injection_protection.max_assessed_bytes must be positive"
    );

    for (name, enabled) in [
        (
            "internal_tooling.jev.bash_file_tracking.enabled",
            settings.jev.bash_file_tracking.enabled,
        ),
        (
            "internal_tooling.jev.skill_suggestion.enabled",
            settings.jev.skill_suggestion.enabled,
        ),
        (
            "internal_tooling.jev.compaction_timing.enabled",
            settings.jev.compaction_timing.enabled,
        ),
    ] {
        anyhow::ensure!(
            settings.jev.enabled || !enabled,
            "{name} requires internal_tooling.jev.enabled"
        );
    }
    if settings.jev.enabled {
        crate::typesafe::TypeSafeClient::from_environment()?;
    }
    Ok(())
}

fn validate_context_model_overrides(
    context: Option<&crate::context::ContextBudget>,
) -> anyhow::Result<()> {
    let Some(context) = context else {
        return Ok(());
    };
    for (key, model_override) in &context.model_overrides {
        let Some((provider, model)) = key.split_once('/') else {
            anyhow::bail!("context.model_overrides key '{key}' must use provider/model");
        };
        if provider.is_empty() || model.is_empty() {
            anyhow::bail!("context.model_overrides key '{key}' must use non-empty provider/model");
        }
        if key
            .chars()
            .any(|ch| ch.is_ascii_whitespace() || ch.is_ascii_control())
        {
            anyhow::bail!(
                "context.model_overrides key '{key}' must not contain ASCII whitespace or control characters"
            );
        }
        if model_override.is_empty() {
            anyhow::bail!(
                "context.model_overrides.{key} must set at least one of max_tokens, reserve_tokens, or keep_recent_tokens"
            );
        }
    }
    Ok(())
}

pub(crate) fn validate_lsp_settings(settings: &LspSettings) -> anyhow::Result<()> {
    if !(1..=MAX_LSP_DIAGNOSTICS_WAIT_MS).contains(&settings.diagnostics_wait_ms) {
        anyhow::bail!(
            "lsp.diagnostics_wait_ms must be between 1 and {MAX_LSP_DIAGNOSTICS_WAIT_MS} milliseconds"
        );
    }
    if !(1..=MAX_LSP_IDLE_SHUTDOWN_MINUTES).contains(&settings.idle_shutdown_minutes) {
        anyhow::bail!(
            "lsp.idle_shutdown_minutes must be between 1 and {MAX_LSP_IDLE_SHUTDOWN_MINUTES} minutes"
        );
    }
    for (name, config) in &settings.servers {
        validate_lsp_server_name(name)?;
        if config.command.trim().is_empty() {
            anyhow::bail!("lsp.servers.{name}.command must not be empty");
        }
    }
    Ok(())
}

fn validate_lsp_server_name(name: &str) -> anyhow::Result<()> {
    if name.trim().is_empty() {
        anyhow::bail!("lsp server name must not be empty");
    }
    if name.contains("__") {
        anyhow::bail!("lsp server name '{name}' must not contain '__'");
    }
    Ok(())
}

pub(crate) fn validate_mcp_servers_settings(servers: &McpServersSettings) -> anyhow::Result<()> {
    for (name, config) in servers {
        validate_mcp_server_name(name)?;
        if config.enabled() {
            validate_mcp_server(name, config)?;
        }
    }
    Ok(())
}

pub(super) fn validate_mcp_server(name: &str, config: &McpServerConfig) -> anyhow::Result<()> {
    match config {
        McpServerConfig::Stdio(stdio) => {
            if stdio.command.trim().is_empty() {
                anyhow::bail!("mcp_servers.{name}.command must not be empty");
            }
            validate_mcp_timeout(name, stdio.timeout)
        }
        McpServerConfig::Http(http) => validate_mcp_http_server(name, http),
    }
}

fn validate_mcp_timeout(name: &str, timeout: Option<u64>) -> anyhow::Result<()> {
    if let Some(timeout) = timeout
        && !(1..=MAX_MCP_TIMEOUT_SECONDS).contains(&timeout)
    {
        anyhow::bail!(
            "mcp_servers.{name}.timeout must be between 1 and {MAX_MCP_TIMEOUT_SECONDS} seconds"
        );
    }
    Ok(())
}

fn validate_mcp_http_server(name: &str, config: &McpHttpServerConfig) -> anyhow::Result<()> {
    validate_mcp_http_url(name, &config.url)?;
    validate_mcp_timeout(name, config.timeout)?;
    if let Some(oauth) = &config.oauth {
        validate_mcp_oauth_config(name, oauth, &config.headers)?;
    }
    for (header_name, header_value) in &config.headers {
        validate_mcp_http_header_name(name, header_name)?;
        if reqwest::header::HeaderValue::from_str(header_value).is_err() {
            anyhow::bail!(
                "mcp_servers.{name}.headers.{header_name} contains an invalid header value"
            );
        }
    }
    Ok(())
}

fn validate_mcp_oauth_config(
    name: &str,
    oauth: &McpOAuthConfig,
    headers: &BTreeMap<String, String>,
) -> anyhow::Result<()> {
    for header_name in headers.keys() {
        if header_name.eq_ignore_ascii_case("authorization")
            || header_name.eq_ignore_ascii_case("proxy-authorization")
        {
            anyhow::bail!(
                "mcp_servers.{name}.headers.{header_name} must not be configured when mcp_servers.{name}.oauth is configured"
            );
        }
    }
    if let Some(client_id) = &oauth.client_id
        && client_id.trim().is_empty()
    {
        anyhow::bail!("mcp_servers.{name}.oauth.client_id must not be empty");
    }
    for scope in &oauth.scopes {
        if scope.trim().is_empty()
            || scope
                .bytes()
                .any(|byte| !byte.is_ascii() || byte.is_ascii_control())
        {
            anyhow::bail!(
                "mcp_servers.{name}.oauth.scopes entries must be non-empty printable ASCII"
            );
        }
    }
    if let Some(url) = &oauth.authorization_server {
        validate_mcp_http_url_field(name, "oauth.authorization_server", url)?;
    }
    Ok(())
}

fn validate_mcp_http_url(name: &str, url: &str) -> anyhow::Result<()> {
    validate_mcp_http_url_field(name, "url", url)
}

pub(crate) fn validate_mcp_http_url_field(
    name: &str,
    field: &str,
    url: &str,
) -> anyhow::Result<()> {
    let parsed = reqwest::Url::parse(url)
        .map_err(|_| anyhow::anyhow!("mcp_servers.{name}.{field} must be an absolute HTTP URL"))?;
    if !parsed.username().is_empty() || parsed.password().is_some() {
        anyhow::bail!("mcp_servers.{name}.{field} must not contain credentials");
    }
    match parsed.scheme() {
        "https" => Ok(()),
        "http" if is_loopback_http_host(parsed.host_str()) => Ok(()),
        "http" => anyhow::bail!(
            "mcp_servers.{name}.{field} must use https; http is allowed only for loopback hosts"
        ),
        _ => anyhow::bail!("mcp_servers.{name}.{field} must use http or https"),
    }
}

fn is_loopback_http_host(host: Option<&str>) -> bool {
    match host {
        Some("localhost") => true,
        Some(host) => host
            .trim_matches(['[', ']'])
            .parse::<IpAddr>()
            .is_ok_and(|ip| ip.is_loopback()),
        None => false,
    }
}

fn validate_mcp_http_header_name(server_name: &str, header_name: &str) -> anyhow::Result<()> {
    if header_name.is_empty() {
        anyhow::bail!("mcp_servers.{server_name}.headers contains an empty header name");
    }
    if header_name
        .bytes()
        .any(|byte| !byte.is_ascii() || byte.is_ascii_control() || byte == b':' || byte == b' ')
    {
        anyhow::bail!(
            "mcp_servers.{server_name}.headers.{header_name} must be visible ASCII without colon, spaces, or control characters"
        );
    }
    Ok(())
}

pub(crate) fn validate_mcp_server_name(name: &str) -> anyhow::Result<()> {
    if name.is_empty() {
        anyhow::bail!("mcp server name must not be empty");
    }
    if name.contains("__") {
        anyhow::bail!("mcp server name '{name}' must not contain '__'");
    }
    if name.ends_with('_') {
        anyhow::bail!(
            "mcp server name '{name}' must not end with '_' because mcp__<server>__<tool> would be ambiguous; choose a name that does not end with '_'"
        );
    }
    if !name
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
    {
        anyhow::bail!(
            "mcp server name '{name}' must contain only ASCII letters, digits, '_' or '-'"
        );
    }
    Ok(())
}

impl ProviderStreamSettings {
    fn validate(&self) -> anyhow::Result<()> {
        validate_provider_stream_timeout(
            "provider_stream.semantic_progress_timeout_seconds",
            self.semantic_progress_timeout_seconds,
        )?;
        validate_provider_stream_timeout(
            "provider_stream.subagent_semantic_progress_timeout_seconds",
            self.subagent_semantic_progress_timeout_seconds,
        )
    }
}

fn validate_provider_stream_timeout(field: &str, value: Option<u64>) -> anyhow::Result<()> {
    if let Some(value) = value
        && !(1..=MAX_PROVIDER_STREAM_SEMANTIC_PROGRESS_TIMEOUT_SECONDS).contains(&value)
    {
        anyhow::bail!(
            "{field} must be between 1 and {MAX_PROVIDER_STREAM_SEMANTIC_PROGRESS_TIMEOUT_SECONDS} seconds"
        );
    }
    Ok(())
}

impl SubagentsSettings {
    fn validate(&self) -> anyhow::Result<()> {
        if let Some(retries) = self.schema_validation_max_retries
            && retries > MAX_SUBAGENT_SCHEMA_VALIDATION_MAX_RETRIES
        {
            anyhow::bail!(
                "subagents.schema_validation_max_retries must be between 0 and {MAX_SUBAGENT_SCHEMA_VALIDATION_MAX_RETRIES}"
            );
        }
        Ok(())
    }
}

impl TuiSettings {
    fn validate(&self) -> anyhow::Result<()> {
        if let Some(rows) = self.subagent_card_rows
            && !(MIN_TUI_SUBAGENT_CARD_ROWS..=MAX_TUI_SUBAGENT_CARD_ROWS).contains(&rows)
        {
            anyhow::bail!(
                "tui.subagent_card_rows must be between {MIN_TUI_SUBAGENT_CARD_ROWS} and {MAX_TUI_SUBAGENT_CARD_ROWS}"
            );
        }
        Ok(())
    }
}

impl AutoCompactionSettings {
    fn validate(&self) -> anyhow::Result<()> {
        if self.enabled && self.threshold_percent.is_none() && self.threshold_tokens.is_none() {
            anyhow::bail!(
                "compaction.auto.enabled requires at least one of threshold_percent or threshold_tokens"
            );
        }
        if let Some(percent) = self.threshold_percent
            && !(1..=100).contains(&percent)
        {
            anyhow::bail!("compaction.auto.threshold_percent must be between 1 and 100");
        }
        if let Some(tokens) = self.threshold_tokens
            && tokens == 0
        {
            anyhow::bail!("compaction.auto.threshold_tokens must be greater than 0");
        }
        Ok(())
    }
}

impl CompactionSettings {
    fn validate(&self) -> anyhow::Result<()> {
        self.auto.validate()?;
        self.auto_for_provider(crate::providers::CLAUDE_SUBSCRIPTION_PROVIDER, usize::MAX)
            .validate()
            .map_err(|error| {
                anyhow::anyhow!(
                    error
                        .to_string()
                        .replace("compaction.auto", "compaction.claude_subscription")
                )
            })?;
        anyhow::ensure!(
            (1..crate::providers::CLAUDE_SUBSCRIPTION_MAX_PROMPT_TOKENS)
                .contains(&self.claude_subscription.reserve_tokens),
            "compaction.claude_subscription.reserve_tokens must be between 1 and 201999"
        );
        if !self.claude_subscription.allow_compaction {
            self.resolve_config(crate::providers::CLAUDE_SUBSCRIPTION_PROVIDER, "default")
                .map_err(anyhow::Error::msg)?;
        }
        Ok(())
    }
}