1use 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
30pub const TOOL_CHECK_ENV: &str = "AI6_CODEX_TOOL_CHECK";
33
34pub const KEPT_FEATURES: [&str; 5] = [
38 "secret_auth_storage",
39 "enable_request_compression",
40 "system_proxy_fallback",
41 "unbounded_connection_retries",
42 "incremental_tools",
46];
47
48const CODE_MODE_HOST: &str = "code_mode_host";
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub(crate) enum ToolCheck {
56 Strict,
57 Warn,
58}
59
60impl ToolCheck {
61 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#[derive(Clone, Debug, PartialEq, Eq)]
78pub(crate) struct Checked {
79 pub(crate) overrides: Vec<String>,
81 pub(crate) weakening: Option<String>,
83}
84
85#[derive(Clone, Debug, Default, PartialEq, Eq)]
88pub(crate) struct FeatureList {
89 pub(crate) enabled: Vec<String>,
90 pub(crate) unread: Vec<String>,
91}
92
93pub(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
118pub(crate) fn mcp_server_names(output: &[u8], csi: ai6::Limit) -> Option<Vec<String>> {
123 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
136fn 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
146fn addressable(name: &str) -> bool {
149 !name.is_empty()
150 && name
151 .bytes()
152 .all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte))
153}
154
155pub(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
173pub(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
191fn prompt_items(output: &[u8], csi: ai6::Limit) -> Option<Vec<Lenient<JsonObject<PromptItem>>>> {
193 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 read_catalog(&text[start..])
200}
201
202fn read_catalog<T: serde::de::DeserializeOwned>(array: &[u8]) -> Option<T> {
203 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
237pub(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
275fn 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
308pub(crate) const CODE_MODE_TOOLS: [&str; 2] = ["functions.exec", "functions.wait"];
312
313const COMMAND_TOOLS: [&str; 2] = ["exec_command", "write_stdin"];
316const MCP_RESOURCE_TOOLS: [&str; 3] = [
319 "list_mcp_resources",
320 "list_mcp_resource_templates",
321 "read_mcp_resource",
322];
323const INERT_TOOLS: [&str; 1] = ["clock__curr_time"];
326
327#[derive(Clone, Copy, Debug)]
329pub(crate) struct Allowed<'a> {
330 pub(crate) servers: &'a [String],
332 pub(crate) code_mode: bool,
335 pub(crate) commands: bool,
337 pub(crate) files: bool,
339}
340
341impl Allowed<'_> {
342 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 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
361pub(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
453fn 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
468pub(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#[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
492type 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
501pub(crate) struct Probe<'a> {
503 pub(crate) terminal: &'a Object<dyn AgentTerminal>,
504 pub(crate) executable: &'a str,
505 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 pub(crate) servers: &'a [String],
512 pub(crate) code_mode: bool,
514 pub(crate) commands: bool,
517 pub(crate) files: bool,
519 pub(crate) config: &'a crate::CodexConfig,
521}
522
523impl Probe<'_> {
524 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 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 fn csi(&self) -> ai6::Limit {
659 ai6::Limit::at(self.config.csi_bytes)
660 }
661 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 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 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 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 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 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 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 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 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 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 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 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 "[{\"type\":\"additional_tools\",\"tools\":[]}]",
1159 "[{\"type\":\"message\"}] [{\"type\":\"message\"}]",
1161 "[{\"type\":\"message\"}] trailing",
1162 "[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}