alix 0.8.0

A learning tool built for understanding, not just remembering.
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
mod claude;
mod codex;
mod copilot;
mod gemini;
pub mod health;

pub use claude::ClaudeBackend;
pub use codex::CodexBackend;
pub use copilot::CopilotBackend;
pub use gemini::GeminiBackend;

use crate::config::{AskConfig, BackendKind};

pub enum PromptDelivery {
    Stdin,
    Arg,
    ExecArg,
}

pub enum Access {
    None,
    ReadOnly {
        files: bool,
        fetch: bool,
        search: bool,
    },
}

impl Access {
    pub fn from_allowed_tools(tools: &[String]) -> Self {
        let has = |name: &str| tools.iter().any(|t| t == name);
        let files = has("Read") || has("Glob") || has("Grep");
        let fetch = has("WebFetch");
        let search = has("WebSearch");
        if !files && !fetch && !search {
            Access::None
        } else {
            Access::ReadOnly {
                files,
                fetch,
                search,
            }
        }
    }
}

pub struct RunOpts<'a> {
    pub model: Option<&'a str>,
    pub effort: Option<&'a str>,
    pub permission_mode: Option<&'a str>,
    pub access: Access,
    pub session_args: &'a [String],
    pub progress: bool,
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct ProgressUpdate {
    pub activity: bool,
    pub message: Option<String>,
    /// The model the backend reports it actually loaded, when it says so.
    /// Discovered, never assumed: alix does not choose it and cannot name it
    /// from configuration alone.
    pub model: Option<String>,
}

pub trait Backend: Send + Sync {
    fn command(&self) -> &str;

    fn build_argv(&self, opts: &RunOpts) -> Vec<String>;

    fn prompt_delivery(&self) -> PromptDelivery;

    fn extract(&self, stdout: &str) -> anyhow::Result<String>;

    fn extract_progress(&self, stdout: &str) -> anyhow::Result<String> {
        self.extract(stdout)
    }

    fn structured_progress(&self) -> bool {
        false
    }

    fn progress_update(&self, line: &str) -> ProgressUpdate {
        ProgressUpdate {
            activity: !line.trim().is_empty(),
            message: None,
            model: None,
        }
    }

    fn can_fetch_web(&self) -> bool {
        true
    }

    fn can_read_source(&self) -> bool {
        true
    }

    fn supports_session(&self) -> bool {
        false
    }

    fn name(&self) -> &'static str;

    fn required_help_flags(&self) -> &'static [&'static str];

    fn default_trace_model(&self) -> Option<&'static str> {
        None
    }

    /// What the tutor pins when `[ask] model` is unset. Without a pin alix
    /// cannot name what answered, because the backend CLI chooses and never
    /// reports back.
    fn default_ask_model(&self) -> Option<&'static str> {
        None
    }

    fn default_ask_effort(&self) -> Option<&'static str> {
        None
    }
}

pub fn backend_for(cfg: &AskConfig) -> anyhow::Result<Box<dyn Backend>> {
    match cfg.backend {
        BackendKind::Claude => Ok(Box::new(ClaudeBackend)),
        BackendKind::Gemini => Ok(Box::new(GeminiBackend)),
        BackendKind::Codex => Ok(Box::new(CodexBackend)),
        BackendKind::Copilot => Ok(Box::new(CopilotBackend)),
    }
}

pub fn supports_structured_progress(cfg: &AskConfig) -> bool {
    backend_for(cfg).is_ok_and(|backend| backend.structured_progress())
}

/// The single resolution both the invocation and the readout use, so what the
/// tutor panel names is always what was actually passed.
pub fn resolved_ask_model(cfg: &AskConfig) -> Option<String> {
    cfg.model.clone().or_else(|| {
        backend_for(cfg)
            .ok()
            .and_then(|backend| backend.default_ask_model())
            .map(str::to_string)
    })
}

pub fn resolved_ask_effort(cfg: &AskConfig) -> Option<String> {
    cfg.effort.clone().or_else(|| {
        backend_for(cfg)
            .ok()
            .and_then(|backend| backend.default_ask_effort())
            .map(str::to_string)
    })
}

pub fn ensure_source_reachable(cfg: &AskConfig, is_url: bool) -> anyhow::Result<()> {
    let backend = backend_for(cfg)?;
    ensure_source_capability(
        backend.name(),
        is_url,
        backend.can_fetch_web(),
        backend.can_read_source(),
    )
}

