magi-code 0.96.2

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
use std::cmp::Ordering;

pub(crate) const MAX_SERVICE_TIER_BYTES: usize = 64;

/// Accept only small, opaque provider identifiers; metadata is untrusted and is never echoed raw.
pub(crate) fn parse_returned_service_tier(value: &serde_json::Value) -> Option<String> {
    let value = value.as_str()?.trim();
    if value.is_empty()
        || value.len() > MAX_SERVICE_TIER_BYTES
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
    {
        return None;
    }
    let lower = value.to_ascii_lowercase();
    if lower.starts_with("sk-")
        || lower.starts_with("eyj")
        || ["token", "secret", "bearer", "api_key", "authorization"]
            .iter()
            .any(|marker| lower.contains(marker))
    {
        return None;
    }
    Some(value.to_string())
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub(crate) enum FastOutcome {
    #[default]
    NotRequested,
    Confirmed,
    Different(String),
    Unconfirmed,
}

pub(crate) fn fast_outcome(
    provider_id: &str,
    requested: Option<&str>,
    returned: Option<&str>,
) -> FastOutcome {
    let Some(requested) = requested else {
        return FastOutcome::NotRequested;
    };
    match returned {
        // ChatGPT-authenticated Codex routes Fast server-side; these generic
        // response tiers neither confirm Fast nor establish a downgrade.
        Some("default" | "auto") if provider_id == crate::providers::OPENAI_CODEX_PROVIDER => {
            FastOutcome::Unconfirmed
        }
        Some(returned) if returned == requested => FastOutcome::Confirmed,
        Some(returned) => FastOutcome::Different(returned.to_string()),
        None => FastOutcome::Unconfirmed,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FastObservation {
    pub(crate) requested_service_tier: String,
    pub(crate) outcome: FastOutcome,
    pub(crate) request_sequence: u64,
    pub(crate) run_order: Option<u64>,
}

pub(crate) fn fast_requested_service_tier_matches_request(
    requested_service_tier: &str,
    request: &FastRequestState,
) -> bool {
    request
        .service_tier()
        .is_some_and(|configured_service_tier| {
            !configured_service_tier.trim().is_empty()
                && requested_service_tier == configured_service_tier
        })
}

pub(crate) fn fast_observation_matches_request(
    observation: &FastObservation,
    request: &FastRequestState,
) -> bool {
    fast_requested_service_tier_matches_request(&observation.requested_service_tier, request)
}

pub(crate) fn display_service_tier(value: &str) -> String {
    let value = value.trim();
    if value.is_empty()
        || value.len() > MAX_SERVICE_TIER_BYTES
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
    {
        return "<invalid>".to_string();
    }
    let lower = value.to_ascii_lowercase();
    if lower.starts_with("sk-")
        || lower.starts_with("eyj")
        || ["token", "secret", "bearer", "api_key", "authorization"]
            .iter()
            .any(|marker| lower.contains(marker))
    {
        return "<redacted>".to_string();
    }
    value.to_string()
}

/// Return the stable key used for session-local Fast observations.
pub(crate) fn canonical_fast_observation_key(provider_id: &str, model: &str) -> (String, String) {
    let provider_id = provider_id.trim();
    let model = model.trim();
    (
        if provider_id.is_empty() {
            "provider".to_string()
        } else {
            provider_id.to_string()
        },
        if model.is_empty() {
            "model".to_string()
        } else {
            model.to_string()
        },
    )
}

pub(crate) type FastWarningKey = (String, String, String, FastOutcome);

pub(crate) fn canonical_fast_warning_key(
    provider_id: &str,
    model: &str,
    observation: &FastObservation,
) -> FastWarningKey {
    let (provider_id, model) = canonical_fast_observation_key(provider_id, model);
    let outcome = match &observation.outcome {
        FastOutcome::Different(service_tier) => {
            FastOutcome::Different(display_service_tier(service_tier))
        }
        outcome => outcome.clone(),
    };
    (
        provider_id,
        model,
        display_service_tier(&observation.requested_service_tier),
        outcome,
    )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FastObservationOrder {
    pub(crate) run_order: Option<u64>,
    pub(crate) accept_sequence: u64,
}

/// Compare a candidate observation with the observation already stored for a key.
///
/// Consumers assign `accept_sequence` when they receive an observation. A known
/// run order always outranks an unknown one, and a known run order is compared
/// before the consumer-owned arrival sequence. This prevents a late observation
/// from an older run from replacing a newer run while preserving arrival order
/// for observations from the same run.
pub(crate) fn compare_fast_observation_order(
    current: Option<FastObservationOrder>,
    candidate: FastObservationOrder,
) -> Ordering {
    let Some(current) = current else {
        return Ordering::Greater;
    };
    (candidate.run_order, candidate.accept_sequence)
        .cmp(&(current.run_order, current.accept_sequence))
}

use crate::config::Settings;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FastWorkload {
    Primary,
    Subagent,
    Compaction,
    SessionTitle,
}

impl FastWorkload {
    pub(crate) const fn allows_fast(self) -> bool {
        !matches!(self, Self::SessionTitle)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FastCapability {
    Unsupported,
    ServiceTier(String),
}

impl FastCapability {
    pub(crate) fn service_tier(service_tier: impl Into<String>) -> Self {
        Self::ServiceTier(service_tier.into())
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum FastRequestState {
    #[default]
    Standard,
    Fast {
        service_tier: String,
    },
}

impl FastRequestState {
    pub(crate) fn service_tier(&self) -> Option<&str> {
        match self {
            Self::Standard => None,
            Self::Fast { service_tier } => Some(service_tier),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) enum FastProjection {
    #[default]
    Off,
    Unavailable,
    WillRequest {
        service_tier: String,
    },
    Confirmed {
        service_tier: String,
    },
    Different {
        requested_service_tier: String,
        returned_service_tier: String,
    },
    Unconfirmed {
        service_tier: String,
    },
}

impl FastProjection {
    pub(crate) fn status_message(&self, provider: &str, model: &str, mode: &str) -> String {
        match self {
            Self::Off => format!("{mode} mode off. Magi-code will not request {mode} processing."),
            Self::Unavailable => {
                format!(
                    "{mode} remains on, but {provider}/{model} has no configured {mode} support."
                )
            }
            Self::WillRequest { .. } => format!(
                "{mode} mode on. {provider}/{model} will request {mode} processing.\nEligible requests may have higher provider pricing."
            ),
            Self::Confirmed { service_tier } => format!(
                "{mode} was confirmed for {provider}/{model} (tier \"{}\").",
                display_service_tier(service_tier)
            ),
            Self::Different {
                returned_service_tier,
                ..
            } => format!(
                "{mode} requested, but {provider}/{model} reported tier \"{}\".",
                display_service_tier(returned_service_tier)
            ),
            Self::Unconfirmed { .. } if provider == crate::providers::OPENAI_CODEX_PROVIDER => {
                format!(
                    "{mode} mode on. {provider}/{model} requested {mode} routing. Codex response tiers do not reliably confirm {mode} processing."
                )
            }
            Self::Unconfirmed { .. } => format!(
                "{mode} was requested, but {provider}/{model} did not report its processing tier."
            ),
        }
    }
}

pub(crate) fn resolve_fast_projection(
    enabled: bool,
    request: &FastRequestState,
    observation: Option<&FastObservation>,
) -> FastProjection {
    if !enabled {
        return FastProjection::Off;
    }
    let Some(configured_service_tier) = request
        .service_tier()
        .filter(|service_tier| !service_tier.trim().is_empty())
    else {
        return FastProjection::Unavailable;
    };
    let observation =
        observation.filter(|observation| fast_observation_matches_request(observation, request));
    let requested_service_tier = configured_service_tier.to_string();
    match observation.map(|observation| &observation.outcome) {
        Some(FastOutcome::Confirmed) => FastProjection::Confirmed {
            service_tier: requested_service_tier,
        },
        Some(FastOutcome::Different(returned_service_tier)) => FastProjection::Different {
            requested_service_tier,
            returned_service_tier: display_service_tier(returned_service_tier),
        },
        Some(FastOutcome::Unconfirmed) => FastProjection::Unconfirmed {
            service_tier: requested_service_tier,
        },
        Some(FastOutcome::NotRequested) | None => FastProjection::WillRequest {
            service_tier: requested_service_tier,
        },
    }
}

pub(crate) fn resolve_fast_capability(
    settings: &Settings,
    provider_id: &str,
    model: &str,
    paths: &crate::config::McPaths,
    custom: Option<&crate::config::CustomProviderConfig>,
    workload: FastWorkload,
) -> FastRequestState {
    let capability = if provider_id == crate::providers::OPENAI_CODEX_PROVIDER {
        let tier = if settings.fast.ultrafast {
            crate::model_catalog::cached_codex_ultrafast_service_tier(paths, model)
        } else {
            crate::model_catalog::cached_codex_fast_service_tier(paths, model)
        };
        tier.map(FastCapability::service_tier)
            .unwrap_or(FastCapability::Unsupported)
    } else if let Some(custom) = custom.filter(|_| !settings.fast.ultrafast) {
        custom
            .fast_mode
            .as_ref()
            .and_then(|fast| {
                let exact = fast.models.iter().any(|candidate| candidate == model);
                let wildcard = fast.models.len() == 1 && fast.models[0] == "*";
                (exact || wildcard).then(|| FastCapability::service_tier(fast.service_tier.clone()))
            })
            .unwrap_or(FastCapability::Unsupported)
    } else {
        FastCapability::Unsupported
    };
    resolve_fast_request(settings, workload, capability)
}
pub(crate) fn resolve_fast_request(
    settings: &Settings,
    workload: FastWorkload,
    capability: FastCapability,
) -> FastRequestState {
    if !settings.fast.enabled || !workload.allows_fast() {
        return FastRequestState::Standard;
    }
    match capability {
        FastCapability::Unsupported => FastRequestState::Standard,
        FastCapability::ServiceTier(service_tier) if service_tier.trim().is_empty() => {
            FastRequestState::Standard
        }
        FastCapability::ServiceTier(service_tier) => FastRequestState::Fast { service_tier },
    }
}

pub(crate) fn fast_status_message(
    fast: &crate::config::FastSettings,
    provider: &str,
    model: &str,
    capability: &FastRequestState,
    observation: Option<&FastObservation>,
) -> String {
    resolve_fast_projection(fast.enabled, capability, observation).status_message(
        provider,
        model,
        fast.mode_name(),
    )
}

pub(crate) fn speed_command_status(
    fast: &crate::config::FastSettings,
    ultrafast: bool,
    provider: &str,
    model: &str,
    capability: &FastRequestState,
    observation: Option<&FastObservation>,
) -> String {
    let command_mode = if ultrafast { "Ultrafast" } else { "Fast" };
    if !fast.enabled {
        return FastProjection::Off.status_message(provider, model, command_mode);
    }
    let status = fast_status_message(fast, provider, model, capability, observation);
    if fast.ultrafast == ultrafast {
        status
    } else {
        format!("{command_mode} mode off. {status}")
    }
}

pub(crate) fn fast_observation_warning(
    provider: &str,
    model: &str,
    observation: &FastObservation,
) -> Option<String> {
    if provider == crate::providers::OPENAI_CODEX_PROVIDER
        && observation.outcome == FastOutcome::Unconfirmed
    {
        return None;
    }
    if !matches!(
        observation.outcome,
        FastOutcome::Different(_) | FastOutcome::Unconfirmed
    ) {
        return None;
    }
    let capability = FastRequestState::Fast {
        service_tier: observation.requested_service_tier.clone(),
    };
    Some(fast_status_message(
        &crate::config::FastSettings {
            enabled: true,
            ultrafast: observation.requested_service_tier == "ultrafast",
        },
        provider,
        model,
        &capability,
        Some(observation),
    ))
}