magi-code 0.105.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
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, num::NonZeroUsize, path::PathBuf};

use super::helpers::is_false;

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SideAgentSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

impl SideAgentSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn validate(&self) -> anyhow::Result<()> {
        anyhow::ensure!(
            self.provider.is_some() == self.model.is_some(),
            "agent.side.provider and agent.side.model must both be configured, or both omitted to inherit the primary provider/model"
        );
        for (field, value) in [("provider", &self.provider), ("model", &self.model)] {
            if let Some(value) = value {
                super::tools::validate_model_identifier(&format!("agent.side.{field}"), value)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SubagentsSettings {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub disabled: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_validation_max_retries: Option<u64>,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl SubagentsSettings {
    pub(crate) fn schema_validation_max_retries(&self) -> u64 {
        self.schema_validation_max_retries
            .unwrap_or(DEFAULT_SUBAGENT_SCHEMA_VALIDATION_MAX_RETRIES)
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct ModelsSettings {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub enabled: Vec<String>,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl ModelsSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

pub const DEFAULT_SUBAGENT_SCHEMA_VALIDATION_MAX_RETRIES: u64 = 2;
pub const MAX_SUBAGENT_SCHEMA_VALIDATION_MAX_RETRIES: u64 = 5;

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct IntegrationsSettings {
    #[serde(default, skip_serializing_if = "HerdrSettings::is_default")]
    pub herdr: HerdrSettings,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl IntegrationsSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct HerdrSettings {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl HerdrSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

pub const DEFAULT_TUI_SUBAGENT_CARD_ROWS: usize = 16;
pub const MIN_TUI_SUBAGENT_CARD_ROWS: usize = 1;
pub const MAX_TUI_SUBAGENT_CARD_ROWS: usize = 50;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum HeaderPanel {
    Summary,
    ActivityTree,
    SessionFiles,
    BackgroundJobs,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(default)]
pub(crate) struct PanelLayoutSettings {
    pub(crate) open: Vec<HeaderPanel>,
    pub(crate) pinned: bool,
    pub(crate) opened_by_pin: bool,
    #[serde(flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl PanelLayoutSettings {
    fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct TuiSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(range(min = 1, max = 50))]
    pub(crate) subagent_card_rows: Option<usize>,
    #[serde(default, skip_serializing_if = "PanelLayoutSettings::is_default")]
    pub(crate) panel_layout: PanelLayoutSettings,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl TuiSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn subagent_card_rows(&self) -> usize {
        self.subagent_card_rows
            .unwrap_or(DEFAULT_TUI_SUBAGENT_CARD_ROWS)
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct InstructionsSettings {
    #[serde(default, skip_serializing_if = "is_false")]
    pub subdir_discovery: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub additional_markdown_paths: Vec<PathBuf>,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl InstructionsSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SkillsSettings {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub additional_paths: Vec<PathBuf>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub disabled: Vec<String>,
    #[serde(default, flatten)]
    pub(crate) extra: BTreeMap<String, serde_json::Value>,
}

impl SkillsSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

pub(crate) const DEFAULT_AUTO_COMPACTIONS_PER_RUN: u8 = 4;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AutoCompactionLimit {
    Limited(NonZeroUsize),
    NoCountCap,
}

impl AutoCompactionLimit {
    pub(crate) fn allows(self, completed_compactions: usize) -> bool {
        match self {
            Self::Limited(limit) => completed_compactions < limit.get(),
            Self::NoCountCap => true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(default)]
pub struct AutoCompactionSettings {
    pub enabled: bool,
    pub threshold_percent: Option<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub threshold_tokens: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(
        description = "Maximum automatic compactions per run. When omitted, the effective runtime default is 4. Set to 0 to remove only this per-run compaction-count cap.",
        extend("default" = DEFAULT_AUTO_COMPACTIONS_PER_RUN)
    )]
    pub max_compactions_per_run: Option<u8>,
}

impl Default for AutoCompactionSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            threshold_percent: Some(80),
            threshold_tokens: None,
            max_compactions_per_run: None,
        }
    }
}

impl AutoCompactionSettings {
    pub(crate) fn is_enabled(&self) -> bool {
        self.enabled
    }

    pub(crate) fn compaction_limit(&self) -> AutoCompactionLimit {
        let configured = self
            .max_compactions_per_run
            .unwrap_or(DEFAULT_AUTO_COMPACTIONS_PER_RUN);
        NonZeroUsize::new(usize::from(configured)).map_or(
            AutoCompactionLimit::NoCountCap,
            AutoCompactionLimit::Limited,
        )
    }

    fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn triggered(&self, projected_tokens: u64, model_max_tokens: u64) -> bool {
        if !self.enabled {
            return false;
        }
        self.threshold_percent.is_some_and(|percent| {
            u128::from(projected_tokens) * 100 >= u128::from(model_max_tokens) * u128::from(percent)
        }) || self
            .threshold_tokens
            .is_some_and(|threshold| projected_tokens >= threshold)
    }

    pub(crate) fn threshold_display(&self) -> Option<String> {
        match (self.threshold_percent, self.threshold_tokens) {
            (Some(percent), Some(tokens)) => Some(format!("{percent}% or {tokens} tokens")),
            (Some(percent), None) => Some(format!("{percent}%")),
            (None, Some(tokens)) => Some(format!("{tokens} tokens")),
            (None, None) => None,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct CompactionSettings {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "AutoCompactionSettings::is_default")]
    pub auto: AutoCompactionSettings,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CompactionConfig {
    pub(crate) provider: String,
    pub(crate) model: String,
}

impl CompactionSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn resolve_config(
        &self,
        active_provider: &str,
        active_model: &str,
    ) -> Result<CompactionConfig, String> {
        let provider = self.provider.as_deref().map(str::trim);
        let model = self.model.as_deref().map(str::trim);
        match (provider, model) {
            (None, None) => Ok(CompactionConfig {
                provider: non_blank_active(active_provider, "provider")?.to_string(),
                model: non_blank_active(active_model, "model")?.to_string(),
            }),
            (Some(provider), Some(model)) if !provider.is_empty() && !model.is_empty() => {
                Ok(CompactionConfig {
                    provider: provider.to_string(),
                    model: model.to_string(),
                })
            }
            _ => Err("compaction.provider and compaction.model must either both be configured and non-blank, or both be omitted to inherit the active provider/model".to_string()),
        }
    }
}

fn non_blank_active<'a>(value: &'a str, field: &str) -> Result<&'a str, String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        Err(format!(
            "active assistant {field} is blank; set active provider/model or configure both compaction.provider and compaction.model"
        ))
    } else {
        Ok(trimmed)
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SessionTitleSettings {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SessionTitleConfig {
    pub(crate) provider: String,
    pub(crate) model: String,
}

impl SessionTitleSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn eligible_config(&self) -> Result<Option<SessionTitleConfig>, String> {
        if !self.enabled {
            return Ok(None);
        }
        let provider = self
            .provider
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .ok_or_else(|| "session_titles.enabled is true but session_titles.provider is missing or blank; set an explicit title provider or disable session_titles".to_string())?;
        let model = self
            .model
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .ok_or_else(|| "session_titles.enabled is true but session_titles.model is missing or blank; set an explicit title model or disable session_titles".to_string())?;
        Ok(Some(SessionTitleConfig {
            provider: provider.to_string(),
            model: model.to_string(),
        }))
    }
}

/// Independent session summarizer options; omitted selection fields inherit at runtime.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct SummarizerSettings {
    /// Enable the summarizer automatically for each session.
    #[serde(default)]
    pub auto_start: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning: Option<crate::thinking::ThinkingLevel>,
    /// Replace the built-in summarizer system prompt, rather than append to it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
}

impl SummarizerSettings {
    pub(crate) fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub(crate) fn validate(&self) -> anyhow::Result<()> {
        for (field, value) in [("provider", &self.provider), ("model", &self.model)] {
            if let Some(value) = value {
                super::tools::validate_model_identifier(
                    &format!("agent.summarizer.{field}"),
                    value,
                )?;
            }
        }
        if self
            .prompt
            .as_deref()
            .is_some_and(|prompt| prompt.trim().is_empty())
        {
            anyhow::bail!(
                "agent.summarizer.prompt must not be blank; omit it to use the built-in prompt"
            );
        }
        Ok(())
    }
}