fn ensure_source_capability(
    name: &str,
    is_url: bool,
    can_fetch_web: bool,
    can_read_source: bool,
) -> anyhow::Result<()> {
    if is_url && !can_fetch_web {
        anyhow::bail!(
            "the {} backend can't fetch a url under read-only; point source: at a local file, \
             or use a backend that can fetch",
            name
        );
    }
    if !is_url && !can_read_source {
        anyhow::bail!(
            "the {} backend can't read a local source; point source: at a url, or use a backend \
             that can read files",
            name
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AskConfig;

    fn tools(names: &[&str]) -> Vec<String> {
        names.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn every_backend_that_can_isolate_operator_instructions_does() {
        let opts = || RunOpts {
            model: None,
            effort: None,
            permission_mode: None,
            access: Access::None,
            session_args: &[],
            progress: false,
        };
        for (backend, expected) in [
            (
                Box::new(ClaudeBackend) as Box<dyn Backend>,
                Some("--safe-mode"),
            ),
            (Box::new(CodexBackend), Some("project_doc_max_bytes=0")),
            (Box::new(CopilotBackend), Some("--no-custom-instructions")),
            // Gemini 0.57.0 offers no such switch, so alix has none to pass.
            (Box::new(GeminiBackend), None),
        ] {
            let argv = backend.build_argv(&opts());
            let name = backend.name();
            match expected {
                Some(flag) => assert!(
                    argv.iter().any(|a| a == flag),
                    "{name} must pass {flag}, got {argv:?}"
                ),
                None => assert!(
                    !argv
                        .iter()
                        .any(|a| a.contains("instruction") || a.contains("safe-mode")),
                    "{name} has no isolation switch, so it must pass none, got {argv:?}"
                ),
            }
        }
    }

    #[test]
    fn backend_for_wires_all_four_backends() {
        let mut cfg = AskConfig::default();
        assert!(backend_for(&cfg).is_ok(), "claude should be wired");

        cfg.backend = BackendKind::Gemini;
        assert!(backend_for(&cfg).is_ok(), "gemini should be wired");

        cfg.backend = BackendKind::Codex;
        assert!(backend_for(&cfg).is_ok(), "codex should be wired");

        cfg.backend = BackendKind::Copilot;
        assert!(backend_for(&cfg).is_ok(), "copilot should be wired");
    }

    #[test]
    fn codex_backend_refuses_a_url_source_cleanly() {
        let cfg = AskConfig {
            backend: BackendKind::Codex,
            ..AskConfig::default()
        };
        let err = ensure_source_reachable(&cfg, true).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("codex"), "{msg}");
        assert!(msg.contains("can't fetch"), "{msg}");
        assert!(ensure_source_reachable(&cfg, false).is_ok());
    }

    #[test]
    fn fetch_capable_backends_pass_the_url_gate() {
        for backend in [
            BackendKind::Claude,
            BackendKind::Gemini,
            BackendKind::Copilot,
        ] {
            let cfg = AskConfig {
                backend,
                ..AskConfig::default()
            };
            assert!(
                ensure_source_reachable(&cfg, true).is_ok(),
                "{backend:?} should pass the URL gate"
            );
            assert!(ensure_source_reachable(&cfg, false).is_ok());
        }
    }

    #[test]
    fn source_capability_requires_the_matching_power_only() {
        assert!(ensure_source_capability("fake", true, true, false).is_ok());
        assert!(ensure_source_capability("fake", false, false, true).is_ok());

        let url = ensure_source_capability("fake", true, false, true).unwrap_err();
        assert!(format!("{url:#}").contains("can't fetch a url"));
        let local = ensure_source_capability("fake", false, true, false).unwrap_err();
        assert!(format!("{local:#}").contains("can't read a local source"));
    }

    #[test]
    fn only_claude_supports_sessions() {
        assert!(ClaudeBackend.supports_session());
        assert!(!GeminiBackend.supports_session());
        assert!(!CodexBackend.supports_session());
        assert!(!CopilotBackend.supports_session());
    }

    #[test]
    fn a_configured_model_and_effort_resolve_verbatim_for_every_backend() {
        for backend in [
            BackendKind::Claude,
            BackendKind::Gemini,
            BackendKind::Codex,
            BackendKind::Copilot,
        ] {
            let cfg = AskConfig {
                backend,
                model: Some("pinned-model".to_string()),
                effort: Some("pinned-effort".to_string()),
                ..AskConfig::default()
            };
            assert_eq!(
                Some("pinned-model".to_string()),
                resolved_ask_model(&cfg),
                "{backend:?}"
            );
            assert_eq!(
                Some("pinned-effort".to_string()),
                resolved_ask_effort(&cfg),
                "{backend:?}"
            );
        }
    }

    #[test]
    fn without_configured_values_no_backend_invents_a_model_or_effort() {
        for backend in [
            BackendKind::Claude,
            BackendKind::Gemini,
            BackendKind::Codex,
            BackendKind::Copilot,
        ] {
            let cfg = AskConfig {
                backend,
                ..AskConfig::default()
            };
            assert_eq!(None, resolved_ask_model(&cfg), "{backend:?}");
            assert_eq!(None, resolved_ask_effort(&cfg), "{backend:?}");
        }
    }

    #[test]
    fn unstructured_backends_use_the_plain_progress_contract() {
        let backend = GeminiBackend;
        assert!(!backend.structured_progress());
        assert_eq!(
            "plain answer",
            backend.extract_progress("  plain answer\n").unwrap()
        );
        assert_eq!(
            ProgressUpdate {
                activity: true,
                message: None,
                model: None,
            },
            backend.progress_update("some output")
        );
        assert_eq!(ProgressUpdate::default(), backend.progress_update(" \n"));
    }

    #[test]
    fn structured_progress_capability_matches_the_backend_contract() {
        for (backend, expected) in [
            (BackendKind::Claude, true),
            (BackendKind::Codex, true),
            (BackendKind::Gemini, false),
            (BackendKind::Copilot, false),
        ] {
            let cfg = AskConfig {
                backend,
                ..AskConfig::default()
            };
            assert_eq!(expected, supports_structured_progress(&cfg), "{backend:?}");
        }
    }

    #[test]
    fn access_from_askconfig_maps_tools_to_grant() {
        let a = Access::from_allowed_tools(&tools(&["Read", "Glob", "Grep", "WebFetch"]));
        assert!(matches!(
            a,
            Access::ReadOnly {
                files: true,
                fetch: true,
                search: false
            }
        ));

        let b = Access::from_allowed_tools(&tools(&["WebFetch", "WebSearch"]));
        assert!(matches!(
            b,
            Access::ReadOnly {
                files: false,
                fetch: true,
                search: true
            }
        ));

        for tool in ["Read", "Glob", "Grep"] {
            let access = Access::from_allowed_tools(&tools(&[tool]));
            assert!(matches!(
                access,
                Access::ReadOnly {
                    files: true,
                    fetch: false,
                    search: false
                }
            ));
        }

        let d = Access::from_allowed_tools(&[]);
        assert!(matches!(d, Access::None));
    }
}