Skip to main content

ai6_agent_codex/
tools.rs

1//! The tool check of a restricted thread (answer-only, assistant or `desk`).
2//!
3//! A Codex release can offer the model tools that no setting this handler passes switches off,
4//! and a new release adds more. So before a restricted app server starts, the handler runs the
5//! same Codex with the same settings, environment and working directory: `codex features list`,
6//! to switch off every enabled feature not on [`KEPT_FEATURES`], `codex mcp list --json`, to
7//! switch off every MCP server of the user's configuration that is not the thread's (a `-c
8//! mcp_servers` table adds to the user's servers instead of replacing them), then `codex debug
9//! prompt-input`, which renders what the model would be given without asking it anything. The
10//! thread starts only when the tools offered are exactly those of its MCP servers (none for an
11//! answer-only thread). With `AI6_CODEX_TOOL_CHECK=warn` in the Agent's environment it starts
12//! regardless, and what the check found is reported as a weakening.
13
14use std::collections::{BTreeMap, BTreeSet, HashMap};
15use std::sync::{Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18use ai6::directorates::q::terminal::{
19    AgentTerminal, ExitInfo, READ_TIMED_OUT, STREAM_COLS, Spec, strip_controls,
20};
21use ai6::guatiao::library::{Object, ProviderError};
22use ai6::guatiao::{FromValue, Status, ToValue};
23use ai6::wire::OpaqueJson;
24use serde::Deserialize;
25
26use crate::appserver::{JsonObject, Lenient};
27use crate::sandbox::SCRIPT_FEATURES;
28use crate::{internal, refuse};
29
30/// The environment variable that chooses what a failed tool check does: `strict` (the
31/// default) refuses to start, `warn` starts and reports a weakening.
32pub const TOOL_CHECK_ENV: &str = "AI6_CODEX_TOOL_CHECK";
33
34/// Features a restricted thread keeps: how Codex stores its login and reaches its service,
35/// none of which offers the model a tool, and `incremental_tools`. Every other enabled feature
36/// is switched off.
37pub const KEPT_FEATURES: [&str; 5] = [
38    "secret_auth_storage",
39    "enable_request_compression",
40    "system_proxy_fallback",
41    "unbounded_connection_retries",
42    // Without it `codex debug prompt-input` renders no tool, while the app server still sends
43    // the tools of the model's catalog entry (`functions.exec` and `wait` in Codex 0.164.0):
44    // the check would see less than the thread is given.
45    "incremental_tools",
46];
47
48/// The feature that runs `exec`'s JavaScript: with it off, `exec` is still offered and fails with
49/// `code-mode host is disabled`, and an MCP server's tools, which only `exec` reaches, with it
50/// (Codex 0.164.0).
51const CODE_MODE_HOST: &str = "code_mode_host";
52
53/// What a failed check does.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub(crate) enum ToolCheck {
56    Strict,
57    Warn,
58}
59
60impl ToolCheck {
61    /// The choice in `environment`, `strict` when unset; any other value is refused.
62    pub(crate) fn from_environment(
63        environment: &BTreeMap<String, String>,
64    ) -> Result<Self, ProviderError> {
65        match environment.get(TOOL_CHECK_ENV).map(|value| value.trim()) {
66            None | Some("" | "strict") => Ok(Self::Strict),
67            Some("warn") => Ok(Self::Warn),
68            Some(other) => Err(refuse(
69                Status::GUATIAO_ERR_BAD_VALUE,
70                format!("{TOOL_CHECK_ENV} is {other:?}; it takes strict or warn"),
71            )),
72        }
73    }
74}
75
76/// What the check decided for a thread that may start.
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub(crate) struct Checked {
79    /// `-c` overrides that switch the features off, to add to the app server's.
80    pub(crate) overrides: Vec<String>,
81    /// What a `warn` check found, to report as a weakening.
82    pub(crate) weakening: Option<String>,
83}
84
85/// What `codex features list` printed: the enabled features, and every non-blank line that
86/// does not read as `name stage state` (the stage possibly two words).
87#[derive(Clone, Debug, Default, PartialEq, Eq)]
88pub(crate) struct FeatureList {
89    pub(crate) enabled: Vec<String>,
90    pub(crate) unread: Vec<String>,
91}
92
93/// Reads `codex features list` output; `None` when no line reads as a feature.
94pub(crate) fn feature_list(output: &[u8], csi: ai6::Limit) -> Option<FeatureList> {
95    let text = String::from_utf8_lossy(&strip_controls(output, csi)).replace('\r', "");
96    let mut read = 0;
97    let mut list = FeatureList::default();
98    for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) {
99        let words = line.split_whitespace().collect::<Vec<_>>();
100        let named = words.first().is_some_and(|name| {
101            name.bytes().all(|byte| {
102                byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_.".contains(&byte)
103            })
104        });
105        let state = words.last().copied();
106        if words.len() < 3 || !named || !matches!(state, Some("true" | "false")) {
107            list.unread.push(line.to_owned());
108            continue;
109        }
110        read += 1;
111        if state == Some("true") {
112            list.enabled.push(words[0].to_owned());
113        }
114    }
115    (read > 0).then_some(list)
116}
117
118/// The server names in `codex mcp list --json` output; `None` unless it is one JSON array of
119/// objects, each with a string `name`, with nothing after it. The output also holds each
120/// server's environment values, so nothing else of it is kept, and the command runs out of the
121/// viewers' sight ([`Probe::capture`]).
122pub(crate) fn mcp_server_names(output: &[u8], csi: ai6::Limit) -> Option<Vec<String>> {
123    // Pretty-printed JSON, as `offered_tools` reads it: every line break can go.
124    let mut text = strip_controls(output, csi);
125    text.retain(|byte| !matches!(byte, b'\r' | b'\n'));
126    let start = (0..text.len()).find(|&at| opens_server_list(&text[at..]))?;
127    let servers: Vec<JsonObject<McpServer>> = read_catalog(&text[start..])?;
128    Some(servers.into_iter().map(|server| server.0.name).collect())
129}
130
131#[derive(Deserialize)]
132struct McpServer {
133    name: String,
134}
135
136/// Whether `text` starts `[`, then `{` or `]`, with only whitespace between.
137fn opens_server_list(text: &[u8]) -> bool {
138    let mut rest = text.iter().skip_while(|byte| byte.is_ascii_whitespace());
139    rest.next() == Some(&b'[')
140        && matches!(
141            rest.find(|byte| !byte.is_ascii_whitespace()),
142            Some(b'{' | b']')
143        )
144}
145
146/// Codex splits a `-c` key at every dot and reads no quoted part, so only a name that is a
147/// bare TOML key can be addressed as `mcp_servers.<name>`.
148fn addressable(name: &str) -> bool {
149    !name.is_empty()
150        && name
151            .bytes()
152            .all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte))
153}
154
155/// `-c` overrides that switch off every listed MCP server that is not one of the thread's,
156/// and the listed names that cannot be addressed, which stay on.
157pub(crate) fn switch_off_servers(
158    listed: &[String],
159    servers: &[String],
160) -> (Vec<String>, Vec<String>) {
161    let mut overrides = Vec::new();
162    let mut unaddressable = Vec::new();
163    for name in listed.iter().filter(|name| !servers.contains(name)) {
164        if addressable(name) {
165            overrides.extend(["-c".to_owned(), format!("mcp_servers.{name}.enabled=false")]);
166        } else {
167            unaddressable.push(format!("{name:?}"));
168        }
169    }
170    (overrides, unaddressable)
171}
172
173/// The tools `codex debug prompt-input` output offers the model, named `namespace.tool` inside
174/// a namespace; `None` unless the output is one JSON array of input items, holding at least
175/// one `message` and otherwise only `additional_tools`, with nothing after it, so an unknown
176/// shape is never read as "no tools".
177pub(crate) fn offered_tools(output: &[u8], csi: ai6::Limit) -> Option<Vec<String>> {
178    let items = prompt_items(output, csi)?;
179    let mut tools = Vec::new();
180    let mut messages = 0;
181    for item in items {
182        let item = &item.read()?.0;
183        match item.kind.copied()? {
184            PromptKind::Message => messages += 1,
185            PromptKind::AdditionalTools => collect(item.tools.read()?, "", &mut tools)?,
186        }
187    }
188    (messages > 0).then_some(tools)
189}
190
191/// The one JSON array of input items in `codex debug prompt-input` output.
192fn prompt_items(output: &[u8], csi: ai6::Limit) -> Option<Vec<Lenient<JsonObject<PromptItem>>>> {
193    // The output is pretty-printed JSON, and a terminal may break a long line: JSON text holds
194    // no raw line break, so every one can go.
195    let mut text = strip_controls(output, csi);
196    text.retain(|byte| !matches!(byte, b'\r' | b'\n'));
197    let start = (0..text.len()).find(|&at| opens_item_list(&text[at..]))?;
198    // One value, then only whitespace: `from_slice` refuses anything after it.
199    read_catalog(&text[start..])
200}
201
202fn read_catalog<T: serde::de::DeserializeOwned>(array: &[u8]) -> Option<T> {
203    // Preserve Codex's JSON object member semantics, including duplicate keys.
204    serde_json::from_slice::<OpaqueJson>(array)
205        .ok()?
206        .decode()
207        .ok()
208}
209
210#[derive(Clone, Copy, Deserialize)]
211#[serde(rename_all = "snake_case")]
212enum PromptKind {
213    Message,
214    AdditionalTools,
215}
216
217#[derive(Default, Deserialize)]
218#[serde(default)]
219struct PromptItem {
220    #[serde(rename = "type")]
221    kind: Lenient<PromptKind>,
222    tools: Lenient<Vec<ReadTool>>,
223}
224
225type ReadTool = Lenient<JsonObject<PromptTool>>;
226
227#[derive(Default, Deserialize)]
228#[serde(default)]
229struct PromptTool {
230    #[serde(rename = "type")]
231    kind: Lenient<String>,
232    name: Lenient<String>,
233    description: Lenient<String>,
234    tools: Lenient<Vec<ReadTool>>,
235}
236
237/// The tools `functions.exec` nests, as its description in `codex debug prompt-input` output
238/// declares them, one `declare const tools: { NAME(` per tool under an `exec tool
239/// declaration:` heading: `Some` empty when `exec` is not offered, `None` when its declarations
240/// cannot be read. Codex leaves deferred tools (an MCP server's, in 0.164.0) out of the
241/// description, so those are not seen here.
242pub(crate) fn exec_nested(output: &[u8], csi: ai6::Limit) -> Option<Vec<String>> {
243    let items = prompt_items(output, csi)?;
244    let exec = items
245        .iter()
246        .filter_map(|item| item.read().map(|item| &item.0))
247        .filter(|item| matches!(item.kind.copied(), Some(PromptKind::AdditionalTools)))
248        .filter_map(|item| item.tools.read())
249        .flatten()
250        .filter_map(|tool| tool.read().map(|tool| &tool.0))
251        .filter(|tool| tool.name.text() == Some("functions"))
252        .filter_map(|namespace| namespace.tools.read())
253        .flatten()
254        .filter_map(|tool| tool.read().map(|tool| &tool.0))
255        .find(|tool| tool.name.text() == Some("exec"));
256    let Some(exec) = exec else {
257        return Some(Vec::new());
258    };
259    let description = exec.description.text()?;
260    const DECLARATION: &str = "declare const tools: { ";
261    let names: Vec<String> = description
262        .match_indices(DECLARATION)
263        .map(|(at, _)| {
264            description[at + DECLARATION.len()..]
265                .chars()
266                .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '$'))
267                .collect()
268        })
269        .collect();
270    let headings = description.matches("exec tool declaration:").count();
271    (!names.is_empty() && names.len() == headings && names.iter().all(|name| !name.is_empty()))
272        .then_some(names)
273}
274
275/// Whether `text` starts `[`, `{`, `"type"`, with only whitespace between.
276fn opens_item_list(text: &[u8]) -> bool {
277    let rest = |text: &[u8], token: &[u8]| -> Option<usize> {
278        let skipped = text
279            .iter()
280            .take_while(|byte| byte.is_ascii_whitespace())
281            .count();
282        text[skipped..]
283            .starts_with(token)
284            .then_some(skipped + token.len())
285    };
286    let Some(at) = rest(text, b"[") else {
287        return false;
288    };
289    let Some(more) = rest(&text[at..], b"{") else {
290        return false;
291    };
292    rest(&text[at + more..], b"\"type\"").is_some()
293}
294
295fn collect(list: &[ReadTool], prefix: &str, tools: &mut Vec<String>) -> Option<()> {
296    for tool in list {
297        let tool = &tool.read()?.0;
298        let name = tool.name.text()?;
299        if tool.kind.text() == Some("namespace") {
300            collect(tool.tools.read()?, &format!("{prefix}{name}."), tools)?;
301        } else {
302            tools.push(format!("{prefix}{name}"));
303        }
304    }
305    Some(())
306}
307
308/// The tools of Codex's code mode: `exec` runs JavaScript that calls the thread's other tools
309/// (its MCP servers' and the command tools) and `wait` waits on it. A scripts or `desk` thread is
310/// offered these alone.
311pub(crate) const CODE_MODE_TOOLS: [&str; 2] = ["functions.exec", "functions.wait"];
312
313/// The tools nested in `exec` that run a script's commands: `exec_command` starts one and
314/// `write_stdin` writes to one it started.
315const COMMAND_TOOLS: [&str; 2] = ["exec_command", "write_stdin"];
316/// The nested tools that list and read the resources of the configured MCP servers, which the
317/// tool check leaves only the thread's.
318const MCP_RESOURCE_TOOLS: [&str; 3] = [
319    "list_mcp_resources",
320    "list_mcp_resource_templates",
321    "read_mcp_resource",
322];
323/// Nested tools that read and reach nothing: the current time. Codex 0.164.0 offers it with
324/// every feature but the kept ones off, and no setting removes it.
325const INERT_TOOLS: [&str; 1] = ["clock__curr_time"];
326
327/// What a thread may use, for [`judge`].
328#[derive(Clone, Copy, Debug)]
329pub(crate) struct Allowed<'a> {
330    /// The MCP servers the thread may use.
331    pub(crate) servers: &'a [String],
332    /// Whether code mode is admitted: [`CODE_MODE_TOOLS`] are allowed, and a server's tools may
333    /// be reached only through `exec`.
334    pub(crate) code_mode: bool,
335    /// Whether it runs commands: `exec` may nest [`COMMAND_TOOLS`].
336    pub(crate) commands: bool,
337    /// Whether it may change files through Codex's patch tool (`apply_patch`, nested).
338    pub(crate) files: bool,
339}
340
341impl Allowed<'_> {
342    /// Whether `exec` may nest `tool`: the command tools with commands, `apply_patch` with files,
343    /// the resource tools and `mcp__<server>__<tool>` of the thread's servers, and the inert ones.
344    fn nests(&self, tool: &str) -> bool {
345        (self.commands && COMMAND_TOOLS.contains(&tool))
346            || INERT_TOOLS.contains(&tool)
347            || (self.files && tool == "apply_patch")
348            || (!self.servers.is_empty() && MCP_RESOURCE_TOOLS.contains(&tool))
349            || self.servers.iter().any(|server| {
350                // Codex names a nested tool as a JavaScript identifier.
351                let server: String = server
352                    .chars()
353                    .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
354                    .collect();
355                tool.strip_prefix(&format!("mcp__{server}__"))
356                    .is_some_and(|rest| !rest.is_empty())
357            })
358    }
359}
360
361/// Judges the offered tools against what a thread may use: each tool must belong to one of its
362/// MCP servers (`mcp__<server>.<tool>`) and each server must offer at least one. With
363/// `code_mode`, [`CODE_MODE_TOOLS`] are allowed too, a server need not offer a tool directly
364/// (code mode nests them in `exec`), and every tool `exec` declares (`nested`, from
365/// [`exec_nested`]) must be one it may nest ([`Allowed::nests`]). `Ok(None)` passes;
366/// `Ok(Some(found))` is a failure a `warn` check starts with; `Err` refuses.
367pub(crate) fn judge(
368    offered: Option<&[String]>,
369    nested: Option<&[String]>,
370    allowed: Allowed<'_>,
371    check: ToolCheck,
372) -> Result<Option<String>, String> {
373    let Allowed {
374        servers, code_mode, ..
375    } = allowed;
376    let found = match offered {
377        None => {
378            "the tools Codex offers could not be read from `codex debug prompt-input`".to_owned()
379        }
380        Some(offered) => {
381            let offers = |tool: &str| {
382                (code_mode && CODE_MODE_TOOLS.contains(&tool))
383                    || servers.iter().any(|server| {
384                        tool.strip_prefix(&format!("mcp__{server}."))
385                            .is_some_and(|rest| !rest.is_empty())
386                    })
387            };
388            let extra = offered
389                .iter()
390                .filter(|tool| !offers(tool))
391                .cloned()
392                .collect::<BTreeSet<_>>();
393            let missing = servers
394                .iter()
395                .filter(|_| !code_mode)
396                .filter(|server| {
397                    !offered
398                        .iter()
399                        .any(|tool| tool.starts_with(&format!("mcp__{server}.")))
400                })
401                .cloned()
402                .collect::<Vec<_>>();
403            let mut found = Vec::new();
404            if !extra.is_empty() {
405                found.push(format!(
406                    "Codex offers tools beyond the thread's MCP servers: {}",
407                    extra.into_iter().collect::<Vec<_>>().join(", ")
408                ));
409            }
410            if !missing.is_empty() {
411                found.push(format!(
412                    "Codex offers no tool of MCP server {} directly",
413                    missing.join(", ")
414                ));
415            }
416            if code_mode && offered.iter().any(|tool| tool == CODE_MODE_TOOLS[0]) {
417                match nested {
418                    None => found.push(
419                        "the tools nested in functions.exec could not be read from its \
420                         description"
421                            .to_owned(),
422                    ),
423                    Some(nested) => {
424                        let extra = nested
425                            .iter()
426                            .filter(|tool| !allowed.nests(tool))
427                            .cloned()
428                            .collect::<BTreeSet<_>>();
429                        if !extra.is_empty() {
430                            found.push(format!(
431                                "Codex nests tools in functions.exec beyond the thread's: {}",
432                                extra.into_iter().collect::<Vec<_>>().join(", ")
433                            ));
434                        }
435                    }
436                }
437            }
438            if found.is_empty() {
439                return Ok(None);
440            }
441            found.join("; ")
442        }
443    };
444    match check {
445        ToolCheck::Strict => Err(format!(
446            "this restricted Codex thread was not started: {found} \
447             ({TOOL_CHECK_ENV}=warn starts it anyway, as a weakening)"
448        )),
449        ToolCheck::Warn => Ok(Some(found)),
450    }
451}
452
453/// Refuses, naming what was found, when a `strict` check found anything.
454fn refuse_if_strict(found: &[String], check: ToolCheck) -> Result<(), ProviderError> {
455    if found.is_empty() || check == ToolCheck::Warn {
456        return Ok(());
457    }
458    Err(refuse(
459        Status::GUATIAO_ERR_UNSUPPORTED,
460        format!(
461            "this restricted Codex thread was not started: {} \
462             ({TOOL_CHECK_ENV}=warn starts it anyway, as a weakening)",
463            found.join("; ")
464        ),
465    ))
466}
467
468/// The environment variables that decide which Codex runs and which configuration it reads.
469pub(crate) const CONFIG_ENVIRONMENT: [&str; 7] = [
470    "CODEX_HOME",
471    "HOME",
472    "USERPROFILE",
473    "APPDATA",
474    "LOCALAPPDATA",
475    "XDG_CONFIG_HOME",
476    "PATH",
477];
478
479/// What a feature list depends on but the working directory, which only names the project
480/// marked untrusted and the paths of the scripts' sandbox profile.
481#[derive(Clone, Debug, PartialEq, Eq, Hash)]
482struct FeaturesKey {
483    executable: String,
484    version: String,
485    overrides: Vec<String>,
486    environment: Vec<(String, Option<String>)>,
487    check: ToolCheck,
488    code_mode: bool,
489    commands: bool,
490}
491
492/// The features and MCP servers last switched off for a key, as `-c` overrides, and what a
493/// `warn` check found reading them.
494type SwitchedOff = (Vec<String>, Option<String>);
495
496fn feature_lists() -> &'static Mutex<HashMap<FeaturesKey, (Instant, SwitchedOff)>> {
497    static LISTS: OnceLock<Mutex<HashMap<FeaturesKey, (Instant, SwitchedOff)>>> = OnceLock::new();
498    LISTS.get_or_init(Mutex::default)
499}
500
501/// One restricted thread's check, run through `terminal` with the app server's settings.
502pub(crate) struct Probe<'a> {
503    pub(crate) terminal: &'a Object<dyn AgentTerminal>,
504    pub(crate) executable: &'a str,
505    /// The app server's `-c` overrides, as `-c` and value pairs.
506    pub(crate) overrides: &'a [String],
507    pub(crate) cwd: &'a str,
508    pub(crate) environment: &'a BTreeMap<String, String>,
509    pub(crate) model: Option<&'a str>,
510    /// The MCP servers the thread may use.
511    pub(crate) servers: &'a [String],
512    /// Whether the thread may be offered [`CODE_MODE_TOOLS`]: it keeps [`CODE_MODE_HOST`].
513    pub(crate) code_mode: bool,
514    /// Whether it runs commands, in Codex's sandbox or with none: it also keeps
515    /// [`SCRIPT_FEATURES`](crate::sandbox::SCRIPT_FEATURES).
516    pub(crate) commands: bool,
517    /// Whether it may change files through Codex's patch tool.
518    pub(crate) files: bool,
519    /// The handler's configuration: terminal control bytes, the check's lifetime and timeout.
520    pub(crate) config: &'a crate::CodexConfig,
521}
522
523impl Probe<'_> {
524    /// Runs the check. The features and MCP servers to switch off are reused for the same
525    /// Codex, settings and configuration environment for `tool_check_lifetime_secs`; what Codex offers
526    /// is rendered on every start, so a change the key cannot see (a configuration file
527    /// edited) is caught there, except an MCP server added to the user's configuration, whose
528    /// tools `prompt-input` does not render: it is switched off once the lifetime has passed.
529    pub(crate) fn check(&self) -> Result<Checked, ProviderError> {
530        let lifetime = Duration::from_secs(self.config.tool_check_lifetime_secs);
531        let check = ToolCheck::from_environment(self.environment)?;
532        let version = String::from_utf8_lossy(&strip_controls(
533            &self.capture(&[self.executable.to_owned(), "--version".to_owned()])?,
534            self.csi(),
535        ))
536        .trim()
537        .to_owned();
538        let key = FeaturesKey {
539            executable: self.executable.to_owned(),
540            version,
541            overrides: self
542                .overrides
543                .iter()
544                .filter(|value| {
545                    !value.starts_with("projects=") && !value.starts_with("permissions.")
546                })
547                .cloned()
548                .collect(),
549            environment: CONFIG_ENVIRONMENT
550                .iter()
551                .map(|name| ((*name).to_owned(), self.environment.get(*name).cloned()))
552                .collect(),
553            check,
554            code_mode: self.code_mode,
555            commands: self.commands,
556        };
557        let cached = feature_lists().lock().ok().and_then(|lists| {
558            lists
559                .get(&key)
560                .filter(|(at, _)| at.elapsed() < lifetime)
561                .map(|(_, switched)| switched.clone())
562        });
563        let (overrides, read) = match cached {
564            Some(switched) => switched,
565            None => {
566                let switched = self.switch_off(check)?;
567                if let Ok(mut lists) = feature_lists().lock() {
568                    lists.retain(|_, (at, _)| at.elapsed() < lifetime);
569                    lists.insert(key, (Instant::now(), switched.clone()));
570                }
571                switched
572            }
573        };
574        let mut weakenings = read.into_iter().collect::<Vec<_>>();
575        let mut argv = self.command(&["debug", "prompt-input"], &overrides);
576        if let Some(model) = self.model {
577            let model = serde_json::to_string(model).map_err(internal)?;
578            argv.extend(["-c".to_owned(), format!("model={model}")]);
579        }
580        let output = self.capture(&argv)?;
581        let allowed = Allowed {
582            servers: self.servers,
583            code_mode: self.code_mode,
584            commands: self.commands,
585            files: self.files,
586        };
587        let offered = offered_tools(&output, self.csi());
588        let nested = exec_nested(&output, self.csi());
589        if let Some(found) = judge(offered.as_deref(), nested.as_deref(), allowed, check)
590            .map_err(|reason| refuse(Status::GUATIAO_ERR_UNSUPPORTED, reason))?
591        {
592            weakenings.push(found);
593        }
594        Ok(Checked {
595            overrides,
596            weakening: (!weakenings.is_empty()).then(|| weakenings.join("; ")),
597        })
598    }
599
600    /// The `-c` overrides that switch off every enabled feature not kept, from `codex features
601    /// list`, and every MCP server of the user's that is not the thread's, from `codex mcp list
602    /// --json` with those features off; and what a `warn` check found reading them.
603    fn switch_off(&self, check: ToolCheck) -> Result<SwitchedOff, ProviderError> {
604        let mut found = Vec::new();
605        let list = feature_list(
606            &self.capture(&self.command(&["features", "list"], &[]))?,
607            self.csi(),
608        );
609        match &list {
610            None => found.push(
611                "the features Codex enables could not be read from `codex features list`"
612                    .to_owned(),
613            ),
614            Some(list) => found.extend(list.unread.first().map(|line| {
615                format!(
616                    "`codex features list` printed {} line(s) that are not a feature, such as {line:?}",
617                    list.unread.len()
618                )
619            })),
620        }
621        refuse_if_strict(&found, check)?;
622        let mut overrides = list
623            .map(|list| list.enabled)
624            .unwrap_or_default()
625            .into_iter()
626            .filter(|name| !KEPT_FEATURES.contains(&name.as_str()))
627            .filter(|name| !(self.commands && SCRIPT_FEATURES.contains(&name.as_str())))
628            .filter(|name| !(self.code_mode && name == CODE_MODE_HOST))
629            .flat_map(|name| ["-c".to_owned(), format!("features.{name}=false")])
630            .collect::<Vec<_>>();
631        let listed = mcp_server_names(
632            &self.capture(&self.command(&["mcp", "list", "--json"], &overrides))?,
633            self.csi(),
634        );
635        match listed {
636            None => found.push(
637                "the MCP servers of Codex's configuration could not be read from \
638                 `codex mcp list --json`, so none of the user's is switched off"
639                    .to_owned(),
640            ),
641            Some(listed) => {
642                let (off, unaddressable) = switch_off_servers(&listed, self.servers);
643                overrides.extend(off);
644                if !unaddressable.is_empty() {
645                    found.push(format!(
646                        "MCP server {} of Codex's configuration cannot be switched off by \
647                         name and stays on",
648                        unaddressable.join(", ")
649                    ));
650                }
651            }
652        }
653        refuse_if_strict(&found, check)?;
654        Ok((overrides, (!found.is_empty()).then(|| found.join("; "))))
655    }
656
657    /// The longest terminal control sequence stripped from what a command prints.
658    fn csi(&self) -> ai6::Limit {
659        ai6::Limit::at(self.config.csi_bytes)
660    }
661    /// `codex <words>` with the app server's settings and `more`.
662    fn command(&self, words: &[&str], more: &[String]) -> Vec<String> {
663        let mut argv = vec![self.executable.to_owned()];
664        argv.extend(words.iter().map(|word| (*word).to_owned()));
665        argv.extend_from_slice(self.overrides);
666        argv.extend_from_slice(more);
667        argv
668    }
669
670    /// Everything `argv` writes until it exits.
671    fn capture(&self, argv: &[String]) -> Result<Vec<u8>, ProviderError> {
672        let spec = Spec {
673            argv: argv.to_vec(),
674            cwd: Some(self.cwd.to_owned()),
675            env: Some(self.environment.clone()),
676            rows: 24,
677            cols: STREAM_COLS,
678        };
679        // `codex mcp list --json` prints each server's environment values and `debug prompt-input`
680        // the thread's instructions, so none of this may reach the Run's viewers.
681        let run = self
682            .terminal
683            .spawn_private(&spec.to_value().map_err(internal)?)?;
684        let deadline = Instant::now() + Duration::from_millis(self.config.tool_command_timeout_ms);
685        let mut output = Vec::new();
686        let mut buffer = vec![0_u8; 65536];
687        let mut exited = false;
688        loop {
689            if Instant::now() >= deadline {
690                let _ = run.kill();
691                return Err(refuse(
692                    Status::GUATIAO_ERR_INTERNAL,
693                    format!("`{}` did not finish", argv[1..].join(" ")),
694                ));
695            }
696            let count = run.read(&mut buffer, 100)?;
697            if count > 0 {
698                output.extend_from_slice(&buffer[..count as usize]);
699                continue;
700            }
701            // A pseudo-console can stay open after its program exits: once the program has
702            // gone, the first quiet read ends the output.
703            if count == 0 || (count == READ_TIMED_OUT && exited) {
704                break;
705            }
706            exited = run
707                .exit_status(0)
708                .ok()
709                .and_then(|value| ExitInfo::from_value(&value).ok())
710                .is_some_and(|exit| !exit.running);
711        }
712        let _ = run.kill();
713        Ok(output)
714    }
715}
716
717#[cfg(test)]
718mod tests {
719    use super::*;
720    const CSI: ai6::Limit = ai6::Limit::at(64);
721
722    /// `codex debug prompt-input`, `codex features list` and `codex mcp list --json` output
723    /// of Codex 0.164.0 on Windows, model descriptions shortened, message text and server
724    /// commands and environment values replaced (they hold the machine's paths): with the
725    /// settings this handler passed before the tool check, with those it passes now
726    /// (answer-only, and an assistant with one MCP server, `moneypenny`, model `gpt-6.1-sol`,
727    /// a user configuration holding one stdio server, `node_repl`), and with code mode kept
728    /// and that server's namespace exposed directly.
729    const BEFORE: &str = include_str!("../tests/fixtures/codex-0.164.0/prompt-input-main.json");
730    const ANSWER_ONLY: &str =
731        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-answer-only.json");
732    const ASSISTANT: &str =
733        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-assistant.json");
734    const CODE_MODE: &str =
735        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-code-mode.json");
736    const FEATURES: &str = include_str!("../tests/fixtures/codex-0.164.0/features-list.txt");
737    const MCP_LIST: &str = include_str!("../tests/fixtures/codex-0.164.0/mcp-list.json");
738    const MCP_LIST_ASSISTANT: &str =
739        include_str!("../tests/fixtures/codex-0.164.0/mcp-list-assistant.json");
740
741    fn moneypenny() -> Vec<String> {
742        vec!["moneypenny".to_owned()]
743    }
744
745    #[test]
746    fn the_tool_catalog_and_server_overrides_are_fixed() {
747        let mut text = String::new();
748        for input in [BEFORE, ANSWER_ONLY, ASSISTANT, CODE_MODE, SCRIPTS, DESK] {
749            text.push_str(&format!(
750                "{:?}\n{:?}\n",
751                offered_tools(input.as_bytes(), CSI),
752                exec_nested(input.as_bytes(), CSI)
753            ));
754        }
755        for input in [MCP_LIST, MCP_LIST_ASSISTANT] {
756            let servers = mcp_server_names(input.as_bytes(), CSI).unwrap();
757            text.push_str(&format!(
758                "{servers:?}\n{:?}\n",
759                switch_off_servers(&servers, &moneypenny())
760            ));
761        }
762        crate::fixed_tests::golden("tool-catalog.txt", &text);
763    }
764
765    /// A thread on `servers`, with scripts and files or without either.
766    fn allow(servers: &[String], scripts: bool) -> Allowed<'_> {
767        Allowed {
768            servers,
769            code_mode: scripts,
770            commands: scripts,
771            files: scripts,
772        }
773    }
774
775    /// A `desk` thread on `servers`: code mode and file changes, no command.
776    fn desk(servers: &[String]) -> Allowed<'_> {
777        Allowed {
778            servers,
779            code_mode: true,
780            commands: false,
781            files: true,
782        }
783    }
784
785    #[test]
786    fn the_settings_before_the_check_left_code_mode_agents_and_computer_use_on() {
787        let offered = offered_tools(BEFORE.as_bytes(), CSI).unwrap();
788        for tool in [
789            "functions.exec",
790            "functions.request_user_input",
791            "clock.sleep",
792            "collaboration.spawn_agent",
793            "mcp__cua_repl.js",
794        ] {
795            assert!(offered.iter().any(|t| t == tool), "{tool}: {offered:?}");
796        }
797        let refused =
798            judge(Some(&offered), None, allow(&[], false), ToolCheck::Strict).unwrap_err();
799        assert!(refused.contains("functions.exec") && refused.contains("mcp__cua_repl.js"));
800    }
801
802    #[test]
803    fn an_answer_only_thread_offered_the_catalogs_exec_and_wait_is_refused() {
804        let offered = offered_tools(ANSWER_ONLY.as_bytes(), CSI).unwrap();
805        assert_eq!(
806            offered,
807            ["functions.exec", "functions.wait"],
808            "request_user_input is switched off; exec and wait come with the model"
809        );
810        let refused =
811            judge(Some(&offered), None, allow(&[], false), ToolCheck::Strict).unwrap_err();
812        assert!(
813            refused.contains("functions.exec, functions.wait"),
814            "{refused}"
815        );
816        let weakening = judge(Some(&offered), None, allow(&[], false), ToolCheck::Warn)
817            .unwrap()
818            .unwrap();
819        assert!(weakening.contains("functions.exec"), "{weakening}");
820        assert_eq!(
821            judge(Some(&[]), None, allow(&[], false), ToolCheck::Strict),
822            Ok(None),
823            "an answer-only thread passes with no tool at all"
824        );
825    }
826
827    #[test]
828    fn an_assistant_whose_server_codex_does_not_offer_is_refused() {
829        let offered = offered_tools(ASSISTANT.as_bytes(), CSI).unwrap();
830        let refused = judge(
831            Some(&offered),
832            None,
833            allow(&moneypenny(), false),
834            ToolCheck::Strict,
835        )
836        .unwrap_err();
837        assert!(
838            refused.contains("functions.exec, functions.wait")
839                && refused.contains("no tool of MCP server moneypenny"),
840            "{refused}"
841        );
842    }
843
844    #[test]
845    fn the_users_mcp_servers_but_the_threads_are_switched_off_by_name() {
846        assert_eq!(
847            mcp_server_names(MCP_LIST.as_bytes(), CSI).unwrap(),
848            ["node_repl"]
849        );
850        let listed = mcp_server_names(MCP_LIST_ASSISTANT.as_bytes(), CSI).unwrap();
851        assert_eq!(
852            listed,
853            ["moneypenny", "node_repl"],
854            "the thread's server is listed beside the user's"
855        );
856        assert_eq!(
857            switch_off_servers(&listed, &moneypenny()),
858            (
859                vec![
860                    "-c".to_owned(),
861                    "mcp_servers.node_repl.enabled=false".to_owned()
862                ],
863                Vec::new()
864            )
865        );
866        assert_eq!(
867            switch_off_servers(&listed, &[]).0,
868            [
869                "-c",
870                "mcp_servers.moneypenny.enabled=false",
871                "-c",
872                "mcp_servers.node_repl.enabled=false"
873            ]
874        );
875        let odd = [
876            "we.ird".to_owned(),
877            "sp ace".to_owned(),
878            "ok-name_1".to_owned(),
879        ];
880        assert_eq!(
881            switch_off_servers(&odd, &[]),
882            (
883                vec![
884                    "-c".to_owned(),
885                    "mcp_servers.ok-name_1.enabled=false".to_owned()
886                ],
887                vec!["\"we.ird\"".to_owned(), "\"sp ace\"".to_owned()]
888            ),
889            "a name Codex cannot address by a dotted key stays on and is reported"
890        );
891    }
892
893    #[test]
894    fn mcp_list_output_is_read_exactly_or_not_at_all() {
895        assert_eq!(mcp_server_names(b"[]\n", CSI), Some(Vec::new()));
896        let mut rendered = b"\x1b[?25l\x1b]0;codex\x07\r\n".to_vec();
897        rendered.extend_from_slice(MCP_LIST.replace('\n', "\r\n").as_bytes());
898        assert_eq!(
899            mcp_server_names(&rendered, CSI),
900            mcp_server_names(MCP_LIST.as_bytes(), CSI)
901        );
902        for output in [
903            "",
904            "No MCP servers configured yet. Try `codex mcp add my-tool -- my-command`.",
905            "Error: failed to load bootstrap configuration\n\nCaused by:\n    invalid transport",
906            "[{\"enabled\":true}]",
907            "[{\"name\":7}]",
908            "{\"name\":\"node_repl\"}",
909            "[] trailing",
910            "[{\"name\":\"a\"}] [{\"name\":\"b\"}]",
911        ] {
912            assert_eq!(mcp_server_names(output.as_bytes(), CSI), None, "{output}");
913        }
914    }
915
916    #[test]
917    fn extra_tools_are_refused_and_named_or_started_as_a_weakening() {
918        let offered = offered_tools(CODE_MODE.as_bytes(), CSI).unwrap();
919        assert!(offered.iter().any(|tool| tool == "mcp__moneypenny.board"));
920        let refused = judge(
921            Some(&offered),
922            None,
923            allow(&moneypenny(), false),
924            ToolCheck::Strict,
925        )
926        .unwrap_err();
927        assert!(
928            refused.contains("functions.exec, functions.request_user_input"),
929            "{refused}"
930        );
931        assert!(
932            !refused.contains("board"),
933            "the server's own tool is allowed"
934        );
935        let weakening = judge(
936            Some(&offered),
937            None,
938            allow(&moneypenny(), false),
939            ToolCheck::Warn,
940        )
941        .unwrap()
942        .unwrap();
943        assert!(weakening.contains("functions.exec"), "{weakening}");
944    }
945
946    /// `codex debug prompt-input` of Codex 0.164.0 on Windows for an assistant with scripts: the
947    /// kept script features, the sandbox profile with `personal/` and `scratch/` writable and
948    /// one MCP server, `moneypenny`; `exec`'s description whole.
949    const SCRIPTS: &str = include_str!("../tests/fixtures/codex-0.164.0/prompt-input-scripts.json");
950
951    #[test]
952    fn a_scripts_thread_is_offered_code_mode_alone_and_passes_only_with_scripts() {
953        let servers = moneypenny();
954        let offered = offered_tools(SCRIPTS.as_bytes(), CSI).unwrap();
955        let nested = exec_nested(SCRIPTS.as_bytes(), CSI).unwrap();
956        assert_eq!(
957            offered, CODE_MODE_TOOLS,
958            "the server's tools are nested in exec"
959        );
960        assert_eq!(
961            nested,
962            [
963                "apply_patch",
964                "exec_command",
965                "list_mcp_resource_templates",
966                "list_mcp_resources",
967                "read_mcp_resource",
968                "write_stdin",
969                "clock__curr_time"
970            ],
971            "the server's own tools are deferred, out of the description"
972        );
973        let judged = |offered: &[String], nested: &[String], allowed| {
974            judge(Some(offered), Some(nested), allowed, ToolCheck::Strict)
975        };
976        assert_eq!(judged(&offered, &nested, allow(&servers, true)), Ok(None));
977        let refused = judged(&offered, &nested, allow(&servers, false)).unwrap_err();
978        assert!(
979            refused.contains("functions.exec, functions.wait"),
980            "{refused}"
981        );
982        let more = [
983            offered.clone(),
984            vec!["functions.request_user_input".to_owned()],
985        ]
986        .concat();
987        let refused = judged(&more, &nested, allow(&servers, true)).unwrap_err();
988        assert!(
989            refused.contains("functions.request_user_input") && !refused.contains("exec"),
990            "only code mode is admitted: {refused}"
991        );
992    }
993
994    #[test]
995    fn exec_nests_only_the_command_tools_the_patch_tool_with_files_and_the_servers() {
996        let servers = moneypenny();
997        let offered = offered_tools(SCRIPTS.as_bytes(), CSI).unwrap();
998        let nested = exec_nested(SCRIPTS.as_bytes(), CSI).unwrap();
999        let no_files = Allowed {
1000            servers: &servers,
1001            code_mode: true,
1002            commands: true,
1003            files: false,
1004        };
1005        let refused =
1006            judge(Some(&offered), Some(&nested), no_files, ToolCheck::Strict).unwrap_err();
1007        assert!(
1008            refused.contains("functions.exec beyond the thread's: apply_patch"),
1009            "{refused}"
1010        );
1011
1012        // A new nested tool, declared as Codex 0.164.0 declares its own.
1013        let browser = "\\n\\n### `browser__open`\\nOpens a page.\\n\\nexec tool declaration:\\n\
1014                       ```ts\\ndeclare const tools: { browser__open(args: {}): Promise<unknown>; \
1015                       };\\n```";
1016        let at = SCRIPTS.find("\\n\\n## clock").unwrap();
1017        let widened = format!("{}{browser}{}", &SCRIPTS[..at], &SCRIPTS[at..]);
1018        let nested = exec_nested(widened.as_bytes(), CSI).unwrap();
1019        assert!(
1020            nested.iter().any(|tool| tool == "browser__open"),
1021            "{nested:?}"
1022        );
1023        let refused = judge(
1024            Some(&offered),
1025            Some(&nested),
1026            allow(&servers, true),
1027            ToolCheck::Strict,
1028        )
1029        .unwrap_err();
1030        assert!(
1031            refused.contains("beyond the thread's: browser__open"),
1032            "{refused}"
1033        );
1034
1035        let allowed = allow(&servers, true);
1036        assert!(
1037            allowed.nests("mcp__moneypenny__board")
1038                && !allowed.nests("mcp__moneypenny_evil__board")
1039        );
1040        assert!(!allow(&[], true).nests("read_mcp_resource"));
1041
1042        let cut = SCRIPTS.replacen("exec tool declaration:", "", 1);
1043        assert_eq!(
1044            exec_nested(cut.as_bytes(), CSI),
1045            None,
1046            "a declaration without its heading"
1047        );
1048        assert!(
1049            judge(
1050                Some(&offered),
1051                None,
1052                allow(&servers, true),
1053                ToolCheck::Strict
1054            )
1055            .unwrap_err()
1056            .contains("could not be read")
1057        );
1058        assert_eq!(
1059            exec_nested(ANSWER_ONLY.as_bytes(), CSI),
1060            None,
1061            "the older fixtures cut exec's description"
1062        );
1063        assert_eq!(
1064            exec_nested(b"[{\"type\":\"message\"}]", CSI),
1065            Some(Vec::new())
1066        );
1067    }
1068
1069    /// `codex debug prompt-input` of Codex 0.164.0 on Windows for a `desk` thread, the settings
1070    /// of `desk_argv` with one MCP server, `ai6-cables`; `exec`'s description whole.
1071    const DESK: &str = include_str!("../tests/fixtures/codex-0.164.0/prompt-input-desk.json");
1072
1073    #[test]
1074    fn a_desk_thread_passes_with_no_command_tool_nested_in_exec() {
1075        let servers = vec!["ai6-cables".to_owned()];
1076        let offered = offered_tools(DESK.as_bytes(), CSI).unwrap();
1077        let nested = exec_nested(DESK.as_bytes(), CSI).unwrap();
1078        assert_eq!(offered, CODE_MODE_TOOLS);
1079        assert_eq!(
1080            nested,
1081            [
1082                "apply_patch",
1083                "list_mcp_resource_templates",
1084                "list_mcp_resources",
1085                "read_mcp_resource",
1086                "clock__curr_time"
1087            ],
1088            "features.shell_tool=false takes the command tools out of exec"
1089        );
1090        let judged = |nested: &[String], allowed| {
1091            judge(Some(&offered), Some(nested), allowed, ToolCheck::Strict)
1092        };
1093        assert_eq!(judged(&nested, desk(&servers)), Ok(None));
1094
1095        // The same thread on a release that leaves a command tool in exec.
1096        let scripts = exec_nested(SCRIPTS.as_bytes(), CSI).unwrap();
1097        let refused = judged(&scripts, desk(&servers)).unwrap_err();
1098        assert!(
1099            refused.contains("functions.exec beyond the thread's: exec_command, write_stdin"),
1100            "{refused}"
1101        );
1102        let found = judge(
1103            Some(&offered),
1104            Some(&scripts),
1105            desk(&servers),
1106            ToolCheck::Warn,
1107        )
1108        .unwrap()
1109        .unwrap();
1110        assert!(found.contains("exec_command"), "{found}");
1111
1112        // A tool outside code mode, as a model not on code mode would be offered.
1113        let more = [offered.clone(), vec!["functions.shell".to_owned()]].concat();
1114        let refused = judge(
1115            Some(&more),
1116            Some(&nested),
1117            desk(&servers),
1118            ToolCheck::Strict,
1119        );
1120        assert!(refused.unwrap_err().contains("functions.shell"));
1121    }
1122
1123    #[test]
1124    fn exactly_the_servers_tools_pass() {
1125        let offered = vec![
1126            "mcp__moneypenny.board".to_owned(),
1127            "mcp__moneypenny.missions".to_owned(),
1128        ];
1129        assert_eq!(
1130            judge(
1131                Some(&offered),
1132                None,
1133                allow(&moneypenny(), false),
1134                ToolCheck::Strict
1135            ),
1136            Ok(None)
1137        );
1138        let lookalike = vec!["mcp__moneypenny_evil.board".to_owned()];
1139        assert!(
1140            judge(
1141                Some(&lookalike),
1142                None,
1143                allow(&moneypenny(), false),
1144                ToolCheck::Strict
1145            )
1146            .is_err()
1147        );
1148    }
1149
1150    #[test]
1151    fn unreadable_output_is_refused_unless_warned() {
1152        for output in [
1153            "",
1154            "Error: unknown command",
1155            "[{\"type\":\"hosted_tools\",\"tools\":[]}]",
1156            "[{\"type\":\"additional_tools\",\"tools\":[{\"type\":\"function\"}]}]",
1157            // No message: not a prompt.
1158            "[{\"type\":\"additional_tools\",\"tools\":[]}]",
1159            // Anything after the list.
1160            "[{\"type\":\"message\"}] [{\"type\":\"message\"}]",
1161            "[{\"type\":\"message\"}] trailing",
1162            // A list that does not open with an item.
1163            "[1, {\"type\":\"message\"}]",
1164        ] {
1165            let offered = offered_tools(output.as_bytes(), CSI);
1166            assert_eq!(offered, None, "{output}");
1167            assert!(judge(None, None, allow(&[], false), ToolCheck::Strict).is_err());
1168            assert!(
1169                judge(None, None, allow(&[], false), ToolCheck::Warn)
1170                    .unwrap()
1171                    .is_some()
1172            );
1173        }
1174    }
1175
1176    #[test]
1177    fn prompt_input_reads_through_a_terminal_that_broke_its_lines() {
1178        let mut rendered = b"\x1b[?9001h\x1b[?1004h\x1b[m\x1b]0;codex\x07\x1b[?25h\r\n".to_vec();
1179        let text = CODE_MODE.replace('\n', "\r\n");
1180        let (head, tail) = text.split_at(text.find("V8 isolate").unwrap());
1181        rendered.extend_from_slice(head.as_bytes());
1182        rendered.extend_from_slice(b"\r\n\x1b[23;80H");
1183        rendered.extend_from_slice(tail.as_bytes());
1184        assert_eq!(
1185            offered_tools(&rendered, CSI),
1186            offered_tools(CODE_MODE.as_bytes(), CSI)
1187        );
1188    }
1189
1190    #[test]
1191    fn the_feature_list_names_what_is_on() {
1192        let list = feature_list(FEATURES.as_bytes(), CSI).unwrap();
1193        assert_eq!(list.unread, Vec::<String>::new(), "every line is a feature");
1194        let enabled = list.enabled;
1195        for feature in [
1196            "code_mode_host",
1197            "computer_use",
1198            "browser_use",
1199            "plugins",
1200            "hooks",
1201            "skill_search",
1202            "sleep_tool",
1203            "tool_suggest",
1204            "image_generation",
1205            "incremental_tools",
1206        ] {
1207            assert!(enabled.iter().any(|f| f == feature), "{feature}");
1208        }
1209        assert!(!enabled.iter().any(|f| f == "memories"), "off by default");
1210        assert!(
1211            KEPT_FEATURES.contains(&"incremental_tools"),
1212            "kept, or prompt-input renders no tool"
1213        );
1214        assert_eq!(feature_list(b"Error: no such command\n", CSI), None);
1215        let noisy = format!("{FEATURES}\nWARNING: plugin cache is stale\n");
1216        assert_eq!(
1217            feature_list(noisy.as_bytes(), CSI).unwrap().unread,
1218            ["WARNING: plugin cache is stale"],
1219            "a line that is not a feature is kept, for the check to judge"
1220        );
1221    }
1222
1223    #[test]
1224    fn the_check_choice_is_strict_unless_warn() {
1225        let with = |value: &str| {
1226            ToolCheck::from_environment(&BTreeMap::from([(
1227                TOOL_CHECK_ENV.to_owned(),
1228                value.to_owned(),
1229            )]))
1230        };
1231        assert_eq!(
1232            ToolCheck::from_environment(&BTreeMap::new()).unwrap(),
1233            ToolCheck::Strict
1234        );
1235        assert_eq!(with("warn").unwrap(), ToolCheck::Warn);
1236        assert!(with("off").is_err(), "no way to skip the check");
1237    }
1238}