Skip to main content

ai6_agent_codex/
lib.rs

1//! Codex app-server JSON-RPC implementation of AI6's AgentHandler contract.
2
3#![doc = include_str!("../README.md")]
4#![deny(unsafe_code)]
5
6ai6::guatiao::providers!(CodexHandler);
7
8mod appserver;
9mod loadout;
10mod policy;
11mod sandbox;
12mod terminal;
13mod tools;
14
15#[cfg(test)]
16mod fixed_tests;
17
18pub use tools::{KEPT_FEATURES, TOOL_CHECK_ENV};
19
20use std::collections::{HashMap, VecDeque};
21use std::ffi::OsString;
22use std::path::Path;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, Condvar, Mutex, Weak};
25use std::time::{Duration, Instant};
26
27use ai6::directorates::m::identity::RunId;
28use ai6::directorates::q::terminal::{AgentTerminal, exit_code_text};
29use ai6::directorates::section_00::agent::{
30    AgentHandler, AgentResume, AgentStart, Answer, AssistantMode, ChoiceInfo, ModelInfo,
31    RunRecordFile, RunRecordQuery, SessionInfo, SessionList, StartOptions, clearance_reads_only,
32    clearance_runs_commands,
33};
34use ai6::directorates::section_00::gate::{GateClient, GateVerdict, gate};
35use ai6::directorates::section_00::ledger_seed::{
36    CODEX, SeedRequest, discard_transcript, new_session_id, write_transcript,
37};
38use ai6::directorates::section_00::listing;
39use ai6::directorates::section_00::loadout::LoadoutSupport;
40use ai6::directorates::section_00::records;
41use ai6::guatiao::library::{Object, ProviderError};
42use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
43use ai6::{
44    AgentEvent, AgentMessage, AgentSession, Bucket, BucketStatus, LIMIT_EVENT, LimitHit, Refill,
45    SessionChange, SessionCommand, Spend, UsageReport, UsageSource, UsageSupport, infer_limit,
46};
47use appserver::{
48    CommandInput, Details, Empty, Initialize, Initialized, Item, JsonObject, Message, ModelList,
49    Notification, OfThread, Reply, Request, ThreadConfig, ThreadList, ThreadPolicy, WINDOWS,
50    Window,
51};
52use coqui_acp_codex::harness::PlainSpawn;
53use coqui_acp_codex::harness::event::{Content, Event as CodexEvent, Outcome, PermissionRequest};
54use coqui_acp_codex::harness::mode::Mode as NeutralMode;
55use coqui_acp_codex::{
56    ClientInfo, CodexLaunch, CodexSession as AppServer, CodexSettings, Error as CodexError,
57    ThreadStart,
58};
59use policy::{ConfigRead, ThreadPermissions};
60use serde::Deserialize;
61#[cfg(test)]
62use serde_json::{Value, json};
63
64use terminal::{Link, TerminalSpawn};
65
66/// The visible models in the app server's answer to `model/list` and their reasoning efforts.
67fn models_of(answer: &Reply<ModelList>) -> Answer<Vec<ModelInfo>> {
68    let Some(models) = answer.result().and_then(ModelList::models) else {
69        return Answer::unknown("this Codex does not list its models");
70    };
71    Answer::known(
72        models
73            .filter(|model| model.hidden.copied() != Some(true))
74            .filter_map(|model| {
75                let id = model.model.text().or_else(|| model.id.text())?;
76                Some(ModelInfo {
77                    name: model
78                        .display_name
79                        .text()
80                        .filter(|name| *name != id)
81                        .map(str::to_owned),
82                    id: id.to_owned(),
83                    description: model.description.text().map(str::to_owned),
84                    efforts: model
85                        .supported_reasoning_efforts
86                        .read()
87                        .into_iter()
88                        .flatten()
89                        .filter_map(|effort| effort.read()?.0.reasoning_effort.text())
90                        .map(str::to_owned)
91                        .collect(),
92                })
93            })
94            .collect(),
95    )
96}
97
98/// The efforts of every model, once each, in the order they first appear.
99fn efforts_of(models: &Answer<Vec<ModelInfo>>) -> Answer<Vec<ChoiceInfo>> {
100    match models {
101        Answer::Known { value } => {
102            let mut seen: Vec<&str> = Vec::new();
103            for effort in value.iter().flat_map(|model| &model.efforts) {
104                if !seen.contains(&effort.as_str()) {
105                    seen.push(effort);
106                }
107            }
108            Answer::known(seen.into_iter().map(ChoiceInfo::of).collect())
109        }
110        Answer::Unknown { reason } => Answer::unknown(reason.clone()),
111        Answer::NotSupported => Answer::NotSupported,
112    }
113}
114
115/// The threads in the app server's answer to `thread/list`. An answer that is an error is
116/// unknown, saying which Codex was asked (`version`) and what it said.
117fn sessions_of(listed: &ThreadList, version: Option<&str>) -> Answer<SessionList> {
118    let Some(threads) = listed.threads() else {
119        let said = listed.refusal().unwrap_or("no list");
120        let which = version.map_or_else(
121            || "this Codex".to_owned(),
122            |version| format!("Codex {version}"),
123        );
124        return Answer::unknown(format!("{which} did not list its threads: {said}"));
125    };
126    Answer::known(SessionList {
127        sessions: threads
128            .into_iter()
129            .filter_map(|thread| {
130                Some(SessionInfo {
131                    id: thread.id()?.to_owned(),
132                    title: thread.title().map(str::to_owned),
133                    directory: thread.directory().map(str::to_owned),
134                    updated_at: thread.updated_at(),
135                })
136            })
137            .collect(),
138        incomplete: listed
139            .has_more()
140            .then(|| "Codex has more threads than its first page".to_owned()),
141    })
142}
143
144/// The requests that list what Codex can start with, as the app server takes them.
145fn listing_initialize() -> Request<Initialize> {
146    Request::new(
147        1,
148        "initialize",
149        Initialize::new("ai6", env!("CARGO_PKG_VERSION")),
150    )
151}
152
153fn listing_initialized() -> Notification<Empty> {
154    Notification::new("initialized", Empty {})
155}
156
157fn listing_models() -> Request<Empty> {
158    Request::new(2, "model/list", Empty {})
159}
160
161fn listing_threads() -> Request<Empty> {
162    Request::new(3, "thread/list", Empty {})
163}
164
165/// The parameters of `thread/compact/start`: the thread and nothing else.
166fn compact_params(thread: &str) -> OfThread<'_> {
167    OfThread::new(thread)
168}
169
170/// What Codex can start with: its models and their efforts from `model/list`, the harness-neutral
171/// modes `coqui-acp-codex` maps to its approval policy and sandbox, its threads from
172/// `thread/list`, and no other option.
173fn start_options_of(models: Answer<Vec<ModelInfo>>, sessions: Answer<SessionList>) -> StartOptions {
174    StartOptions {
175        efforts: efforts_of(&models),
176        models,
177        modes: Answer::known(
178            NeutralMode::ALL
179                .into_iter()
180                .map(|mode| ChoiceInfo {
181                    id: mode.id().to_owned(),
182                    name: Some(mode.name().to_owned()),
183                    description: Some(mode.description().to_owned()),
184                })
185                .collect(),
186        ),
187        config: Answer::NotSupported,
188        sessions,
189    }
190}
191
192/// Codex app-server AgentHandler configuration.
193#[derive(Debug, Clone, ToValue, FromValue, Schema)]
194#[map(crate = ::ai6::guatiao)]
195pub struct CodexConfig {
196    /// Executable visible to the AI6-owned terminal environment.
197    #[map(default = String::from("codex"))]
198    pub executable: String,
199    /// Bytes of one line of the app server's output a Run holds before handing over what it
200    /// has. Default 67108864 (64 MiB).
201    #[map(default = 64 * 1024 * 1024)]
202    pub json_line_bytes: u64,
203    /// Bytes of one terminal control sequence before it is dropped, from the app server's
204    /// output and from the commands of the tool check. Default 64.
205    #[map(default = 64)]
206    pub csi_bytes: u64,
207    /// Bytes an assistant's context file may hold. Default 1048576 (1 MiB).
208    #[map(default = 1024 * 1024)]
209    pub context_file_bytes: u64,
210    /// How many of the last non-JSON lines a failed Run quotes. Default 8.
211    #[map(default = 8)]
212    pub tail_lines: u64,
213    /// Bytes of each of those lines a failed Run quotes. Default 512.
214    #[map(default = 512)]
215    pub tail_line_bytes: u64,
216    /// Milliseconds a closing Run waits for the app server to have exited. Default 2000.
217    #[map(default = 2_000)]
218    pub close_wait_ms: u64,
219    /// Milliseconds the end of the output waits for the app server's exit status. Default 1000.
220    #[map(default = 1_000)]
221    pub exit_wait_ms: u64,
222    /// Milliseconds the app server may take to answer `initialize`. Default 20000.
223    #[map(default = 20_000)]
224    pub start_timeout_ms: u64,
225    /// Milliseconds the app server may take to answer a thread request (`thread/start`,
226    /// `thread/resume`, `config/read`). Default 30000.
227    #[map(default = 30_000)]
228    pub request_timeout_ms: u64,
229    /// Milliseconds the sandbox probe of an assistant's scripts may run. Default 60000.
230    #[map(default = 60_000)]
231    pub sandbox_probe_timeout_ms: u64,
232    /// Seconds the answer of that probe stands per executable and configuration environment.
233    /// Default 900.
234    #[map(default = 900)]
235    pub sandbox_probe_lifetime_secs: u64,
236    /// Characters of the probe's last output line quoted when the sandbox did not run. Default
237    /// 300.
238    #[map(default = 300)]
239    pub sandbox_error_chars: u64,
240    /// On Unix, how many times the process table is read again when the sandbox probe's
241    /// process tree is killed. Default 32; Windows ignores it.
242    #[map(default = 32)]
243    pub tree_scans: u64,
244    /// Seconds the tool check's feature list stands for the same Codex, settings and
245    /// environment. Default 900.
246    #[map(default = 900)]
247    pub tool_check_lifetime_secs: u64,
248    /// Milliseconds one of the tool check's commands may run. Default 120000.
249    #[map(default = 120_000)]
250    pub tool_command_timeout_ms: u64,
251}
252
253impl Default for CodexConfig {
254    fn default() -> Self {
255        Self {
256            executable: String::from("codex"),
257            json_line_bytes: 64 * 1024 * 1024,
258            csi_bytes: 64,
259            context_file_bytes: 1024 * 1024,
260            tail_lines: 8,
261            tail_line_bytes: 512,
262            close_wait_ms: 2_000,
263            exit_wait_ms: 1_000,
264            start_timeout_ms: 20_000,
265            request_timeout_ms: 30_000,
266            sandbox_probe_timeout_ms: 60_000,
267            sandbox_probe_lifetime_secs: 900,
268            sandbox_error_chars: 300,
269            tree_scans: 32,
270            tool_check_lifetime_secs: 900,
271            tool_command_timeout_ms: 120_000,
272        }
273    }
274}
275
276impl CodexConfig {
277    fn millis(&self, ms: u64) -> Duration {
278        Duration::from_millis(ms)
279    }
280}
281
282/// Starts and resumes Codex through its app-server protocol.
283#[derive(Provider)]
284#[provider(
285    AgentHandler,
286    id = "codex",
287    name = "Codex",
288    crate = ::ai6::guatiao,
289    config = CodexConfig
290)]
291pub struct CodexHandler {
292    config: CodexConfig,
293}
294
295impl TryFrom<CodexConfig> for CodexHandler {
296    type Error = ProviderError;
297
298    fn try_from(config: CodexConfig) -> Result<Self, Self::Error> {
299        if config.executable.trim().is_empty() {
300            return Err(refuse(
301                Status::GUATIAO_ERR_BAD_VALUE,
302                "Codex executable is empty",
303            ));
304        }
305        Ok(Self { config })
306    }
307}
308
309/// The format of Codex's rollout file.
310pub const RECORD_FORMAT: &str = "codex-rollout-jsonl";
311
312/// Codex's rollout of the thread `query` names, when it is on this host: `runs/YYYY/MM/DD/
313/// rollout-<time>-<thread>.jsonl` under `CODEX_HOME` (else `~/.codex`).
314fn codex_record(query: &RunRecordQuery) -> Option<RunRecordFile> {
315    if !records::file_safe(&query.run_id) {
316        return None;
317    }
318    let root = records::configured_dir(&query.environment, "CODEX_HOME", ".codex")?;
319    let suffix = format!("-{}.jsonl", query.run_id);
320    let path = records::find_file(&root.join("runs"), 3, &|file| {
321        file.starts_with("rollout-") && file.ends_with(&suffix)
322    })?;
323    Some(RunRecordFile {
324        path: path.to_string_lossy().into_owned(),
325        format: RECORD_FORMAT.to_owned(),
326    })
327}
328
329impl AgentHandler for CodexHandler {
330    /// `codex app-server` speaks JSON-RPC, one message per line, over standard input and output.
331    fn stdio(&self) -> Result<ai6::HarnessStdio, ProviderError> {
332        Ok(ai6::HarnessStdio::Json)
333    }
334
335    /// The app server compacts a thread on request (`thread/compact/start`) and opens another
336    /// thread on request (`thread/start`), which is a clear that keeps the process.
337    fn session_commands(&self) -> Result<ai6::SessionCommands, ProviderError> {
338        Ok(ai6::SessionCommands {
339            compact: true,
340            clear: true,
341            unsupported_because: None,
342        })
343    }
344
345    fn read_only_refusal(&self) -> Result<Option<String>, ProviderError> {
346        Ok(None)
347    }
348
349    fn program(&self) -> Result<Option<String>, ProviderError> {
350        Ok(Some(self.config.executable.clone()))
351    }
352
353    /// Codex keeps each thread as a rollout file, one JSON object per line.
354    fn run_record(&self, query: RunRecordQuery) -> Result<Option<RunRecordFile>, ProviderError> {
355        Ok(codex_record(&query))
356    }
357
358    /// The app server's `model/list` and `thread/list`: the models Codex offers the account
359    /// behind `environment` (its `CODEX_HOME` login or API key) with the efforts each takes, and
360    /// the threads it holds, before any model turn. With no login it answers from the catalog it
361    /// ships with, so the list is what Codex offers, not a check of the account. Its modes are
362    /// the harness-neutral ones `coqui-acp-codex` maps to an approval policy and a sandbox;
363    /// Codex has no other option to choose.
364    fn start_options(
365        &self,
366        environment: std::collections::BTreeMap<String, String>,
367    ) -> Result<StartOptions, ProviderError> {
368        let start = self.config.millis(self.config.start_timeout_ms);
369        let request = self.config.millis(self.config.request_timeout_ms);
370        let asked = listing::ask(
371            &self.config.executable,
372            &["app-server"],
373            &environment,
374            start + request * 2,
375            |harness| {
376                harness.send(&listing_initialize())?;
377                let initialized = harness
378                    .next_where(|line: &JsonObject<Reply<Initialized>>| line.0.answers(1))?;
379                harness.send(&listing_initialized())?;
380                harness.send(&listing_models())?;
381                let models =
382                    harness.next_where(|line: &JsonObject<Reply<ModelList>>| line.0.answers(2))?;
383                harness.send(&listing_threads())?;
384                // A Codex that does not know the method answers an error with no id.
385                let threads = harness.next_where(|line: &JsonObject<ThreadList>| {
386                    line.0.answers(3) || line.0.is_unidentified_error()
387                })?;
388                Ok((initialized, models, threads))
389            },
390        );
391        Ok(match asked {
392            Ok((initialized, models, threads)) => {
393                let version = initialized.0.result().and_then(Initialized::version);
394                start_options_of(models_of(&models.0), sessions_of(&threads.0, version))
395            }
396            Err(reason) => StartOptions {
397                models: Answer::unknown(reason.clone()),
398                efforts: Answer::unknown(reason.clone()),
399                sessions: Answer::unknown(reason),
400                ..start_options_of(Answer::NotSupported, Answer::NotSupported)
401            },
402        })
403    }
404
405    /// Codex reports each request's tokens and the account's rate-limit windows as a turn goes,
406    /// and its app server answers `account/rateLimits/read` with no turn, so a Station may poll it.
407    fn usage_support(&self) -> Result<UsageSupport, ProviderError> {
408        Ok(UsageSupport::new(vec![UsageSource::Reported], true))
409    }
410
411    /// Starts an app server with `environment`, reads the account's rate limits and ends it: no
412    /// thread is opened and no model turn is spent. A Codex that is not signed in with an account
413    /// that has allowances is an error, not an empty report.
414    fn usage(
415        &self,
416        environment: std::collections::BTreeMap<String, String>,
417    ) -> Result<UsageReport, ProviderError> {
418        let mut launch = CodexLaunch::new(std::env::temp_dir());
419        launch.executable = self.config.executable.clone().into();
420        launch.env = environment
421            .into_iter()
422            .map(|(name, value)| (name.into(), value.into()))
423            .collect();
424        launch.clear_env = true;
425        let mut settings = CodexSettings::new();
426        settings.initialize_timeout = self.config.millis(self.config.start_timeout_ms);
427        settings.request_timeout = self.config.millis(self.config.request_timeout_ms);
428        let buckets = AppServer::read_account_usage(&launch, &PlainSpawn, settings)
429            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error.to_string()))?;
430        let mut report = UsageReport::new();
431        report.sources = vec![UsageSource::Reported];
432        report.buckets = buckets;
433        Ok(report)
434    }
435
436    /// Asks Codex to run a command in the sandbox an assistant's scripts would get (`codex
437    /// sandbox -P`, no model involved; on Windows MXC), with `environment`; the answer stands
438    /// 15 minutes per executable and configuration environment.
439    fn assistant_scripts(
440        &self,
441        environment: std::collections::BTreeMap<String, String>,
442    ) -> Result<Option<String>, ProviderError> {
443        Ok(sandbox::unavailable(&self.config, &environment))
444    }
445
446    fn assistant_skills(&self) -> Result<Option<String>, ProviderError> {
447        Ok(Some(NO_SKILL_LIST.to_owned()))
448    }
449
450    /// An assistant has no web tool, and its scripts have no network under any policy.
451    fn assistant_network(&self) -> Result<Option<String>, ProviderError> {
452        Ok(None)
453    }
454
455    /// Codex takes stdio MCP servers and disables a server's tools by name; a permission profile
456    /// limits its commands' writes and gives them no network, where its sandbox runs; it has no host
457    /// list.
458    fn loadout_support(&self) -> Result<LoadoutSupport, ProviderError> {
459        let environment: std::collections::BTreeMap<String, String> = std::env::vars().collect();
460        Ok(loadout::support(sandbox::unavailable(
461            &self.config,
462            &environment,
463        )))
464    }
465
466    fn start(
467        &self,
468        request: AgentStart,
469        terminal: Object<dyn AgentTerminal>,
470    ) -> Result<Object<dyn ai6::AgentSession>, ProviderError> {
471        let gate = station_gate(&request.environment);
472        self.start_gated(request, terminal, gate)
473    }
474
475    fn resume(
476        &self,
477        request: AgentResume,
478        terminal: Object<dyn AgentTerminal>,
479    ) -> Result<Object<dyn ai6::AgentSession>, ProviderError> {
480        let profile = scripts_profile(
481            &self.config.executable,
482            &request.working_directory,
483            &request.environment,
484            request.assistant.as_ref(),
485        );
486        let desk = held_to_desk(
487            &request.clearance,
488            request.answer_only,
489            request.assistant.as_ref(),
490        );
491        refuse_resume_in_theater(
492            &request.environment,
493            desk || request.answer_only || request.assistant.is_some(),
494        )?;
495        let gate = station_gate(&request.environment)
496            .filter(|_| !(request.answer_only || request.assistant.is_some()));
497        let applied = loadout::apply(
498            &self.config,
499            &request.loadout,
500            &request.environment,
501            &request.working_directory,
502            request.answer_only || request.assistant.is_some() || desk,
503        )?;
504        let run = open(Opening {
505            config: &self.config,
506            terminal,
507            cwd: &request.working_directory,
508            environment: &request.environment,
509            mode: Mode {
510                config: &self.config,
511                project_settings: request.project_settings,
512                answer_only: request.answer_only || request.assistant.is_some(),
513                desk,
514                assistant: request.assistant.as_ref(),
515                model: request.model.as_deref(),
516                profile: profile.as_ref(),
517            },
518            thread: ThreadStart::Resume(request.run_id.as_str().to_owned()),
519            model: request.model.clone(),
520            effort: request.effort,
521            instructions: None,
522            gate,
523            restriction: restriction(
524                request.answer_only,
525                request.assistant.as_ref(),
526                desk.then_some(&request.environment),
527                clearance_reads_only(&request.clearance),
528            ),
529            profile: profile.as_ref(),
530            loadout: applied,
531        })?;
532        if let Some(message) = request.message
533            && let Err(error) = run.send_message(AgentMessage { text: message })
534        {
535            let _ = run.close();
536            return Err(error);
537        }
538        Ok(run.into_object())
539    }
540}
541
542impl CodexHandler {
543    /// Starts a thread whose command approvals `gate` answers.
544    fn start_gated(
545        &self,
546        request: AgentStart,
547        terminal: Object<dyn AgentTerminal>,
548        gate: Option<Gate>,
549    ) -> Result<Object<dyn ai6::AgentSession>, ProviderError> {
550        let scripts = Scripts::of(request.assistant.as_ref());
551        // Codex 0.164.0 reads skills from its home and the project only: no setting and no
552        // `skills/list` root added one, so an overlay's skill is the file a routing line names.
553        let mut instructions = request
554            .overlays
555            .with_routing(&request.initial_context, false);
556        let desk = held_to_desk(
557            &request.clearance,
558            request.answer_only,
559            request.assistant.as_ref(),
560        );
561        if let Some(mode) = &request.assistant {
562            instructions.extend(assistant_instructions(
563                mode,
564                scripts,
565                self.config.context_file_bytes,
566            )?);
567        }
568        if desk {
569            instructions.push(DESK_READS_NOTHING.to_owned());
570        }
571        let profile = scripts_profile(
572            &self.config.executable,
573            &request.working_directory,
574            &request.environment,
575            request.assistant.as_ref(),
576        );
577        let gate = gate.filter(|_| !(request.answer_only || request.assistant.is_some()));
578        let applied = loadout::apply(
579            &self.config,
580            &request.loadout,
581            &request.environment,
582            &request.working_directory,
583            request.answer_only || request.assistant.is_some() || desk,
584        )?;
585        let mut written: Option<(String, std::path::PathBuf)> = None;
586        let thread = if let Some(ledger) = &request.ledger {
587            refuse_resume_in_theater(
588                &request.environment,
589                desk || request.answer_only || request.assistant.is_some(),
590            )?;
591            let codex_home = records::configured_dir(&request.environment, "CODEX_HOME", ".codex")
592                .ok_or_else(|| {
593                    refuse(
594                        Status::GUATIAO_ERR_INTERNAL,
595                        "Codex's home directory (`CODEX_HOME` or `HOME`) is not set",
596                    )
597                })?;
598            let session = ledger.session.clone().unwrap_or_else(new_session_id);
599            let document = &ledger.document;
600            write_transcript(
601                document,
602                &SeedRequest::new(CODEX, &request.working_directory, &session),
603                &codex_home,
604            )
605            .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?;
606            written = Some((session.clone(), codex_home));
607            ThreadStart::Resume(session)
608        } else {
609            ThreadStart::New
610        };
611        let started = open(Opening {
612            config: &self.config,
613            terminal,
614            cwd: &request.working_directory,
615            environment: &request.environment,
616            mode: Mode {
617                config: &self.config,
618                project_settings: request.project_settings,
619                answer_only: request.answer_only || request.assistant.is_some(),
620                desk,
621                assistant: request.assistant.as_ref(),
622                model: request.model.as_deref(),
623                profile: profile.as_ref(),
624            },
625            thread,
626            model: request.model.clone(),
627            effort: request.effort,
628            instructions: (!instructions.is_empty()).then(|| instructions.join("\n\n")),
629            gate,
630            restriction: restriction(
631                request.answer_only,
632                request.assistant.as_ref(),
633                desk.then_some(&request.environment),
634                clearance_reads_only(&request.clearance),
635            ),
636            profile: profile.as_ref(),
637            loadout: applied,
638        });
639        let forget = |written: &Option<(String, std::path::PathBuf)>| {
640            if let Some((session, home)) = written {
641                discard_transcript(CODEX, session, home);
642            }
643        };
644        let run = match started {
645            Ok(run) => run,
646            Err(error) => {
647                forget(&written);
648                return Err(error);
649            }
650        };
651        if !request.prompt.is_empty()
652            && let Err(error) = run.send_message(AgentMessage {
653                text: request.prompt,
654            })
655        {
656            let _ = run.close();
657            forget(&written);
658            return Err(error);
659        }
660        Ok(run.into_object())
661    }
662}
663
664/// What a `desk` thread is told: Codex reads files through commands, and it has none, so what it
665/// writes down about the checkout is not from reading it.
666const DESK_READS_NOTHING: &str = "This conversation has no tool that reads a file, so you cannot \
667     read the checkout: work from the brief and the AI6 tools only, and say in what you submit \
668     which files you would have read and could not.";
669
670/// What a restricted (answer-only, assistant or `desk`) thread may use besides answering.
671#[derive(Clone, Debug, Default, PartialEq, Eq)]
672struct Restriction {
673    /// The MCP servers whose tools it may call.
674    servers: Vec<String>,
675    /// Whether it may run commands: an assistant with scripts.
676    commands: bool,
677    /// Whether it may change files through Codex's own patch tool: an assistant with scripts
678    /// and directories to write, or a `desk` thread working on the Station's disk.
679    file_changes: bool,
680    /// Whether Codex asks before each change, and only one inside the working directory is
681    /// accepted: a `desk` thread, with or without a green ink gate.
682    asks_file_changes: bool,
683}
684
685/// Whether a Mission's thread at `clearance` is held to `desk`: answer-only and assistant threads
686/// have limits of their own.
687fn held_to_desk(clearance: &str, answer_only: bool, assistant: Option<&AssistantMode>) -> bool {
688    !answer_only && assistant.is_none() && !clearance_runs_commands(clearance)
689}
690
691/// AI6's own MCP servers a Run's environment names, as [`app_server_argv`] configures them.
692fn station_servers(environment: &std::collections::BTreeMap<String, String>) -> Vec<String> {
693    [
694        ("ai6-cables", "AI6_CABLE_MCP"),
695        ("ai6-theater", "AI6_THEATER_MCP"),
696    ]
697    .iter()
698    .filter(|(_, prefix)| {
699        environment.contains_key(&format!("{prefix}_URL"))
700            && environment.contains_key(&format!("{prefix}_TOKEN"))
701    })
702    .map(|(server, _)| (*server).to_owned())
703    .collect()
704}
705
706/// What a restricted thread may use, `None` for a thread that is not restricted. `desk` is the
707/// environment of a thread held to `desk`; `reads_only` holds it further, to reading until its plan
708/// passes: no file change at all, so a patch ends the thread.
709fn restriction(
710    answer_only: bool,
711    assistant: Option<&AssistantMode>,
712    desk: Option<&std::collections::BTreeMap<String, String>>,
713    reads_only: bool,
714) -> Option<Restriction> {
715    if let Some(environment) = desk {
716        let changes = !is_remote_hands(environment) && !reads_only;
717        return Some(Restriction {
718            servers: station_servers(environment),
719            commands: false,
720            file_changes: changes,
721            asks_file_changes: changes,
722        });
723    }
724    match assistant {
725        Some(mode) => {
726            let commands = Scripts::of(Some(mode)) != Scripts::None;
727            Some(Restriction {
728                servers: mode
729                    .mcp_servers
730                    .iter()
731                    .map(|server| server.name.clone())
732                    .collect(),
733                commands,
734                file_changes: commands && (mode.unsandboxed || !mode.files.is_empty()),
735                asks_file_changes: false,
736            })
737        }
738        None => answer_only.then(Restriction::default),
739    }
740}
741
742/// Where an assistant's scripts run.
743#[derive(Clone, Copy, Debug, PartialEq, Eq)]
744enum Scripts {
745    /// No scripts: no interpreter, or no assistant.
746    None,
747    /// In Codex's sandbox, under [`sandbox::PROFILE`].
748    Sandboxed,
749    /// Without a sandbox (`AssistantMode::unsandboxed`).
750    Unsandboxed,
751}
752
753impl Scripts {
754    fn of(assistant: Option<&AssistantMode>) -> Self {
755        match assistant {
756            Some(mode) if !mode.interpreters.is_empty() && mode.unsandboxed => Self::Unsandboxed,
757            Some(mode) if !mode.interpreters.is_empty() => Self::Sandboxed,
758            _ => Self::None,
759        }
760    }
761}
762
763/// Why this handler loads no skill for an assistant.
764const NO_SKILL_LIST: &str = "Codex has no list of allowed skills: it loads the skills of the \
765                             project, of the user's home directory and of the system, and its own \
766                             bundled ones";
767
768/// The developer instructions an assistant thread gets besides its initial context: the text
769/// of its `context_file`, and what it cannot do here that its mode suggests it could.
770fn assistant_instructions(
771    mode: &AssistantMode,
772    scripts: Scripts,
773    context_file_bytes: u64,
774) -> Result<Vec<String>, ProviderError> {
775    let mut parts = Vec::new();
776    if let Some(file) = &mode.context_file {
777        let size = std::fs::metadata(file)
778            .map_err(|error| {
779                refuse(
780                    Status::GUATIAO_ERR_BAD_VALUE,
781                    format!("context file: {error}"),
782                )
783            })?
784            .len();
785        if size > context_file_bytes {
786            return Err(refuse(
787                Status::GUATIAO_ERR_BAD_VALUE,
788                format!("the context file holds {size} bytes, more than {context_file_bytes}"),
789            ));
790        }
791        let text = std::fs::read_to_string(file).map_err(|error| {
792            refuse(
793                Status::GUATIAO_ERR_BAD_VALUE,
794                format!("context file: {error}"),
795            )
796        })?;
797        parts.push(text);
798    }
799    if scripts == Scripts::None && !mode.files.is_empty() {
800        parts.push(
801            "You have no file tools in this conversation: you cannot create or change files, \
802             your memory among them. Say so when the person asks you to save or remember \
803             something."
804                .to_owned(),
805        );
806    }
807    if scripts == Scripts::Sandboxed && !mode.network.reaches_nothing() {
808        eprintln!(
809            "ai6: warning: Moneypenny's scripts run with no network under Codex: its app server enforces \
810             no host list for them, so they get none"
811        );
812        parts.push(
813            "Your scripts have no network access in this conversation: say so when the person \
814             asks for something that needs it."
815                .to_owned(),
816        );
817    }
818    Ok(parts)
819}
820
821/// Decides whether a command Codex asks to run may go ahead, given its working directory.
822type Gate = Arc<dyn Fn(&str, Option<&Path>) -> GateVerdict + Send + Sync>;
823
824/// The green ink gate asking the Run's Station through its Cable endpoint. A Run with
825/// no endpoint cannot ask for green ink at all, so it has no gate, as with Claude Code.
826fn station_gate(environment: &std::collections::BTreeMap<String, String>) -> Option<Gate> {
827    let client = GateClient::from_environment(environment)?;
828    Some(Arc::new(move |command, cwd| {
829        gate(command, cwd, Some(&client))
830    }))
831}
832
833/// When the thread asks before running a command. Answer-only, or in remote-hands mode, it
834/// never asks (its sandbox is read-only, and in remote-hands mode the Station gates
835/// `theater_run`); with a green ink gate it asks (`untrusted`) for every command outside
836/// Codex's own list of safe reads, so the gate sees each one.
837/// An assistant with scripts never asks either, and runs them in the sandbox its app server's
838/// profile describes (no `sandbox` here: Codex does not combine the two), or with none when
839/// unsandboxed. A `desk` thread has no command to ask about; `untrusted` over a read-only sandbox
840/// makes Codex 0.164.0 ask about each patch, so the handler decides where it lands.
841fn set_approval_policy(
842    params: &mut ThreadPolicy,
843    environment: &std::collections::BTreeMap<String, String>,
844    answer_only: bool,
845    scripts: Scripts,
846    desk: bool,
847) {
848    if answer_only {
849        restrict_to_answer_only(params);
850        match scripts {
851            Scripts::None => {}
852            Scripts::Sandboxed => params.sandbox = None,
853            Scripts::Unsandboxed => params.sandbox = Some("danger-full-access"),
854        }
855    } else if is_remote_hands(environment) {
856        restrict_to_remote_hands(params);
857    } else if desk {
858        params.sandbox = Some("read-only");
859        params.approval_policy = Some("untrusted");
860    } else if GateClient::from_environment(environment).is_some() {
861        params.approval_policy = Some("untrusted");
862    }
863}
864
865/// Everything `open` needs to start a thread.
866struct Opening<'a> {
867    config: &'a CodexConfig,
868    terminal: Object<dyn AgentTerminal>,
869    cwd: &'a str,
870    environment: &'a std::collections::BTreeMap<String, String>,
871    mode: Mode<'a>,
872    thread: ThreadStart,
873    model: Option<String>,
874    effort: Option<String>,
875    /// The developer instructions of a new thread.
876    instructions: Option<String>,
877    gate: Option<Gate>,
878    /// For a restricted (answer-only, assistant or `desk`) thread, what it may use.
879    restriction: Option<Restriction>,
880    profile: Option<&'a sandbox::Profile>,
881    /// What the Mission thread's loadout adds: MCP servers and a permission profile.
882    loadout: loadout::Applied,
883}
884
885/// Starts the app server on the Station's terminal and opens the thread, through
886/// `coqui-acp-codex`.
887fn open(opening: Opening<'_>) -> Result<CodexRun, ProviderError> {
888    let Opening {
889        config,
890        terminal,
891        cwd,
892        environment,
893        mode,
894        thread,
895        model,
896        effort,
897        instructions,
898        gate,
899        restriction,
900        profile,
901        loadout,
902    } = opening;
903    let scripts = Scripts::of(mode.assistant);
904    let (mut argv, weakening) = prepare(&terminal, &config.executable, cwd, environment, mode)?;
905    argv.extend(loadout.overrides.iter().cloned());
906    let mut policy = ThreadPolicy::default();
907    set_approval_policy(
908        &mut policy,
909        environment,
910        mode.answer_only,
911        scripts,
912        mode.desk,
913    );
914    let mut launch = CodexLaunch::new(cwd);
915    launch.executable = config.executable.clone().into();
916    launch.thread = thread;
917    launch.model = model;
918    launch.effort = effort;
919    launch.developer_instructions = instructions;
920    launch.approval_policy = policy.approval_policy.map(str::to_owned);
921    // Codex does not combine a `sandbox` with a permission profile.
922    if loadout.profile.is_some() {
923        launch.sandbox = None;
924    } else {
925        launch.sandbox = policy.sandbox.map(str::to_owned);
926    }
927    if let Some(settings) = &policy.config {
928        launch.thread_config = serde_json::to_value(settings)
929            .ok()
930            .and_then(|settings| settings.as_object().cloned())
931            .unwrap_or_default();
932    }
933    launch.extra_args = argv.iter().skip(2).map(OsString::from).collect();
934    if !mode.desk && !mode.answer_only {
935        launch.environment = native_environment(environment);
936    }
937    launch.client_info = ClientInfo::new("ai6", env!("CARGO_PKG_VERSION"));
938
939    let link = Arc::new(Link::default());
940    let shared = Arc::new(Shared::new(
941        gate,
942        restriction,
943        scripts != Scripts::None,
944        Path::new(cwd).to_path_buf(),
945        Arc::clone(&link),
946    ));
947    shared.weakened(weakening);
948
949    let mut settings = session_settings(config);
950    {
951        let shared = Arc::clone(&shared);
952        settings.on_line = Some(Arc::new(move |raw| {
953            let message = JsonObject::<Message>::deserialize(raw)
954                .map(|object| object.0)
955                .unwrap_or_default();
956            shared.line(&message, |hint| DriverEvent {
957                limit: coqui_acp_codex::limit_of_message(raw, hint),
958                cap_refusal: (message.method() == Some("error"))
959                    .then(|| CapError::deserialize(raw).ok()?.params.into_text())
960                    .flatten(),
961                data: serde_json::to_vec(raw).ok(),
962            })
963        }));
964    }
965    if let Some(profile) = profile {
966        let (config_check, thread_check) = (profile.clone(), profile.clone());
967        settings.check_config = Some(Arc::new(move |result| {
968            let result = JsonObject::<ConfigRead>::deserialize(result).map(|object| object.0);
969            config_check.check_config(&result.unwrap_or_default())
970        }));
971        settings.check_thread = Some(Arc::new(move |result| {
972            let result =
973                JsonObject::<ThreadPermissions>::deserialize(result).map(|object| object.0);
974            thread_check.check_thread(&result.unwrap_or_default())
975        }));
976    }
977    if let Some(profile) = loadout.profile.clone() {
978        let (config_check, thread_check) = (profile.clone(), profile);
979        settings.check_config = Some(Arc::new(move |result| {
980            let result = JsonObject::<ConfigRead>::deserialize(result).map(|object| object.0);
981            config_check.check_config(&result.unwrap_or_default())
982        }));
983        settings.check_thread = Some(Arc::new(move |result| {
984            let result =
985                JsonObject::<ThreadPermissions>::deserialize(result).map(|object| object.0);
986            thread_check.check_thread(&result.unwrap_or_default())
987        }));
988    }
989    let mut limits = ai6::station::limits::TerminalOutputLimits::default();
990    limits.json_line_bytes = ai6::Limit::at(config.json_line_bytes);
991    limits.csi_bytes = ai6::Limit::at(config.csi_bytes);
992    let spawner = TerminalSpawn {
993        terminal,
994        environment: environment.clone(),
995        limits,
996        link,
997    };
998    let sink = Arc::clone(&shared);
999    let session = AppServer::start(&launch, &spawner, settings, move |event| sink.tell(event))
1000        .map_err(started_with)?;
1001    // The thread was opened with the model; a turn names none of its own.
1002    session.set_model(None);
1003    let thread_id = RunId::try_from(session.thread())
1004        .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error))?;
1005    let session = Arc::new(session);
1006    *lock(&shared.session)? = Arc::downgrade(&session);
1007    Ok(CodexRun {
1008        session,
1009        shared,
1010        thread_id: Mutex::new(thread_id),
1011        request_wait: config.millis(config.request_timeout_ms),
1012    })
1013}
1014
1015/// The app server's settings from the agent's configuration. `resume_unconfirmed_environment` stays at its
1016/// default (off): a thread opened again with a host-given environment is refused rather than run unconfirmed.
1017fn session_settings(config: &CodexConfig) -> CodexSettings {
1018    let mut settings = CodexSettings::new();
1019    settings.max_line = config.json_line_bytes;
1020    settings.tail_lines = usize::try_from(config.tail_lines).unwrap_or(usize::MAX);
1021    settings.tail_line_bytes = usize::try_from(config.tail_line_bytes).unwrap_or(usize::MAX);
1022    settings.initialize_timeout = config.millis(config.start_timeout_ms);
1023    settings.request_timeout = config.millis(config.request_timeout_ms);
1024    settings.exit_wait = config.millis(config.exit_wait_ms);
1025    settings.close_wait = config.millis(config.close_wait_ms);
1026    settings.list_models = false;
1027    settings.version_wait = Duration::ZERO;
1028    settings
1029}
1030
1031/// What a failed start was, in AI6's terms.
1032fn started_with(error: CodexError) -> ProviderError {
1033    match error {
1034        CodexError::Refused(why) => refuse(Status::GUATIAO_ERR_UNSUPPORTED, why),
1035        CodexError::Timeout { .. } => {
1036            refuse(Status::GUATIAO_ERR_INTERNAL, "Codex app-server timed out")
1037        }
1038        CodexError::Harness(why) if why.ends_with("not the one requested") => refuse(
1039            Status::GUATIAO_ERR_BAD_VALUE,
1040            "Codex resumed a different thread than requested",
1041        ),
1042        other => refuse(Status::GUATIAO_ERR_INTERNAL, polished(&other.to_string())),
1043    }
1044}
1045
1046/// An exit reason in the words of a Run: how the driver words it, with a negative exit code also
1047/// as Windows names it.
1048fn polished(reason: &str) -> String {
1049    let mut text = reason
1050        .replace("before completing the session", "before completing the Run")
1051        .replace("closed its output", "closed its terminal");
1052    const CODE: &str = "exited with code ";
1053    if let Some(at) = text.find(CODE) {
1054        let start = at + CODE.len();
1055        let digits = text[start..]
1056            .char_indices()
1057            .find(|(index, c)| !(c.is_ascii_digit() || (*index == 0 && *c == '-')))
1058            .map_or(text.len(), |(index, _)| start + index);
1059        if let Ok(code) = text[start..digits].parse::<i64>() {
1060            text.replace_range(start..digits, &exit_code_text(code));
1061        }
1062    }
1063    text
1064}
1065
1066/// What a Run's reader thread and its caller share.
1067struct Shared {
1068    gate: Option<Gate>,
1069    events: Mutex<VecDeque<AgentEvent>>,
1070    arrived: Condvar,
1071    /// The events of approval requests, told once the request is answered, after the events the
1072    /// answer itself gave.
1073    held: Mutex<Vec<AgentEvent>>,
1074    /// The latest quota window the account reported as used up.
1075    exhausted: Mutex<Option<LimitHit>>,
1076    /// What the thread's requests have used since this process started: Codex reports each
1077    /// request, and its own running total survives a resume.
1078    spent: Mutex<Spend>,
1079    /// For a restricted (answer-only, assistant or `desk`) thread, what it may use.
1080    restricted: Option<Restriction>,
1081    /// Whether a command it starts is reported as the tool `exec_command`: an assistant with
1082    /// scripts, whose commands may read any file of her working directory and, unsandboxed,
1083    /// reach any host.
1084    reports_commands: bool,
1085    /// Set once a restricted thread used a tool it may not, and was ended.
1086    tripped: AtomicBool,
1087    /// The command of each command execution item the thread started, by item id.
1088    started: Mutex<HashMap<String, String>>,
1089    /// The paths of each file change item the thread started, by item id.
1090    started_changes: Mutex<HashMap<String, Vec<String>>>,
1091    /// Where a file change is the Mission's own work.
1092    working_directory: std::path::PathBuf,
1093    /// Set once the end of the app server was reported as a `failed` event.
1094    ended_reported: AtomicBool,
1095    link: Arc<Link>,
1096    session: Mutex<Weak<AppServer>>,
1097    /// The thread's context size as the app server last said it, and what a compaction in
1098    /// flight started from.
1099    context: Mutex<Context>,
1100}
1101
1102/// What `thread/tokenUsage/updated` says of the thread's context, kept to tell a compaction's
1103/// tokens before and after.
1104#[derive(Default)]
1105struct Context {
1106    /// The tokens of the latest request, which is the context it held.
1107    latest: Option<u64>,
1108    /// Set from `item/started` of a `contextCompaction` to its `item/completed`: the tokens
1109    /// held when it began.
1110    compacting: Option<Option<u64>>,
1111    /// Whether the Station asked for the compaction in flight, or for the next one to come.
1112    asked: bool,
1113    /// Whether a compaction finished since the Station asked.
1114    done: bool,
1115}
1116
1117fn failed(reason: String) -> AgentEvent {
1118    AgentEvent {
1119        kind: "failed".to_owned(),
1120        text: Some(reason),
1121        data: None,
1122        limit: None,
1123        tools: Vec::new(),
1124        report: None,
1125    }
1126}
1127
1128impl Shared {
1129    fn new(
1130        gate: Option<Gate>,
1131        restricted: Option<Restriction>,
1132        reports_commands: bool,
1133        working_directory: std::path::PathBuf,
1134        link: Arc<Link>,
1135    ) -> Self {
1136        Self {
1137            gate,
1138            events: Mutex::new(VecDeque::new()),
1139            arrived: Condvar::new(),
1140            held: Mutex::new(Vec::new()),
1141            exhausted: Mutex::new(None),
1142            spent: Mutex::new(Spend::new("")),
1143            restricted,
1144            reports_commands,
1145            tripped: AtomicBool::new(false),
1146            started: Mutex::default(),
1147            started_changes: Mutex::default(),
1148            working_directory,
1149            ended_reported: AtomicBool::new(false),
1150            link,
1151            session: Mutex::new(Weak::new()),
1152            context: Mutex::default(),
1153        }
1154    }
1155
1156    /// What a message says of a compaction, as the events that report it, in order. A
1157    /// compaction is one `contextCompaction` item in a turn of its own, whether the Station asked
1158    /// for it or Codex began it; the tokens after are the thread's last count in the turn.
1159    /// A turn the Station asked to compact that ends with no compaction reports why.
1160    fn compaction(&self, message: &Message) -> Vec<AgentEvent> {
1161        let Ok(mut context) = self.context.lock() else {
1162            return Vec::new();
1163        };
1164        let method = message.method();
1165        let item = message.item_kind();
1166        match (method, item) {
1167            (Some("thread/tokenUsage/updated"), _) => {
1168                if let Some(last) = message.context_tokens() {
1169                    context.latest = Some(last);
1170                }
1171                Vec::new()
1172            }
1173            (Some("item/started"), Some("contextCompaction")) => {
1174                context.compacting = Some(context.latest);
1175                Vec::new()
1176            }
1177            (Some("item/completed"), Some("contextCompaction")) => {
1178                let before = context.compacting.take().flatten();
1179                let trigger = if context.asked { "manual" } else { "auto" };
1180                context.done = true;
1181                vec![
1182                    SessionChange {
1183                        trigger: Some(trigger.to_owned()),
1184                        tokens_before: before,
1185                        tokens_after: context.latest,
1186                        session_id: None,
1187                    }
1188                    .event(ai6::COMPACTED_EVENT, None),
1189                ]
1190            }
1191            (Some("turn/completed" | "turn/failed"), _) if context.asked => {
1192                let compacted = std::mem::take(&mut context.done);
1193                context.asked = false;
1194                context.compacting = None;
1195                if compacted {
1196                    return Vec::new();
1197                }
1198                let why = message
1199                    .failure_text()
1200                    .unwrap_or("Codex ended the turn without compacting the thread");
1201                vec![
1202                    SessionChange::default().event(ai6::COMPACT_FAILED_EVENT, Some(why.to_owned())),
1203                ]
1204            }
1205            _ => Vec::new(),
1206        }
1207    }
1208
1209    /// Notes that the Station asked for a compaction.
1210    fn compaction_asked(&self) {
1211        if let Ok(mut context) = self.context.lock() {
1212            context.asked = true;
1213            context.done = false;
1214        }
1215    }
1216
1217    fn push(&self, event: AgentEvent) {
1218        if let Ok(mut events) = self.events.lock() {
1219            events.push_back(event);
1220            self.arrived.notify_all();
1221        }
1222    }
1223
1224    fn flush_held(&self) {
1225        let held = self
1226            .held
1227            .lock()
1228            .map(|mut held| std::mem::take(&mut *held))
1229            .unwrap_or_default();
1230        for event in held {
1231            self.push(event);
1232        }
1233    }
1234
1235    /// Reports what a `warn` tool check found, on the Station's log and as the Run's
1236    /// first event (kind `weakened`).
1237    fn weakened(&self, weakening: Option<String>) {
1238        if let Some(text) = weakening {
1239            eprintln!("ai6: info: {text}");
1240            self.push(AgentEvent {
1241                kind: "weakened".to_owned(),
1242                text: Some(text),
1243                data: None,
1244                limit: None,
1245                tools: Vec::new(),
1246                report: None,
1247            });
1248        }
1249    }
1250
1251    /// Ends a restricted thread that used `what`: the tool check confirmed before the start
1252    /// what Codex said it would offer, and this is the backstop for what it offered anyway.
1253    fn trip(&self, what: &str) {
1254        if self.tripped.swap(true, Ordering::AcqRel) {
1255            return;
1256        }
1257        let reason = format!(
1258            "the restricted Codex thread used {what}, which it may not use; the Run was ended"
1259        );
1260        eprintln!("ai6: {reason}");
1261        self.link.kill();
1262        self.ended_reported.store(true, Ordering::Release);
1263        self.push(failed(reason));
1264    }
1265
1266    /// Takes one message the app server wrote, before the driver reads it; `false` ends the app
1267    /// server.
1268    fn line(
1269        &self,
1270        message: &Message,
1271        driver_event: impl FnOnce(Option<&LimitHit>) -> DriverEvent,
1272    ) -> bool {
1273        self.flush_held();
1274        // An answer to one of the driver's own requests.
1275        if !message.has_method() {
1276            return true;
1277        }
1278        if self.tripped.load(Ordering::Acquire) {
1279            return false;
1280        }
1281        if let Some(restriction) = &self.restricted
1282            && let Some(what) = forbidden_use(message, restriction)
1283        {
1284            self.trip(&what);
1285            return false;
1286        }
1287        if message.method() == Some("item/started")
1288            && let Some(item) = message.item()
1289            && let Some(id) = item.id()
1290        {
1291            match item.kind() {
1292                Some("fileChange") => {
1293                    if let Ok(mut started) = self.started_changes.lock() {
1294                        started.insert(id.to_owned(), item.change_paths());
1295                    }
1296                }
1297                Some("commandExecution") => {
1298                    if let Some(command) = item.command()
1299                        && let Ok(mut started) = self.started.lock()
1300                    {
1301                        started.insert(id.to_owned(), command.to_owned());
1302                    }
1303                }
1304                _ => {}
1305            }
1306        }
1307        if let Some(exhausted) = exhausted_window(message)
1308            && let Ok(mut hint) = self.exhausted.lock()
1309        {
1310            *hint = Some(exhausted);
1311        }
1312        let hint = self.exhausted.lock().ok().and_then(|hint| hint.clone());
1313        let mut changes = self.compaction(message).into_iter();
1314        let turn_ends = matches!(message.method(), Some("turn/completed" | "turn/failed"));
1315        let Some(mut event) = decode_event(message, driver_event(hint.as_ref())) else {
1316            changes.for_each(|change| self.push(change));
1317            return true;
1318        };
1319        // A failed compaction is told before the turn ends, a finished one after its item.
1320        let told_after = if turn_ends {
1321            changes.by_ref().for_each(|change| self.push(change));
1322            Vec::new()
1323        } else {
1324            changes.collect::<Vec<_>>()
1325        };
1326        if self.reports_commands && started_item(message) == Some("commandExecution") {
1327            event.tools.push(COMMAND_TOOL.to_owned());
1328        }
1329        if let Some(spend) = event
1330            .report
1331            .as_mut()
1332            .and_then(|report| report.spend.as_mut())
1333            && let Ok(mut spent) = self.spent.lock()
1334        {
1335            spent.input = spent.input.saturating_add(spend.input);
1336            spent.output = spent.output.saturating_add(spend.output);
1337            spent.cache_read = spent.cache_read.saturating_add(spend.cache_read);
1338            spent.cache_write = spent.cache_write.saturating_add(spend.cache_write);
1339            *spend = spent.clone();
1340        }
1341        let asks =
1342            message.has_id() && matches!(message.method(), Some(COMMAND_APPROVAL | FILE_APPROVAL));
1343        if asks {
1344            if let Ok(mut held) = self.held.lock() {
1345                held.push(event);
1346            }
1347        } else {
1348            self.push(event);
1349        }
1350        told_after.into_iter().for_each(|change| self.push(change));
1351        true
1352    }
1353
1354    /// Takes what the driver tells of the app server.
1355    fn tell(&self, event: CodexEvent) -> bool {
1356        match event {
1357            CodexEvent::Permission(request) => self.permission(request),
1358            CodexEvent::Output(text) => self.push(AgentEvent {
1359                kind: "output".to_owned(),
1360                text: Some(text),
1361                data: None,
1362                limit: None,
1363                tools: Vec::new(),
1364                report: None,
1365            }),
1366            CodexEvent::Exited(reason) => {
1367                self.flush_held();
1368                // The app server's exit ends the Run once, with the reason.
1369                if !self.ended_reported.swap(true, Ordering::AcqRel) {
1370                    let reason = polished(&reason);
1371                    eprintln!("ai6: {reason}");
1372                    self.push(failed(reason));
1373                }
1374            }
1375            _ => {}
1376        }
1377        true
1378    }
1379
1380    /// Answers what the app server asks leave for. A question that is not a command or a file
1381    /// change is left unanswered, which the driver reports to the app server as nobody having
1382    /// chosen.
1383    fn permission(&self, request: PermissionRequest) {
1384        match details_of(&request).method() {
1385            Some(COMMAND_APPROVAL) => self.answer_command_approval(request),
1386            Some(FILE_APPROVAL) => self.answer_file_approval(request),
1387            _ => {}
1388        }
1389        self.flush_held();
1390    }
1391
1392    /// A hold the gate did not decide: logged, and queued as a `declined` event.
1393    fn declined(&self, reason: &str) -> GateVerdict {
1394        eprintln!("ai6: {reason}");
1395        self.push(AgentEvent {
1396            kind: "declined".to_owned(),
1397            text: Some(reason.to_owned()),
1398            data: None,
1399            limit: None,
1400            tools: Vec::new(),
1401            report: None,
1402        });
1403        GateVerdict::Hold(reason.to_owned())
1404    }
1405
1406    /// Answers a command approval with the green ink gate: `accept` unless the gate holds the
1407    /// command, then `decline`, and the reason is steered into the running turn so the Agent
1408    /// knows to ask for green ink. With a gate, these are declined without asking it: input to
1409    /// a running command and a request that names no command (the gate cannot see what they
1410    /// run), a request whose line was rebuilt from a terminal's rendering (`rebuilt`: its
1411    /// command may not be what Codex wrote), and one with no command execution item started
1412    /// earlier under its item id with the same command. A decline the gate did not decide is
1413    /// also logged and queued as an event of kind `declined`. Without a gate (no Cable
1414    /// endpoint) everything is accepted.
1415    fn answer_command_approval(&self, request: PermissionRequest) {
1416        let input = request
1417            .tool
1418            .input
1419            .as_ref()
1420            .and_then(|input| appserver::JsonObject::<CommandInput>::deserialize(input).ok())
1421            .map(|input| input.0)
1422            .unwrap_or_default();
1423        let command = input.command().filter(|command| !command.is_empty());
1424        let cwd = input.cwd().map(Path::new);
1425        let details = details_of(&request);
1426        let kind = details.kind();
1427        let started = details
1428            .item_id()
1429            .and_then(|item| self.started.lock().ok()?.get(item).cloned());
1430        let rebuilt = self.link.rebuilt.load(Ordering::Acquire);
1431        let unseen = |command: &str| started.as_deref() != Some(command);
1432        let verdict = match (&self.gate, kind, command) {
1433            (None, _, _) => GateVerdict::Allow,
1434            (Some(_), _, _) if rebuilt => self.declined(
1435                "Green ink: this approval request reached AI6 rebuilt from a terminal's \
1436                 rendering (a line it broke, or a control inside it), so its command may not be \
1437                 what was asked; it is declined. Run the command again.",
1438            ),
1439            (Some(_), kind, Some(command)) if kind != Some("writeStdin") && unseen(command) => self
1440                .declined(
1441                    "Green ink: this approval request names a command no command execution \
1442                     item started with before it; it is declined. Run the command again.",
1443                ),
1444            (Some(_), Some("writeStdin"), _) => GateVerdict::Hold(
1445                "Green ink: input to a running command is declined, because the gate cannot see \
1446                 what it runs; run the command with all its arguments instead."
1447                    .to_owned(),
1448            ),
1449            (Some(_), _, None) => GateVerdict::Hold(
1450                "Green ink: an approval request that names no command is declined; run the \
1451                 command with all its arguments instead."
1452                    .to_owned(),
1453            ),
1454            (Some(gate), _, Some(command)) => gate(command, cwd),
1455        };
1456        self.answer_approval(request, verdict);
1457    }
1458
1459    /// Answers a file change the way the Claude handler's gate treats an edit: green ink governs
1460    /// shell commands, so an edit inside the working directory is the Mission's own work and
1461    /// `accept`ed. Codex 0.164.0 applies what is accepted wherever it points, even from a
1462    /// read-only thread, so a gated thread is declined a path outside the working directory, a
1463    /// `grantRoot`, a request whose line was `rebuilt`, and one with no file change item started
1464    /// earlier under its item id, and so is a `desk` thread, gated or not. Otherwise, without a
1465    /// gate, everything is accepted.
1466    fn answer_file_approval(&self, request: PermissionRequest) {
1467        let details = details_of(&request);
1468        let paths = details
1469            .item_id()
1470            .and_then(|item| self.started_changes.lock().ok()?.get(item).cloned());
1471        let granted = details.grants_a_root();
1472        let judged = self.gate.is_some()
1473            || self
1474                .restricted
1475                .as_ref()
1476                .is_some_and(|allowed| allowed.asks_file_changes);
1477        let rebuilt = self.link.rebuilt.load(Ordering::Acquire);
1478        let root = &self.working_directory;
1479        let verdict = match (judged, paths) {
1480            (false, _) => GateVerdict::Allow,
1481            _ if rebuilt => self.declined(
1482                "Green ink: this file change request reached AI6 rebuilt from a terminal's \
1483                 rendering, so what it changes may not be what was asked; it is declined. Apply \
1484                 the change again.",
1485            ),
1486            _ if granted => self.declined(
1487                "Green ink: a file change may not widen where this thread writes; it is \
1488                 declined. Keep the change inside the working directory.",
1489            ),
1490            (true, Some(paths))
1491                if !paths.is_empty() && paths.iter().all(|path| inside(root, path)) =>
1492            {
1493                GateVerdict::Allow
1494            }
1495            (true, Some(_)) => self.declined(
1496                "Green ink: this file change reaches outside the working directory; it is \
1497                 declined. Keep the change inside the working directory.",
1498            ),
1499            (true, None) => self.declined(
1500                "Green ink: this approval request names a change no file change item started \
1501                 with before it; it is declined. Apply the change again.",
1502            ),
1503        };
1504        self.answer_approval(request, verdict);
1505    }
1506
1507    /// Writes the decision, and steers a held step's reason into the running turn.
1508    fn answer_approval(&self, request: PermissionRequest, verdict: GateVerdict) {
1509        let turn = details_of(&request).turn_id().map(str::to_owned);
1510        let chosen = match verdict {
1511            GateVerdict::Allow => coqui_acp_codex::parse::ALLOW_ONCE,
1512            GateVerdict::Hold(_) => coqui_acp_codex::parse::REJECT,
1513        };
1514        let _ = request
1515            .responder
1516            .answer(Outcome::Selected(chosen.to_owned()));
1517        if let GateVerdict::Hold(reason) = verdict
1518            && let Some(turn) = turn
1519            && let Some(session) = self
1520                .session
1521                .lock()
1522                .ok()
1523                .and_then(|session| session.upgrade())
1524        {
1525            let _ = session.steer(&turn, &[Content::Text(reason)]);
1526        }
1527    }
1528}
1529
1530/// A started Codex thread, as one of AI6's Runs.
1531struct CodexRun {
1532    session: Arc<AppServer>,
1533    shared: Arc<Shared>,
1534    /// The thread the Run is on: the one it opened with, or the last a clear opened.
1535    thread_id: Mutex<RunId>,
1536    /// How long the app server may take to answer a request of the Station's own.
1537    request_wait: Duration,
1538}
1539
1540/// The tool name a scripts thread's command executions are reported under.
1541const COMMAND_TOOL: &str = "exec_command";
1542
1543/// The type of the item an `item/started` notification starts.
1544fn started_item(message: &Message) -> Option<&str> {
1545    (message.method()? == "item/started")
1546        .then(|| message.item_kind())
1547        .flatten()
1548}
1549
1550/// What an approval request says of itself.
1551fn details_of(request: &PermissionRequest) -> Details {
1552    appserver::JsonObject::<Details>::deserialize(&request.details)
1553        .map(|details| details.0)
1554        .unwrap_or_default()
1555}
1556
1557/// What the app server wrote, as far as this handler reads it; a message that is no object says
1558/// nothing.
1559#[cfg(test)]
1560fn read_message(message: &Value) -> Message {
1561    if message.is_object() {
1562        Message::deserialize(message).unwrap_or_default()
1563    } else {
1564        Message::default()
1565    }
1566}
1567
1568/// The app-server's request to approve a command before it runs.
1569const COMMAND_APPROVAL: &str = "item/commandExecution/requestApproval";
1570
1571/// The app-server's request to approve a file change before it is applied.
1572const FILE_APPROVAL: &str = "item/fileChange/requestApproval";
1573
1574/// Thread items a restricted thread may produce besides calls to its own MCP servers: what it
1575/// is told and says, its reasoning and plan, and the thread's own bookkeeping.
1576const RESTRICTED_ITEMS: [&str; 7] = [
1577    "userMessage",
1578    "agentMessage",
1579    "reasoning",
1580    "plan",
1581    "contextCompaction",
1582    "enteredReviewMode",
1583    "exitedReviewMode",
1584];
1585
1586/// What `message` shows a restricted thread doing that it may not: any request from the server
1587/// but token refresh, attestation and, as `restriction` allows, a file change (approvals, tool
1588/// calls, questions, elicitation), or an `item/started` or `item/completed` of any other kind than
1589/// [`RESTRICTED_ITEMS`], an MCP call to one of its servers, and, as `restriction` allows, a command
1590/// execution or a file change.
1591fn forbidden_use(message: &Message, restriction: &Restriction) -> Option<String> {
1592    let servers = &restriction.servers;
1593    let method = message.method()?;
1594    if message.has_id() {
1595        if method == FILE_APPROVAL && restriction.asks_file_changes {
1596            return None;
1597        }
1598        return (!matches!(
1599            method,
1600            "account/chatgptAuthTokens/refresh" | "attestation/generate"
1601        ))
1602        .then(|| format!("a {method:?} request"));
1603    }
1604    if !matches!(method, "item/started" | "item/completed") {
1605        return None;
1606    }
1607    let item = message.item();
1608    let field = |read: fn(&Item) -> Option<&str>| item.and_then(read).unwrap_or("");
1609    match field(Item::kind) {
1610        kind if RESTRICTED_ITEMS.contains(&kind) => None,
1611        "commandExecution" if restriction.commands => None,
1612        "fileChange" if restriction.file_changes => None,
1613        "mcpToolCall" if servers.iter().any(|server| server == field(Item::server)) => None,
1614        "mcpToolCall" => Some(format!(
1615            "the tool {:?} of MCP server {:?}",
1616            field(Item::tool),
1617            field(Item::server)
1618        )),
1619        kind => Some(format!("a {kind:?} item")),
1620    }
1621}
1622
1623/// Whether `path` lies under `root`, as far as the file system resolves either: a link inside the
1624/// directory that points out of it counts as outside.
1625fn inside(root: &Path, path: &str) -> bool {
1626    let path = Path::new(path);
1627    let joined = if path.is_absolute() {
1628        path.to_path_buf()
1629    } else {
1630        root.join(path)
1631    };
1632    if joined
1633        .components()
1634        .any(|part| matches!(part, std::path::Component::ParentDir))
1635    {
1636        return false;
1637    }
1638    resolved(&joined).starts_with(resolved(root))
1639}
1640
1641/// `path` with its longest existing ancestor made canonical; what does not exist yet follows it.
1642fn resolved(path: &Path) -> std::path::PathBuf {
1643    let mut existing = path;
1644    let mut rest = Vec::new();
1645    loop {
1646        if let Ok(found) = existing.canonicalize() {
1647            return rest.iter().rev().fold(found, |path, part| path.join(part));
1648        }
1649        match (existing.parent(), existing.file_name()) {
1650            (Some(parent), Some(name)) => {
1651                rest.push(name);
1652                existing = parent;
1653            }
1654            _ => return path.to_path_buf(),
1655        }
1656    }
1657}
1658
1659/// The name of a Codex quota window by its length, else its position.
1660fn window_name(window: &Window, position: &str) -> String {
1661    match window.minutes() {
1662        Some(300) => "five_hour".to_owned(),
1663        Some(10_080) => "weekly".to_owned(),
1664        _ => position.to_owned(),
1665    }
1666}
1667
1668/// The bucket one Codex rate-limit window is: `usedPercent` as thousandths, `resetsAt` in Unix
1669/// seconds, exhausted once it is used up.
1670fn bucket_of(window: &Window, position: &str) -> Bucket {
1671    let mut bucket = Bucket::new(window_name(window, position));
1672    if let Some(percent) = window.used_percent() {
1673        bucket.limit = Some(1000);
1674        bucket.used = Some((percent * 10.0).round().clamp(0.0, 1000.0) as u64);
1675        if percent >= 100.0 {
1676            bucket.status = BucketStatus::Exhausted;
1677        }
1678    }
1679    bucket.refill = Refill::FixedWindow {
1680        length: window
1681            .unsigned_minutes()
1682            .map(|minutes| std::time::Duration::from_secs(minutes.saturating_mul(60))),
1683        resets_at: window.resets_at(),
1684    };
1685    bucket
1686}
1687
1688/// Every quota window an `account/rateLimits/updated` notification reports: `usedPercent`
1689/// as thousandths, `resetsAt` in Unix seconds.
1690fn decode_quota(message: &Message) -> Vec<Bucket> {
1691    if message.method() != Some("account/rateLimits/updated") {
1692        return Vec::new();
1693    }
1694    WINDOWS
1695        .iter()
1696        .filter_map(|position| Some(bucket_of(message.window(position)?, position)))
1697        .collect()
1698}
1699
1700/// The quota window an `account/rateLimits/updated` notification reports as used up.
1701///
1702/// The usage-limit error that follows does not always repeat the reset time, so the run
1703/// keeps the latest exhausted window as a hint.
1704fn exhausted_window(message: &Message) -> Option<LimitHit> {
1705    if message.method()? != "account/rateLimits/updated" {
1706        return None;
1707    }
1708    WINDOWS
1709        .iter()
1710        .filter_map(|position| {
1711            let window = message.window(position)?;
1712            (window.used_percent()? >= 100.0).then(|| {
1713                let mut hit = LimitHit::new(0);
1714                hit.resets_at = window.resets_at();
1715                hit.bucket = match window.minutes() {
1716                    Some(300 | 10_080) => Some(window_name(window, "")),
1717                    _ => None,
1718                };
1719                hit
1720            })
1721        })
1722        // Work resumes only when every exhausted window has reset.
1723        .max_by_key(|hit| hit.resets_at)
1724}
1725
1726/// Recognises the limit Codex reports on a failed turn: the driver's reading of the message
1727/// ([`coqui_acp_codex::limit_of_message`]), whose reset falls back on the exhausted window the account
1728/// last reported, with the wait the words state.
1729fn stated_limit(mut hit: LimitHit) -> (LimitHit, Option<String>) {
1730    let text = hit.text.clone();
1731    // A wait the message states (`try again in 90 seconds`) is the refusal's own.
1732    hit.retry_after = text
1733        .as_deref()
1734        .and_then(|words| infer_limit(words, &["limit"]))
1735        .and_then(|stated| stated.retry_after);
1736    (hit, text)
1737}
1738
1739/// The tokens one model request used, from a `thread/tokenUsage/updated` notification.
1740///
1741/// The notification also carries the thread's running total, which survives a resume, so
1742/// only `last` (the latest request) is read and reported as an addition. Codex reports no
1743/// cost. Its `inputTokens` include the cached ones, which are split out here.
1744fn decode_usage(message: &Message) -> Option<Spend> {
1745    if message.method()? != "thread/tokenUsage/updated" {
1746        return None;
1747    }
1748    let last = message.last_counts()?;
1749    let cached = last.cached_input();
1750    let mut spend = Spend::new("");
1751    spend.input = last.input().saturating_sub(cached);
1752    spend.output = last.output();
1753    spend.cache_read = cached;
1754    Some(spend)
1755}
1756
1757/// The tool an `item/started` notification begins: a web search, or an MCP or dynamic
1758/// tool call, named the way Claude Code names it (`WebSearch`, or the tool's own name).
1759fn decode_tools(message: &Message) -> Vec<String> {
1760    if message.method() != Some("item/started") {
1761        return Vec::new();
1762    }
1763    let item = message.item();
1764    let name = match message.item_kind() {
1765        Some("webSearch") => Some("WebSearch"),
1766        Some("mcpToolCall" | "dynamicToolCall") => item.and_then(Item::tool),
1767        _ => None,
1768    };
1769    name.map(str::to_owned).into_iter().collect()
1770}
1771
1772/// What a notification tells of the account's usage: one request's spend (an addition, which
1773/// the run turns into a running total) and the rate-limit windows.
1774fn decode_report(message: &Message) -> Option<UsageReport> {
1775    let spend = decode_usage(message);
1776    let buckets = decode_quota(message);
1777    if spend.is_none() && buckets.is_empty() {
1778        return None;
1779    }
1780    let mut report = UsageReport::new();
1781    report.spend = spend;
1782    report.buckets = buckets;
1783    Some(report)
1784}
1785
1786/// The portion of an app-server `error` notification whose strings may contain a gateway refusal.
1787#[derive(Deserialize)]
1788struct CapError {
1789    params: ai6::TokenCapRefusal,
1790}
1791
1792/// The driver's limit classification and the original payload AI6 attaches to its event.
1793struct DriverEvent {
1794    limit: Option<LimitHit>,
1795    cap_refusal: Option<String>,
1796    data: Option<Vec<u8>>,
1797}
1798
1799fn decode_event(message: &Message, driver: DriverEvent) -> Option<AgentEvent> {
1800    if !message.has_method() {
1801        return None;
1802    }
1803    let method = message.method().unwrap_or("event");
1804    if let Some((limit, text)) = driver.limit.map(stated_limit) {
1805        return Some(AgentEvent {
1806            kind: LIMIT_EVENT.to_owned(),
1807            text,
1808            data: driver.data,
1809            limit: Some(limit),
1810            tools: Vec::new(),
1811            report: None,
1812        });
1813    }
1814    // Codex retries a gateway's refusal while `willRetry` is set; a token-cap refusal is the same
1815    // every time, so the turn ends with the gateway's own words.
1816    if method == "error"
1817        && let Some(words) = driver.cap_refusal
1818    {
1819        return Some(AgentEvent {
1820            kind: "failed".to_owned(),
1821            text: Some(words),
1822            data: driver.data,
1823            limit: None,
1824            tools: Vec::new(),
1825            report: None,
1826        });
1827    }
1828    let kind = match method {
1829        "item/agentMessage/delta" => "text",
1830        "turn/completed" => "completed",
1831        "turn/failed" => "failed",
1832        _ => method,
1833    };
1834    Some(AgentEvent {
1835        kind: kind.to_string(),
1836        text: message.text().map(str::to_string),
1837        data: driver.data,
1838        limit: None,
1839        tools: decode_tools(message),
1840        report: decode_report(message),
1841    })
1842}
1843
1844/// [`decode_event`] of a message that is read here.
1845#[cfg(test)]
1846fn decoded(raw: &Value, hint: Option<&LimitHit>) -> Option<AgentEvent> {
1847    decode_event(&read_message(raw), driver_event(raw, hint))
1848}
1849
1850#[cfg(test)]
1851fn driver_event(raw: &Value, hint: Option<&LimitHit>) -> DriverEvent {
1852    DriverEvent {
1853        limit: coqui_acp_codex::limit_of_message(raw, hint),
1854        cap_refusal: CapError::deserialize(raw)
1855            .ok()
1856            .and_then(|error| error.params.into_text()),
1857        data: serde_json::to_vec(raw).ok(),
1858    }
1859}
1860
1861impl CodexRun {
1862    /// A clear: another thread on the same app server, which the session then prompts. What the
1863    /// old thread was counted at does not carry over. The clear is a turn of its own, ended at
1864    /// once.
1865    fn clear(&self) -> Result<(), ProviderError> {
1866        let opened = self
1867            .session
1868            .new_thread()
1869            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))?;
1870        let thread = RunId::try_from(opened)
1871            .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error))?;
1872        *lock(&self.shared.context)? = Context::default();
1873        *lock(&self.thread_id)? = thread.clone();
1874        let change = SessionChange {
1875            trigger: Some("manual".to_owned()),
1876            session_id: Some(thread.into()),
1877            ..SessionChange::default()
1878        };
1879        self.shared.push(change.event(ai6::CLEARED_EVENT, None));
1880        self.shared.push(AgentEvent {
1881            kind: "completed".to_owned(),
1882            text: None,
1883            data: None,
1884            limit: None,
1885            tools: Vec::new(),
1886            report: None,
1887        });
1888        Ok(())
1889    }
1890}
1891
1892impl AgentSession for CodexRun {
1893    fn session_id(&self) -> Result<Option<String>, ProviderError> {
1894        Ok(Some(lock(&self.thread_id)?.clone().into()))
1895    }
1896
1897    fn send_message(&self, message: AgentMessage) -> Result<(), ProviderError> {
1898        match SessionCommand::parse(&message.text)
1899            .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?
1900        {
1901            // `thread/compact/start` takes the thread and nothing else, so a focus is not
1902            // passed on: Codex writes its own summary.
1903            Some(SessionCommand::Compact { .. }) => {
1904                self.shared.compaction_asked();
1905                self.session
1906                    .request(
1907                        "thread/compact/start",
1908                        serde_json::to_value(compact_params(&self.session.thread()))
1909                            .unwrap_or_default(),
1910                        self.request_wait,
1911                    )
1912                    .map(drop)
1913                    .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))
1914            }
1915            Some(SessionCommand::Clear) => self.clear(),
1916            None => self
1917                .session
1918                .prompt(&[Content::Text(message.text)])
1919                .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error)),
1920        }
1921    }
1922
1923    fn next_event(&self, timeout_ms: i64) -> Result<Option<AgentEvent>, ProviderError> {
1924        let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
1925        let mut events = lock(&self.shared.events)?;
1926        loop {
1927            if let Some(event) = events.pop_front() {
1928                return Ok(Some(event));
1929            }
1930            let remaining = deadline.saturating_duration_since(Instant::now());
1931            if remaining.is_zero() {
1932                return Ok(None);
1933            }
1934            events = self
1935                .shared
1936                .arrived
1937                .wait_timeout(events, remaining)
1938                .map_err(|_| refuse(Status::GUATIAO_ERR_INTERNAL, "run lock was poisoned"))?
1939                .0;
1940        }
1941    }
1942
1943    fn interrupt(&self) -> Result<(), ProviderError> {
1944        self.session
1945            .interrupt()
1946            .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error))
1947    }
1948
1949    /// Ends the app server. The caller may remove the working directory next, which the app
1950    /// server holds until it has exited, so this waits for that.
1951    fn close(&self) -> Result<(), ProviderError> {
1952        self.session.close();
1953        Ok(())
1954    }
1955}
1956
1957/// What AI6 decided about the thread's settings.
1958#[derive(Clone, Copy)]
1959struct Mode<'a> {
1960    project_settings: bool,
1961    /// Set for answer-only and assistant threads alike: both run read-only and never ask.
1962    answer_only: bool,
1963    /// Set for a Mission's thread held to `desk` ([`held_to_desk`]).
1964    desk: bool,
1965    assistant: Option<&'a AssistantMode>,
1966    /// The model the thread asks for; what Codex offers it depends on the model.
1967    model: Option<&'a str>,
1968    /// The sandbox of an assistant's scripts, when they run in one.
1969    profile: Option<&'a sandbox::Profile>,
1970    /// The handler's configuration: the tool check's and the sandbox probe's bounds.
1971    config: &'a CodexConfig,
1972}
1973
1974/// The sandbox `assistant`'s scripts run in, `None` when they run in none.
1975fn scripts_profile(
1976    executable: &str,
1977    cwd: &str,
1978    environment: &std::collections::BTreeMap<String, String>,
1979    assistant: Option<&AssistantMode>,
1980) -> Option<sandbox::Profile> {
1981    assistant
1982        .filter(|mode| Scripts::of(Some(mode)) == Scripts::Sandboxed)
1983        .map(|mode| sandbox::Profile::new(executable, cwd, environment, mode))
1984}
1985
1986/// The app server's command line, and what a `warn` tool check found. A restricted (answer-only,
1987/// assistant or `desk`) app server starts only after its tool check ([`tools`]).
1988fn prepare(
1989    terminal: &Object<dyn AgentTerminal>,
1990    executable: &str,
1991    cwd: &str,
1992    environment: &std::collections::BTreeMap<String, String>,
1993    mode: Mode<'_>,
1994) -> Result<(Vec<String>, Option<String>), ProviderError> {
1995    let mut argv = if let Some(assistant) = mode.assistant {
1996        assistant_argv(executable, environment, assistant, mode.profile)?
1997    } else if mode.answer_only {
1998        answer_only_argv(executable)
1999    } else if mode.desk {
2000        desk_argv(executable, environment)
2001    } else {
2002        app_server_argv(executable, environment)
2003    };
2004    if !mode.project_settings || mode.answer_only {
2005        argv.extend(untrusted_project(cwd));
2006    }
2007    let scripts = Scripts::of(mode.assistant);
2008    let mut weakening = None;
2009    if mode.answer_only || mode.desk {
2010        let servers = if mode.desk {
2011            station_servers(environment)
2012        } else {
2013            mode.assistant
2014                .map(|assistant| {
2015                    assistant
2016                        .mcp_servers
2017                        .iter()
2018                        .map(|server| server.name.clone())
2019                        .collect::<Vec<_>>()
2020                })
2021                .unwrap_or_default()
2022        };
2023        let commands = scripts != Scripts::None;
2024        let checked = tools::Probe {
2025            terminal,
2026            executable,
2027            overrides: &argv[2..],
2028            cwd,
2029            environment,
2030            model: mode.model,
2031            servers: &servers,
2032            code_mode: commands || mode.desk,
2033            commands,
2034            config: mode.config,
2035            // `apply_patch` is nested in `exec` in remote-hands mode too, where a read-only sandbox
2036            // that never asks refuses it.
2037            files: mode.desk
2038                || restriction(mode.answer_only, mode.assistant, None, false)
2039                    .is_some_and(|allowed| allowed.file_changes),
2040        }
2041        .check()?;
2042        argv.extend(checked.overrides);
2043        weakening = checked.weakening;
2044    }
2045    if let Some(assistant) = mode.assistant.filter(|_| scripts != Scripts::None) {
2046        let admitted = format!(
2047            "Codex gives Moneypenny's thread functions.exec and functions.wait (code mode): her \
2048             scripts may run any command {}, not only {}",
2049            if scripts == Scripts::Sandboxed {
2050                "inside Codex's sandbox"
2051            } else {
2052                "with no sandbox"
2053            },
2054            assistant.interpreters.join(", ")
2055        );
2056        weakening = Some(match weakening {
2057            Some(found) => format!("{admitted}; {found}"),
2058            None => admitted,
2059        });
2060    }
2061    Ok((argv, weakening))
2062}
2063
2064/// The app server of a Mission, with AI6's servers its environment names, their tools approved
2065/// without asking: Codex otherwise asks about each MCP call, which fails it under approval `never`
2066/// and leaves it unanswered under `untrusted`. The Station checks what those tools do. In
2067/// remote-hands mode it has no command tool: the harness runs on the Station, where nothing it does
2068/// is to land, and Codex's read-only sandbox lets a command read any file there (Codex 0.164.0 on
2069/// Linux).
2070fn app_server_argv(
2071    executable: &str,
2072    environment: &std::collections::BTreeMap<String, String>,
2073) -> Vec<String> {
2074    let mut argv = vec![executable.to_string(), "app-server".to_string()];
2075    for (server, prefix) in [
2076        ("ai6-cables", "AI6_CABLE_MCP"),
2077        ("ai6-theater", "AI6_THEATER_MCP"),
2078    ] {
2079        if let Some(url) = environment.get(&format!("{prefix}_URL"))
2080            && environment.contains_key(&format!("{prefix}_TOKEN"))
2081        {
2082            argv.extend([
2083                "-c".to_owned(),
2084                format!("mcp_servers.{server}.url=\"{url}\""),
2085                "-c".to_owned(),
2086                format!("mcp_servers.{server}.bearer_token_env_var=\"{prefix}_TOKEN\""),
2087                "-c".to_owned(),
2088                format!("mcp_servers.{server}.default_tools_approval_mode=\"approve\""),
2089            ]);
2090            if server == "ai6-theater"
2091                && let Some(seconds) = theater_tool_timeout_secs(environment)
2092            {
2093                argv.extend([
2094                    "-c".to_owned(),
2095                    format!("mcp_servers.{server}.tool_timeout_sec={seconds}"),
2096                ]);
2097            }
2098        }
2099    }
2100    if is_remote_hands(environment) && native_environment(environment).is_none() {
2101        argv.extend(["-c".to_owned(), "features.shell_tool=false".to_owned()]);
2102    }
2103    // A trial has no web search: its network is the sandbox's.
2104    if environment.contains_key("AI6_TRIAL_MAX_TURNS") {
2105        argv.extend(["-c".to_owned(), "web_search=\"disabled\"".to_owned()]);
2106    }
2107    argv
2108}
2109
2110/// Seconds Codex's MCP client waits for a Theater tool call (its default is 60 s, which would end a
2111/// longer `theater_run`): the Station's `AI6_THEATER_MCP_TIMEOUT_MS`, rounded up.
2112fn theater_tool_timeout_secs(
2113    environment: &std::collections::BTreeMap<String, String>,
2114) -> Option<u64> {
2115    let millis: u64 = environment
2116        .get("AI6_THEATER_MCP_TIMEOUT_MS")?
2117        .parse()
2118        .ok()?;
2119    Some(millis.div_ceil(1000).max(1))
2120}
2121
2122/// The Theater tools a `desk` thread may not call: one runs a command, the other writes any path on
2123/// the Theater. Codex 0.164.0 leaves a tool named here out of `exec`.
2124const THEATER_TOOLS_OFF: &str = "mcp_servers.ai6-theater.disabled_tools=[\"exec\",\"fs_write\",\
2125                                 \"edit\",\"apply_patch\"]";
2126
2127/// The app server of a Mission's thread held to `desk`: AI6's servers, and no built-in tool
2128/// ([`NO_BUILT_IN_TOOLS`]). With `features.shell_tool` off Codex 0.164.0 offers `functions.exec`
2129/// and `functions.wait` with no command tool nested, and `exec`'s JavaScript has no file system,
2130/// process or network of its own; the tool check ([`tools`]) confirms what a release offers.
2131/// That leaves the thread nothing that reads a file, since Codex reads through commands.
2132fn desk_argv(
2133    executable: &str,
2134    environment: &std::collections::BTreeMap<String, String>,
2135) -> Vec<String> {
2136    let mut argv = app_server_argv(executable, environment);
2137    argv.extend(no_built_in_tools(false));
2138    if is_remote_hands(environment) {
2139        argv.extend(["-c".to_owned(), THEATER_TOOLS_OFF.to_owned()]);
2140    }
2141    argv
2142}
2143
2144/// The settings that leave an answer-only or assistant thread no built-in tool that reads,
2145/// runs or reaches anything: no command execution (`features.shell_tool`; Codex ignores a
2146/// user's `features.unified_exec = false`), no web search, no sub-agents
2147/// (`features.multi_agent`, `agents.enabled`), no app connectors, a skills catalog too small to
2148/// list one (`skills.max_context_tokens`, which takes no 0), and no questions to the user. Names
2149/// and meanings from the Codex configuration reference
2150/// (learn.chatgpt.com/docs/config-file/config-reference), but for
2151/// `tools.experimental_request_user_input`: switched off, it removes `request_user_input` and
2152/// `request_user_input_async`, which no feature does (Codex 0.164.0). Every other
2153/// feature Codex enables, and every MCP server of the user's, is switched off by the tool check
2154/// ([`tools`]), and the read-only sandbox and approval policy `never` stay as a further line.
2155const NO_BUILT_IN_TOOLS: [&str; 7] = [
2156    "features.shell_tool=false",
2157    "web_search=\"disabled\"",
2158    "features.multi_agent=false",
2159    "agents.enabled=false",
2160    "features.apps=false",
2161    "skills.max_context_tokens=1",
2162    "tools.experimental_request_user_input={enabled=false}",
2163];
2164
2165/// `-c` overrides for [`NO_BUILT_IN_TOOLS`]; with `shell`, the command tools stay on.
2166fn no_built_in_tools(shell: bool) -> Vec<String> {
2167    NO_BUILT_IN_TOOLS
2168        .iter()
2169        .filter(|setting| !(shell && setting.starts_with("features.shell_tool=")))
2170        .flat_map(|setting| ["-c".to_owned(), (*setting).to_owned()])
2171        .collect()
2172}
2173
2174/// The app server of an answer-only thread: an empty `mcp_servers` table, AI6's servers left
2175/// out, and no built-in tool ([`NO_BUILT_IN_TOOLS`]). Codex merges the table into the user's
2176/// own servers, which the tool check switches off by name ([`tools`]). The checkout's own
2177/// `AGENTS.md` is no input (`project_doc_max_bytes=0`); Codex 0.166.0 has no setting that keeps its
2178/// home's own instructions file out, which `codex debug prompt-input` still renders.
2179fn answer_only_argv(executable: &str) -> Vec<String> {
2180    let mut argv = vec![
2181        executable.to_owned(),
2182        "app-server".to_owned(),
2183        "-c".to_owned(),
2184        "mcp_servers={}".to_owned(),
2185    ];
2186    argv.extend(no_built_in_tools(false));
2187    argv.extend(["-c".to_owned(), "project_doc_max_bytes=0".to_owned()]);
2188    argv
2189}
2190
2191/// The app server of an assistant thread, built from its mode's parts: `mcp_servers` set to
2192/// one inline table holding exactly the mode's servers, which Codex merges into the user's own
2193/// (the tool check switches those off by name, [`tools`]), each with its URL, the name of the
2194/// variable holding its bearer token and its tools approved without asking (under approval
2195/// `never` Codex 0.164.0 fails every MCP call it would ask about); no built-in tool
2196/// ([`NO_BUILT_IN_TOOLS`]); and no project instructions file (`project_doc_max_bytes=0`), since
2197/// its standing context is the mode's `context_file`, which the thread gets as developer
2198/// instructions.
2199///
2200/// With interpreters the command tools stay on and the thread's commands run under `profile`
2201/// ([`sandbox::Profile`]): the mode's `files` directories writable, nothing outside the working
2202/// directory readable, no network; unsandboxed, under none. Without interpreters `exec` is not
2203/// offered, so `files` gives no tool to write with. Skills are refused: Codex keeps no list of
2204/// allowed skills.
2205fn assistant_argv(
2206    executable: &str,
2207    environment: &std::collections::BTreeMap<String, String>,
2208    mode: &AssistantMode,
2209    profile: Option<&sandbox::Profile>,
2210) -> Result<Vec<String>, ProviderError> {
2211    mode.validate()
2212        .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
2213    if !mode.skills.is_empty() {
2214        return Err(refuse(Status::GUATIAO_ERR_UNSUPPORTED, NO_SKILL_LIST));
2215    }
2216    let scripts = Scripts::of(Some(mode));
2217    let mut servers = Vec::new();
2218    for server in &mode.mcp_servers {
2219        let prefix = &server.env_prefix;
2220        let (Some(url), true) = (
2221            environment.get(&format!("{prefix}_URL")),
2222            environment.contains_key(&format!("{prefix}_TOKEN")),
2223        ) else {
2224            return Err(refuse(
2225                Status::GUATIAO_ERR_BAD_VALUE,
2226                format!(
2227                    "the environment carries no URL and token for MCP server {:?}",
2228                    server.name
2229                ),
2230            ));
2231        };
2232        // A JSON string is a valid TOML basic string.
2233        let url = serde_json::to_string(url).map_err(internal)?;
2234        let token = serde_json::to_string(&format!("{prefix}_TOKEN")).map_err(internal)?;
2235        servers.push(format!(
2236            "{}={{url={url},bearer_token_env_var={token},\
2237             default_tools_approval_mode=\"approve\"}}",
2238            server.name
2239        ));
2240    }
2241    let mut argv = vec![
2242        executable.to_owned(),
2243        "app-server".to_owned(),
2244        "-c".to_owned(),
2245        format!("mcp_servers={{{}}}", servers.join(",")),
2246    ];
2247    argv.extend(no_built_in_tools(scripts != Scripts::None));
2248    argv.extend(["-c".to_owned(), "project_doc_max_bytes=0".to_owned()]);
2249    if let Some(profile) = profile {
2250        argv.extend(profile.overrides());
2251    }
2252    Ok(argv)
2253}
2254
2255/// Marks the working directory an untrusted project for this process, so Codex skips its
2256/// project `.codex/` layer: project config, hooks and rules. `projects` is set as one inline
2257/// table because a path holds dots, which a dotted `-c` key would split; it replaces the
2258/// user's own `projects` table for this process only.
2259fn untrusted_project(cwd: &str) -> [String; 2] {
2260    let path = serde_json::to_string(cwd).unwrap_or_else(|_| "\"\"".to_owned());
2261    [
2262        "-c".to_owned(),
2263        format!("projects={{{path}={{trust_level=\"untrusted\"}}}}"),
2264    ]
2265}
2266
2267/// Whether the Station serves a Theater's tools, which is remote-hands mode.
2268fn is_remote_hands(environment: &std::collections::BTreeMap<String, String>) -> bool {
2269    environment.contains_key("AI6_THEATER_MCP_URL")
2270        && environment.contains_key("AI6_THEATER_MCP_TOKEN")
2271}
2272
2273/// The Theater as Codex's own environment backend, when the Station serves one: an exec-server it registers with
2274/// `environment/add`, so every tool Codex has (shell, patches, file reads) acts there, whatever tool it adds later.
2275fn native_environment(
2276    environment: &std::collections::BTreeMap<String, String>,
2277) -> Option<coqui_acp_codex::environment::CodexEnvironment> {
2278    Some(coqui_acp_codex::environment::CodexEnvironment::new(
2279        environment.get("AI6_THEATER_EXEC_ID")?.clone(),
2280        environment.get("AI6_THEATER_EXEC_URL")?.clone(),
2281        environment.get("AI6_THEATER_EXEC_TOKEN")?.clone(),
2282        environment.get("AI6_THEATER_EXEC_CWD")?.clone(),
2283    ))
2284}
2285
2286/// Refuses to resume a thread, or start one from a transcript, whose commands are to run in the
2287/// Theater's own environment (`restricted` threads have none): Codex is handed that environment
2288/// only as a thread starts new, so a resumed thread falls back to the Station's host and would
2289/// run its shell there.
2290fn refuse_resume_in_theater(
2291    environment: &std::collections::BTreeMap<String, String>,
2292    restricted: bool,
2293) -> Result<(), ProviderError> {
2294    if !restricted && native_environment(environment).is_some() {
2295        return Err(refuse(
2296            Status::GUATIAO_ERR_UNSUPPORTED,
2297            "Codex does not carry a Theater's environment into a resumed thread, so it would run \
2298             its commands on the Station: start a new thread instead",
2299        ));
2300    }
2301    Ok(())
2302}
2303
2304/// In remote-hands mode the Theater tools are how a thread changes anything. Its command tool is off
2305/// ([`app_server_argv`]), and its read-only sandbox that asks nothing refuses Codex's patches, so
2306/// no work lands on the Station.
2307fn restrict_to_remote_hands(params: &mut ThreadPolicy) {
2308    params.sandbox = Some("read-only");
2309    params.approval_policy = Some("never");
2310}
2311
2312/// A thread that only reads its prompt and answers: its app server has no built-in tool
2313/// ([`NO_BUILT_IN_TOOLS`]), and the thread also runs in the read-only sandbox (no writes;
2314/// Codex gives that sandbox no network), never asks, and has web search off.
2315fn restrict_to_answer_only(params: &mut ThreadPolicy) {
2316    restrict_to_remote_hands(params);
2317    params.config = Some(ThreadConfig {
2318        web_search: "disabled",
2319    });
2320}
2321
2322fn lock<T>(mutex: &Mutex<T>) -> Result<std::sync::MutexGuard<'_, T>, ProviderError> {
2323    mutex
2324        .lock()
2325        .map_err(|_| refuse(Status::GUATIAO_ERR_INTERNAL, "run lock was poisoned"))
2326}
2327
2328fn internal(error: impl std::fmt::Display) -> ProviderError {
2329    refuse(Status::GUATIAO_ERR_INTERNAL, error)
2330}
2331
2332fn refuse(status: Status, error: impl std::fmt::Display) -> ProviderError {
2333    ProviderError::new(status, &error.to_string())
2334}
2335
2336#[cfg(test)]
2337mod tests {
2338    use super::*;
2339    use ai6::LimitKind;
2340    use ai6::directorates::q::terminal::{
2341        ExitInfo, READ_TIMED_OUT, STREAM_COLS, Spec, TerminalRun,
2342    };
2343    use ai6::guatiao::{FromValue, ToValue};
2344    use std::collections::BTreeMap;
2345
2346    #[test]
2347    fn the_app_server_never_resumes_into_an_unconfirmed_environment() {
2348        let settings = session_settings(&CodexConfig::default());
2349        assert!(!settings.resume_unconfirmed_environment);
2350    }
2351
2352    #[test]
2353    fn a_trial_has_web_search_off() {
2354        let trial =
2355            std::collections::BTreeMap::from([("AI6_TRIAL_MAX_TURNS".to_owned(), "2".to_owned())]);
2356        let off = "web_search=\"disabled\"".to_owned();
2357        assert!(app_server_argv("codex", &trial).contains(&off));
2358        assert!(!app_server_argv("codex", &std::collections::BTreeMap::new()).contains(&off));
2359    }
2360
2361    #[test]
2362    fn a_threads_rollout_is_found_under_codex_home() {
2363        let home = tempfile::tempdir().unwrap();
2364        let day = home.path().join("runs").join("2026").join("11").join("04");
2365        std::fs::create_dir_all(&day).unwrap();
2366        let file = day.join("rollout-2026-11-04T10-00-00-0195-thread.jsonl");
2367        std::fs::write(&file, "{}\n").unwrap();
2368        let query = |thread: &str| RunRecordQuery {
2369            run_id: thread.to_owned(),
2370            working_directory: "/work".to_owned(),
2371            environment: BTreeMap::from([(
2372                "CODEX_HOME".to_owned(),
2373                home.path().to_string_lossy().into_owned(),
2374            )]),
2375        };
2376        let found = codex_record(&query("0195-thread")).unwrap();
2377        assert_eq!(std::path::PathBuf::from(found.path), file);
2378        assert_eq!(found.format, RECORD_FORMAT);
2379        assert!(codex_record(&query("other")).is_none());
2380        assert!(codex_record(&query("../0195-thread")).is_none());
2381    }
2382
2383    #[test]
2384    fn codexs_usage_is_read_with_no_turn_and_a_codex_that_cannot_run_is_an_error_not_an_empty_report()
2385     {
2386        let config = CodexConfig {
2387            executable: "ai6-no-such-codex".to_owned(),
2388            ..CodexConfig::default()
2389        };
2390        let handler = CodexHandler::try_from(config).unwrap();
2391        let support = handler.usage_support().unwrap();
2392        assert!(!support.needs_turn && !support.needs_session);
2393        assert_eq!(support.sources, [UsageSource::Reported]);
2394        assert!(handler.usage(Default::default()).is_err());
2395    }
2396
2397    #[test]
2398    fn the_models_codex_lists_are_read_from_model_list_and_hidden_ones_are_left_out() {
2399        let answer = json!({"id": 2, "result": {"data": [
2400            {"id": "gpt-6.1-sol", "model": "gpt-6.1-sol", "displayName": "GPT-6.1-Sol",
2401             "description": "Latest workhorse model", "hidden": false, "isDefault": true,
2402             "supportedReasoningEfforts": [
2403                 {"reasoningEffort": "low", "description": "Fast"},
2404                 {"reasoningEffort": "high", "description": "Deep"}]},
2405            {"id": "internal", "model": "internal", "hidden": true},
2406            {"id": "gpt-6-astra", "displayName": "Astra",
2407             "supportedReasoningEfforts": [{"reasoningEffort": "high"}, {"reasoningEffort": "xhigh"}]}
2408        ]}});
2409        let models = models_of(&Reply::deserialize(answer).unwrap());
2410        let listed = models.value().expect("the models are known");
2411        let ids: Vec<_> = listed.iter().map(|model| model.id.as_str()).collect();
2412        assert_eq!(ids, ["gpt-6.1-sol", "gpt-6-astra"]);
2413        assert_eq!(listed[0].name.as_deref(), Some("GPT-6.1-Sol"));
2414        assert_eq!(listed[0].efforts, ["low", "high"]);
2415        let efforts = efforts_of(&models);
2416        let ids: Vec<_> = efforts
2417            .value()
2418            .unwrap()
2419            .iter()
2420            .map(|choice| choice.id.as_str())
2421            .collect();
2422        assert_eq!(
2423            ids,
2424            ["low", "high", "xhigh"],
2425            "each once, in order of appearance"
2426        );
2427    }
2428
2429    #[test]
2430    fn an_answer_without_data_is_unknown_never_empty() {
2431        let answer = json!({"id": 2, "error": {"code": -32601, "message": "no such method"}});
2432        let models = models_of(&Reply::deserialize(answer).unwrap());
2433        assert!(
2434            matches!(&models, Answer::Unknown { reason } if !reason.is_empty()),
2435            "{models:?}"
2436        );
2437        assert!(matches!(efforts_of(&models), Answer::Unknown { .. }));
2438    }
2439
2440    #[test]
2441    fn the_threads_codex_lists_are_sessions_and_a_next_page_says_the_list_is_cut() {
2442        let answer = json!({"id": 3, "result": {"data": [
2443            {"id": "0195-a", "preview": "Fix the leak", "cwd": "/work", "updatedAt": 1770000000},
2444            {"id": "0195-b", "name": "Named", "preview": "ignored", "updatedAt": "2026-11-01T10:00:00Z"},
2445            {"preview": "no id: not a session"}
2446        ], "nextCursor": "more"}});
2447        let sessions = sessions_of(&ThreadList::deserialize(answer).unwrap(), Some("0.166.0"));
2448        let list = sessions.value().expect("the threads are known");
2449        assert_eq!(list.sessions.len(), 2);
2450        assert_eq!(list.sessions[0].title.as_deref(), Some("Fix the leak"));
2451        assert_eq!(list.sessions[0].directory.as_deref(), Some("/work"));
2452        assert_eq!(list.sessions[0].updated_at.as_deref(), Some("1770000000"));
2453        assert_eq!(list.sessions[1].title.as_deref(), Some("Named"));
2454        assert!(list.incomplete.is_some());
2455
2456        let answer = json!({"id": 3, "result": {"data": [], "nextCursor": null}});
2457        let whole = sessions_of(&ThreadList::deserialize(answer).unwrap(), None);
2458        assert_eq!(whole.value().unwrap().incomplete, None);
2459    }
2460
2461    #[test]
2462    fn a_codex_that_does_not_list_threads_is_unknown_with_its_version() {
2463        let refused =
2464            json!({"error": {"code": -32600, "message": "unknown variant `thread/list`"}});
2465        let sessions = sessions_of(&ThreadList::deserialize(refused).unwrap(), Some("0.100.0"));
2466        match sessions {
2467            Answer::Unknown { reason } => {
2468                assert!(reason.contains("Codex 0.100.0"), "{reason}");
2469                assert!(reason.contains("unknown variant"), "{reason}");
2470            }
2471            other => panic!("{other:?}"),
2472        }
2473    }
2474
2475    #[test]
2476    fn what_codex_has_no_such_thing_as_is_declared_and_its_modes_are_the_adapters() {
2477        let options = start_options_of(
2478            Answer::known(vec![ModelInfo {
2479                id: "m".to_owned(),
2480                name: None,
2481                description: None,
2482                efforts: vec!["low".to_owned()],
2483            }]),
2484            Answer::NotSupported,
2485        );
2486        assert_eq!(options.config, Answer::NotSupported);
2487        let modes: Vec<_> = options
2488            .modes
2489            .value()
2490            .unwrap()
2491            .iter()
2492            .map(|choice| choice.id.as_str())
2493            .collect();
2494        assert_eq!(modes, ["manual", "accept_edits", "auto", "plan", "bypass"]);
2495        assert_eq!(options.sessions, Answer::NotSupported);
2496        assert!(options.efforts.is_known());
2497    }
2498
2499    #[test]
2500    fn a_codex_that_cannot_run_has_unknown_models_efforts_and_sessions_and_its_declared_modes() {
2501        let config = CodexConfig {
2502            executable: "ai6-no-such-codex".to_owned(),
2503            ..CodexConfig::default()
2504        };
2505        let options = CodexHandler::try_from(config)
2506            .unwrap()
2507            .start_options(Default::default())
2508            .unwrap();
2509        assert!(
2510            matches!(options.models, Answer::Unknown { .. }),
2511            "{options:?}"
2512        );
2513        assert!(matches!(options.efforts, Answer::Unknown { .. }));
2514        assert!(matches!(options.sessions, Answer::Unknown { .. }));
2515        assert!(options.modes.is_known());
2516        assert_eq!(options.config, Answer::NotSupported);
2517    }
2518
2519    /// Against the real Codex on this machine, with an empty `CODEX_HOME`, no login and no
2520    /// network: the app server answers `model/list` from its own catalog. Run with
2521    /// `AI6_TEST_LIVE_HARNESSES=1`.
2522    #[test]
2523    #[ignore = "needs Codex installed; set AI6_TEST_LIVE_HARNESSES=1 and run with --ignored"]
2524    fn live_codex_lists_models_with_no_login_and_no_turn() {
2525        assert!(
2526            std::env::var_os("AI6_TEST_LIVE_HARNESSES").is_some(),
2527            "set AI6_TEST_LIVE_HARNESSES=1"
2528        );
2529        let home = tempfile::tempdir().unwrap();
2530        let environment = BTreeMap::from([
2531            ("PATH".to_owned(), std::env::var("PATH").unwrap_or_default()),
2532            (
2533                "SYSTEMROOT".to_owned(),
2534                std::env::var("SYSTEMROOT").unwrap_or_default(),
2535            ),
2536            ("HOME".to_owned(), home.path().display().to_string()),
2537            ("USERPROFILE".to_owned(), home.path().display().to_string()),
2538            ("APPDATA".to_owned(), home.path().display().to_string()),
2539            ("LOCALAPPDATA".to_owned(), home.path().display().to_string()),
2540            (
2541                "CODEX_HOME".to_owned(),
2542                home.path().join(".codex").display().to_string(),
2543            ),
2544            ("HTTPS_PROXY".to_owned(), "http://127.0.0.1:9".to_owned()),
2545        ]);
2546        std::fs::create_dir_all(home.path().join(".codex")).unwrap();
2547        let handler = CodexHandler::try_from(CodexConfig::default()).unwrap();
2548        let options = handler.start_options(environment).unwrap();
2549        let models = options
2550            .models
2551            .value()
2552            .unwrap_or_else(|| panic!("{options:?}"));
2553        assert!(!models.is_empty(), "{options:?}");
2554        assert!(
2555            options.sessions.is_known(),
2556            "thread/list answers with no login: {options:?}"
2557        );
2558    }
2559    use std::io::{BufRead, BufReader, Read, Write};
2560    use std::process::{Child, ChildStdin, Command, Stdio};
2561    use std::sync::Arc;
2562    use std::sync::mpsc::{self, Receiver};
2563    use std::thread;
2564    use std::time::{Duration, Instant};
2565
2566    #[derive(Clone)]
2567    struct ProcessTerminal {
2568        specs: Arc<Mutex<Vec<Spec>>>,
2569        /// The command word of each command run through `spawn_private`.
2570        private: Arc<Mutex<Vec<String>>>,
2571    }
2572
2573    impl ProcessTerminal {
2574        fn new() -> Self {
2575            Self {
2576                specs: Arc::new(Mutex::new(Vec::new())),
2577                private: Arc::new(Mutex::new(Vec::new())),
2578            }
2579        }
2580    }
2581
2582    impl AgentTerminal for ProcessTerminal {
2583        fn spawn_private(
2584            &self,
2585            value: &ai6::guatiao::Value,
2586        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
2587            let spec = Spec::from_value(value).map_err(internal)?;
2588            self.private.lock().unwrap().push(spec.argv[1].clone());
2589            self.spawn(value)
2590        }
2591
2592        fn spawn(
2593            &self,
2594            value: &ai6::guatiao::Value,
2595        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
2596            let spec = Spec::from_value(value).map_err(internal)?;
2597            self.specs.lock().unwrap().push(spec.clone());
2598
2599            let mut child = Command::new(std::env::current_exe().map_err(internal)?)
2600                .args(["--exact", "tests::fake_codex_child", "--nocapture"])
2601                .env("AI6_FAKE_CODEX_CHILD", "1")
2602                .env("AI6_FAKE_CODEX_ARGV", spec.argv[1..].join("\u{1f}"))
2603                .envs(spec.env.unwrap_or_default())
2604                .stdin(Stdio::piped())
2605                .stdout(Stdio::piped())
2606                .stderr(Stdio::null())
2607                .spawn()
2608                .map_err(internal)?;
2609            let stdin = child.stdin.take().ok_or_else(|| {
2610                refuse(
2611                    Status::GUATIAO_ERR_INTERNAL,
2612                    "fake Codex stdin is unavailable",
2613                )
2614            })?;
2615            let stdout = child.stdout.take().ok_or_else(|| {
2616                refuse(
2617                    Status::GUATIAO_ERR_INTERNAL,
2618                    "fake Codex stdout is unavailable",
2619                )
2620            })?;
2621            let (sender, receiver) = mpsc::channel();
2622            // The tool check's commands get everything, libtest's lines included.
2623            let json_only = spec
2624                .argv
2625                .get(1)
2626                .is_some_and(|command| command == "app-server");
2627            thread::spawn(move || forward_json_lines(stdout, sender, json_only));
2628
2629            Ok(ProcessTerminalRun {
2630                child: Mutex::new(child),
2631                stdin: Mutex::new(stdin),
2632                receiver: Mutex::new(receiver),
2633                pending: Mutex::new(std::collections::VecDeque::new()),
2634            }
2635            .into_object())
2636        }
2637    }
2638
2639    /// Marks where a fake tool-check command's own output starts and ends.
2640    const FAKE_BEGIN: &str = "AI6-FAKE-OUTPUT-BEGIN";
2641    const FAKE_END: &str = "AI6-FAKE-OUTPUT-END";
2642
2643    /// Hands over the fake app server's JSON lines, or with `json_only` false a tool-check
2644    /// command's output between [`FAKE_BEGIN`] and [`FAKE_END`].
2645    fn forward_json_lines(mut stdout: impl Read, sender: mpsc::Sender<Vec<u8>>, json_only: bool) {
2646        let mut reader = BufReader::new(&mut stdout);
2647        let mut line = Vec::new();
2648        let mut inside = false;
2649        loop {
2650            line.clear();
2651            match reader.read_until(b'\n', &mut line) {
2652                Ok(0) | Err(_) => return,
2653                Ok(_) if !json_only => {
2654                    let text = String::from_utf8_lossy(&line);
2655                    if text.trim() == FAKE_BEGIN {
2656                        inside = true;
2657                    } else if text.trim() == FAKE_END
2658                        || (inside && sender.send(line.clone()).is_err())
2659                    {
2660                        return;
2661                    }
2662                }
2663                Ok(_) if serde_json::from_slice::<Value>(&line).is_ok() => {
2664                    if sender.send(line.clone()).is_err() {
2665                        return;
2666                    }
2667                }
2668                Ok(_) => {}
2669            }
2670        }
2671    }
2672
2673    struct ProcessTerminalRun {
2674        child: Mutex<Child>,
2675        stdin: Mutex<ChildStdin>,
2676        receiver: Mutex<Receiver<Vec<u8>>>,
2677        pending: Mutex<std::collections::VecDeque<u8>>,
2678    }
2679
2680    impl TerminalRun for ProcessTerminalRun {
2681        fn pid(&self) -> i64 {
2682            i64::from(self.child.lock().unwrap().id())
2683        }
2684
2685        fn read(&self, dst: &mut [u8], timeout_ms: i64) -> Result<i64, ProviderError> {
2686            let mut pending = self.pending.lock().unwrap();
2687            if pending.is_empty() {
2688                match self
2689                    .receiver
2690                    .lock()
2691                    .unwrap()
2692                    .recv_timeout(Duration::from_millis(timeout_ms.max(0) as u64))
2693                {
2694                    Ok(bytes) => pending.extend(bytes),
2695                    Err(mpsc::RecvTimeoutError::Timeout) => return Ok(READ_TIMED_OUT),
2696                    Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(0),
2697                }
2698            }
2699            let count = dst.len().min(pending.len());
2700            for byte in &mut dst[..count] {
2701                *byte = pending
2702                    .pop_front()
2703                    .expect("count is bounded by pending bytes");
2704            }
2705            Ok(count as i64)
2706        }
2707
2708        fn write(&self, data: &[u8]) -> Result<(), ProviderError> {
2709            self.stdin.lock().unwrap().write_all(data).map_err(internal)
2710        }
2711
2712        fn resize(&self, _rows: i64, _cols: i64) -> Result<(), ProviderError> {
2713            Ok(())
2714        }
2715
2716        fn kill(&self) -> Result<(), ProviderError> {
2717            let mut child = self.child.lock().unwrap();
2718            match child.kill() {
2719                Ok(()) => child.wait().map(|_| ()).map_err(internal),
2720                Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => Ok(()),
2721                Err(error) => Err(internal(error)),
2722            }
2723        }
2724
2725        fn exit_status(&self, _timeout_ms: i64) -> Result<ai6::guatiao::Value, ProviderError> {
2726            Err(refuse(
2727                Status::GUATIAO_ERR_INTERNAL,
2728                "process fixture does not expose exit metadata",
2729            ))
2730        }
2731    }
2732
2733    #[test]
2734    fn fake_codex_child() {
2735        if std::env::var_os("AI6_FAKE_CODEX_CHILD").is_none() {
2736            return;
2737        }
2738        let argv = std::env::var("AI6_FAKE_CODEX_ARGV").unwrap_or_default();
2739        let argv = argv.split('\u{1f}').collect::<Vec<_>>();
2740        let stdout = std::io::stdout();
2741        let mut stdout = stdout.lock();
2742        // The tool check's commands, as Codex 0.164.0 answers them, between markers that
2743        // keep libtest's own lines out of what the fake terminal hands over.
2744        let answer = |stdout: &mut std::io::StdoutLock<'_>, output: &str| -> ! {
2745            writeln!(stdout, "\n{FAKE_BEGIN}\n{output}\n{FAKE_END}").unwrap();
2746            stdout.flush().unwrap();
2747            std::process::exit(0)
2748        };
2749        match argv.first().copied() {
2750            Some("--version") => answer(&mut stdout, "codex-cli 0.164.0"),
2751            Some("features") => {
2752                let output = std::env::var("CODEX_FIXTURE_FEATURES").unwrap_or_else(|_| {
2753                    [
2754                        "code_mode_host                           stable             true",
2755                        "memories                                 stable             false",
2756                        "secret_auth_storage                      stable             true",
2757                        "tool_suggest                             under development  true",
2758                    ]
2759                    .join("\n")
2760                });
2761                answer(&mut stdout, &output)
2762            }
2763            Some("mcp") => {
2764                let output =
2765                    std::env::var("CODEX_FIXTURE_MCP_LIST").unwrap_or_else(|_| "[]".to_owned());
2766                answer(&mut stdout, &output)
2767            }
2768            Some("debug") => {
2769                let output = std::env::var("CODEX_FIXTURE_PROMPT_INPUT").unwrap_or_else(|_| {
2770                    let servers = argv
2771                        .iter()
2772                        .any(|argument| argument.starts_with("mcp_servers={moneypenny="));
2773                    if servers {
2774                        "[{\"type\":\"additional_tools\",\"tools\":[{\"type\":\"namespace\",\
2775                         \"name\":\"mcp__moneypenny\",\"tools\":[{\"type\":\"function\",\
2776                         \"name\":\"board\"}]}]},{\"type\":\"message\",\"role\":\"user\",\
2777                         \"content\":[]}]"
2778                            .to_owned()
2779                    } else {
2780                        "[{\"type\":\"message\",\"role\":\"user\",\"content\":[]}]".to_owned()
2781                    }
2782                });
2783                answer(&mut stdout, &output)
2784            }
2785            _ => {}
2786        }
2787        let thread_id = std::env::var("CODEX_FIXTURE_THREAD_ID").unwrap();
2788        // A turn whose text is `run: COMMAND` asks the client to approve COMMAND, as the
2789        // app-server does before running a command, and reports the decision it receives.
2790        let mut asked = 900_u64;
2791        let mut pending = None;
2792        for line in std::io::stdin().lock().lines() {
2793            let message: Value = serde_json::from_str(&line.unwrap()).unwrap();
2794            let method = message.get("method").and_then(Value::as_str).unwrap_or("");
2795            // Codex answers a turn at once, with the turn's id, before it streams anything.
2796            if method == "turn/start"
2797                && let Some(id) = message.get("id")
2798            {
2799                writeln!(
2800                    stdout,
2801                    "{}",
2802                    json!({"id": id, "result": {"turn": {"id": "turn-7"}}})
2803                )
2804                .unwrap();
2805                stdout.flush().unwrap();
2806            }
2807            if pending.is_some() && message.get("id").and_then(Value::as_u64) == pending {
2808                pending = None;
2809                let decision = message
2810                    .pointer("/result/decision")
2811                    .and_then(Value::as_str)
2812                    .unwrap_or("none");
2813                let delta = format!("decision: {decision}");
2814                writeln!(
2815                    stdout,
2816                    "{}",
2817                    json!({"method":"item/agentMessage/delta","params":{"delta":delta}})
2818                )
2819                .unwrap();
2820                if decision == "accept" {
2821                    writeln!(stdout, "{}", json!({"method":"turn/completed","params":{}})).unwrap();
2822                }
2823                stdout.flush().unwrap();
2824                continue;
2825            }
2826            if method == "turn/steer" {
2827                assert_eq!(
2828                    message.pointer("/params/expectedTurnId"),
2829                    Some(&json!("turn-7"))
2830                );
2831                let text = message
2832                    .pointer("/params/input/0/text")
2833                    .and_then(Value::as_str)
2834                    .unwrap_or_default();
2835                let delta = format!("steered: {text}");
2836                writeln!(
2837                    stdout,
2838                    "{}",
2839                    json!({"method":"item/agentMessage/delta","params":{"delta":delta}})
2840                )
2841                .unwrap();
2842                writeln!(stdout, "{}", json!({"method":"turn/completed","params":{}})).unwrap();
2843                stdout.flush().unwrap();
2844                continue;
2845            }
2846            // `stdin: TEXT` asks to write to a running `cat`; `nameless` names no command.
2847            let text = message
2848                .pointer("/params/input/0/text")
2849                .and_then(Value::as_str)
2850                .unwrap_or_default();
2851            // `item: TYPE [SERVER]` starts a thread item of that type, as a turn using a tool.
2852            if method == "turn/start"
2853                && let Some(item) = text.strip_prefix("item: ")
2854            {
2855                let mut parts = item.split(' ');
2856                let kind = parts.next().unwrap_or_default();
2857                let server = parts.next().unwrap_or_default();
2858                for line in [
2859                    json!({"method":"item/started","params":{"item":{
2860                        "type": kind, "id": "item-9", "server": server, "tool": "board"
2861                    }}}),
2862                    json!({"method":"item/agentMessage/delta","params":{"delta":"after"}}),
2863                    json!({"method":"turn/completed","params":{}}),
2864                ] {
2865                    writeln!(stdout, "{line}").unwrap();
2866                }
2867                stdout.flush().unwrap();
2868                continue;
2869            }
2870            let asks = if let Some(command) = text.strip_prefix("run: ") {
2871                Some(("command", json!(command)))
2872            } else if text.starts_with("stdin: ") {
2873                Some(("writeStdin", json!("cat")))
2874            } else if text == "nameless" {
2875                Some(("command", Value::Null))
2876            } else {
2877                None
2878            };
2879            if method == "turn/start"
2880                && let Some((kind, command)) = asks
2881            {
2882                asked += 1;
2883                pending = Some(asked);
2884                // The command execution item the approval is for starts first, as Codex's
2885                // app server announces an item before asking about it.
2886                writeln!(
2887                    stdout,
2888                    "{}",
2889                    json!({"method":"item/started","params":{"item":{
2890                        "type":"commandExecution","id":"item-1","command":command
2891                    }}})
2892                )
2893                .unwrap();
2894                writeln!(
2895                    stdout,
2896                    "{}",
2897                    json!({
2898                        "id": asked,
2899                        "method": "item/commandExecution/requestApproval",
2900                        "params": {
2901                            "threadId": thread_id, "turnId": "turn-7", "itemId": "item-1",
2902                            "startedAtMs": 1_790_000_000_000_u64, "command": command,
2903                            "cwd": "/work", "kind": kind
2904                        }
2905                    })
2906                )
2907                .unwrap();
2908                stdout.flush().unwrap();
2909                continue;
2910            }
2911            if let Some(id) = message.get("id") {
2912                match method {
2913                    "initialize" => {
2914                        writeln!(stdout, "{}", json!({"id":id,"result":{}})).unwrap();
2915                        stdout.flush().unwrap();
2916                    }
2917                    // The driver asks for the skills once the thread is open, and waits for the
2918                    // answer; Codex lists none here.
2919                    "skills/list" => {
2920                        writeln!(stdout, "{}", json!({"id":id,"result":{"data":[]}})).unwrap();
2921                        stdout.flush().unwrap();
2922                    }
2923                    "config/read" => {
2924                        let config = fake_config(&argv);
2925                        writeln!(stdout, "{}", json!({"id":id,"result":{"config":config}}))
2926                            .unwrap();
2927                        stdout.flush().unwrap();
2928                    }
2929                    "thread/start" | "thread/resume" => {
2930                        // Reports the thread's policy as text, for tests that check it.
2931                        if std::env::var_os("CODEX_FIXTURE_SHOW_POLICY").is_some() {
2932                            let policy = json!({
2933                                "sandbox": message.pointer("/params/sandbox"),
2934                                "approvalPolicy": message.pointer("/params/approvalPolicy"),
2935                                "config": message.pointer("/params/config"),
2936                                "developerInstructions":
2937                                    message.pointer("/params/developerInstructions"),
2938                            });
2939                            writeln!(
2940                                stdout,
2941                                "{}",
2942                                json!({"method":"item/agentMessage/delta",
2943                                       "params":{"delta":format!("policy: {policy}")}})
2944                            )
2945                            .unwrap();
2946                        }
2947                        let config = fake_config(&argv);
2948                        let network = config.pointer("/permissions/ai6_assistant/network/enabled")
2949                            == Some(&json!(true));
2950                        let profile = config
2951                            .get("default_permissions")
2952                            .map(|name| json!({ "id": name }));
2953                        writeln!(
2954                            stdout,
2955                            "{}",
2956                            json!({"id":id,"result":{
2957                                "thread":{"id":thread_id},
2958                                "activePermissionProfile": profile,
2959                                "sandbox": {"networkAccess": network}
2960                            }})
2961                        )
2962                        .unwrap();
2963                        stdout.flush().unwrap();
2964                    }
2965                    _ => {}
2966                }
2967            }
2968            if method == "turn/start" {
2969                let text = message
2970                    .pointer("/params/input/0/text")
2971                    .and_then(Value::as_str)
2972                    .unwrap_or_default();
2973                writeln!(
2974                    stdout,
2975                    "{}",
2976                    json!({"method":"item/agentMessage/delta","params":{"delta":text}})
2977                )
2978                .unwrap();
2979                writeln!(stdout, "{}", json!({"method":"turn/completed","params":{}})).unwrap();
2980                stdout.flush().unwrap();
2981            }
2982        }
2983    }
2984
2985    /// The fake app server's effective configuration, as Codex 0.164.0 makes it: the sandbox
2986    /// settings its `-c` arguments give, merged over `CODEX_FIXTURE_USER_CONFIG` (JSON standing
2987    /// for the user's `config.toml`) table by table.
2988    fn fake_config(argv: &[&str]) -> Value {
2989        fn merge(into: &mut Value, from: Value) {
2990            match (into, from) {
2991                (Value::Object(into), Value::Object(from)) => {
2992                    for (key, value) in from {
2993                        merge(into.entry(key).or_insert(Value::Null), value);
2994                    }
2995                }
2996                (slot, value) => *slot = value,
2997            }
2998        }
2999        let mut config = std::env::var("CODEX_FIXTURE_USER_CONFIG")
3000            .map(|text| serde_json::from_str(&text).unwrap())
3001            .unwrap_or_else(|_| json!({}));
3002        for pair in argv.windows(2).filter(|pair| pair[0] == "-c") {
3003            let sandbox = [
3004                "permissions.",
3005                "default_permissions=",
3006                "shell_environment_policy.",
3007            ];
3008            if sandbox.iter().any(|prefix| pair[1].starts_with(prefix)) {
3009                let table: toml::Table = toml::from_str(pair[1]).unwrap();
3010                merge(&mut config, serde_json::to_value(table).unwrap());
3011            }
3012        }
3013        config
3014    }
3015
3016    fn read_to_completion(run: &Object<dyn AgentSession>) -> Vec<AgentEvent> {
3017        let deadline = Instant::now() + Duration::from_secs(60);
3018        let mut events = Vec::new();
3019        while Instant::now() < deadline {
3020            let remaining = deadline.saturating_duration_since(Instant::now());
3021            if let Some(event) = run
3022                .next_event(remaining.as_millis().min(i64::MAX as u128) as i64)
3023                .unwrap()
3024            {
3025                let completed = event.kind == "completed";
3026                events.push(event);
3027                if completed {
3028                    return events;
3029                }
3030            }
3031        }
3032        panic!("fake Codex did not complete the Run")
3033    }
3034
3035    #[test]
3036    fn process_run_restarts_and_resumes_with_the_same_provider_thread() {
3037        let terminal = ProcessTerminal::new();
3038        let run_id = RunId::try_new("codex-process-thread-42").unwrap();
3039        let environment =
3040            BTreeMap::from([("CODEX_FIXTURE_THREAD_ID".to_owned(), run_id.to_string())]);
3041        let handler = CodexHandler::try_from(CodexConfig {
3042            executable: "codex-process-fixture".to_owned(),
3043            ..CodexConfig::default()
3044        })
3045        .unwrap();
3046
3047        let started = handler
3048            .start(
3049                AgentStart {
3050                    mission_id: "mission-process-42".parse().unwrap(),
3051                    agent_id: "007".to_owned(),
3052                    prompt: "first process turn".to_owned(),
3053                    initial_context: vec!["context before the prompt".to_owned()],
3054                    working_directory: std::env::current_dir()
3055                        .unwrap()
3056                        .to_string_lossy()
3057                        .into_owned(),
3058                    clearance: "field".to_owned(),
3059                    environment: environment.clone(),
3060                    model: Some("gpt-5".to_owned()),
3061                    effort: Some("high".to_owned()),
3062                    max_cost_micro_usd: None,
3063                    project_settings: false,
3064                    project_mcp: false,
3065                    answer_only: false,
3066                    assistant: None,
3067                    overlays: Default::default(),
3068                    loadout: Default::default(),
3069                    ledger: None,
3070                },
3071                terminal.clone().into_object(),
3072            )
3073            .unwrap();
3074        let first_events = read_to_completion(&started);
3075        assert_eq!(started.session_id().unwrap(), Some(run_id.to_string()));
3076        assert!(first_events.iter().any(|event| {
3077            event.kind == "text" && event.text.as_deref() == Some("first process turn")
3078        }));
3079        assert!(first_events.iter().any(|event| event.kind == "completed"));
3080        started.close().unwrap();
3081
3082        let resumed = handler
3083            .resume(
3084                AgentResume {
3085                    clearance: "field".to_owned(),
3086                    mission_id: "mission-process-42".parse().unwrap(),
3087                    run_id: run_id.clone(),
3088                    message: Some("resumed process turn".to_owned()),
3089                    working_directory: std::env::current_dir()
3090                        .unwrap()
3091                        .to_string_lossy()
3092                        .into_owned(),
3093                    environment,
3094                    model: Some("gpt-5".to_owned()),
3095                    effort: Some("high".to_owned()),
3096                    max_cost_micro_usd: None,
3097                    project_settings: false,
3098                    project_mcp: false,
3099                    answer_only: false,
3100                    assistant: None,
3101                    initial_context: Vec::new(),
3102                    overlays: Default::default(),
3103                    loadout: Default::default(),
3104                },
3105                terminal.clone().into_object(),
3106            )
3107            .unwrap();
3108        assert_eq!(resumed.session_id().unwrap(), Some(run_id.to_string()));
3109        let resumed_events = read_to_completion(&resumed);
3110        assert!(resumed_events.iter().any(|event| {
3111            event.kind == "text" && event.text.as_deref() == Some("resumed process turn")
3112        }));
3113        assert!(resumed_events.iter().any(|event| event.kind == "completed"));
3114        resumed.close().unwrap();
3115
3116        let specs = terminal.specs.lock().unwrap();
3117        assert_eq!(specs.len(), 2);
3118        let cwd = std::env::current_dir().unwrap();
3119        let expected = [
3120            vec!["codex-process-fixture".to_owned(), "app-server".to_owned()],
3121            untrusted_project(&cwd.to_string_lossy()).to_vec(),
3122        ]
3123        .concat();
3124        assert_eq!(
3125            specs[0].argv, expected,
3126            "start ignores the project's settings"
3127        );
3128        assert_eq!(specs[1].argv, expected, "and so does resume");
3129    }
3130
3131    /// A gate that holds every governed step until an approval in `approved` covers it, as
3132    /// the Station answers through `check_approval`.
3133    /// A repository where every name is a branch and nothing is configured.
3134    struct Branches;
3135
3136    impl ai6::directorates::m::approvals::Repository for Branches {
3137        fn full_name(
3138            &self,
3139            _at: &ai6::directorates::m::approvals::GitContext,
3140            name: &str,
3141        ) -> Result<Option<String>, String> {
3142            Ok(Some(format!("refs/heads/{name}")))
3143        }
3144
3145        fn config(
3146            &self,
3147            _at: &ai6::directorates::m::approvals::GitContext,
3148            _key: &str,
3149        ) -> Result<Vec<String>, String> {
3150            Ok(Vec::new())
3151        }
3152    }
3153
3154    fn approvals_gate(approved: Arc<Mutex<Vec<ai6::ActionScope>>>) -> Option<Gate> {
3155        Some(Arc::new(move |command, _cwd| {
3156            match ai6::classify(command, &Branches, 4) {
3157                Err(reason) => GateVerdict::Hold(reason),
3158                Ok(steps) => {
3159                    let approved = approved.lock().unwrap();
3160                    match steps
3161                        .iter()
3162                        .find(|step| !approved.iter().any(|approval| approval.covers(step)))
3163                    {
3164                        None => GateVerdict::Allow,
3165                        Some(step) => GateVerdict::Hold(format!(
3166                            "call request_approval with kind {} and target {}",
3167                            step.kind, step.target
3168                        )),
3169                    }
3170                }
3171            }
3172        }))
3173    }
3174
3175    fn texts_until_completed(run: &Object<dyn AgentSession>) -> Vec<String> {
3176        let deadline = Instant::now() + Duration::from_secs(30);
3177        let mut texts = Vec::new();
3178        while Instant::now() < deadline {
3179            if let Some(event) = run.next_event(1_000).unwrap() {
3180                if event.kind == "completed" {
3181                    return texts;
3182                }
3183                texts.extend(event.text);
3184            }
3185        }
3186        panic!("fake Codex did not complete the turn: {texts:?}")
3187    }
3188
3189    #[test]
3190    fn a_governed_command_is_declined_until_green_ink_covers_it() {
3191        let approved = Arc::new(Mutex::new(Vec::new()));
3192        let handler = CodexHandler::try_from(CodexConfig {
3193            executable: "codex-gate-fixture".to_owned(),
3194            ..CodexConfig::default()
3195        })
3196        .unwrap();
3197        let run = handler
3198            .start_gated(
3199                AgentStart {
3200                    mission_id: "mission-gate".parse().unwrap(),
3201                    agent_id: "007".to_owned(),
3202                    prompt: "run: git push origin main".to_owned(),
3203                    initial_context: Vec::new(),
3204                    working_directory: std::env::current_dir()
3205                        .unwrap()
3206                        .to_string_lossy()
3207                        .into_owned(),
3208                    clearance: "field".to_owned(),
3209                    environment: BTreeMap::from([(
3210                        "CODEX_FIXTURE_THREAD_ID".to_owned(),
3211                        "codex-gate-thread".to_owned(),
3212                    )]),
3213                    model: None,
3214                    effort: None,
3215                    max_cost_micro_usd: None,
3216                    project_settings: false,
3217                    project_mcp: false,
3218                    answer_only: false,
3219                    assistant: None,
3220                    overlays: Default::default(),
3221                    loadout: Default::default(),
3222                    ledger: None,
3223                },
3224                ProcessTerminal::new().into_object(),
3225                approvals_gate(approved.clone()),
3226            )
3227            .unwrap();
3228
3229        let declined = texts_until_completed(&run);
3230        assert_eq!(declined[0], "decision: decline", "{declined:?}");
3231        assert!(
3232            declined[1].starts_with("steered: ")
3233                && declined[1].contains("request_approval")
3234                && declined[1].contains("origin:refs/heads/main"),
3235            "the Agent is told why: {declined:?}"
3236        );
3237
3238        approved
3239            .lock()
3240            .unwrap()
3241            .push(ai6::ActionScope::try_new("push", "origin:main").unwrap());
3242        run.send_message(AgentMessage {
3243            text: "run: git push origin main".to_owned(),
3244        })
3245        .unwrap();
3246        assert_eq!(texts_until_completed(&run), ["decision: accept"]);
3247
3248        run.send_message(AgentMessage {
3249            text: "run: cargo test --workspace".to_owned(),
3250        })
3251        .unwrap();
3252        assert_eq!(texts_until_completed(&run), ["decision: accept"]);
3253
3254        // The gate cannot see what these run, so they are declined and the Agent told why.
3255        for (text, why) in [
3256            ("stdin: git push origin main", "input to a running command"),
3257            ("nameless", "names no command"),
3258        ] {
3259            run.send_message(AgentMessage {
3260                text: text.to_owned(),
3261            })
3262            .unwrap();
3263            let declined = texts_until_completed(&run);
3264            assert_eq!(declined[0], "decision: decline", "{text}: {declined:?}");
3265            assert!(declined[1].contains(why), "{text}: {declined:?}");
3266        }
3267        run.close().unwrap();
3268    }
3269
3270    /// What a gated run answers to `stream`: the decision written back, and the events.
3271    fn answered(stream: &[u8]) -> (Value, Vec<AgentEvent>) {
3272        let (run, writes) = scripted_run(
3273            stream,
3274            "/work",
3275            approvals_gate(Arc::new(Mutex::new(Vec::new()))),
3276            None,
3277        );
3278        let events = events_until_quiet(&run);
3279        let (decision, _) = written_decision(&writes).expect("the approval was answered");
3280        (decision, events)
3281    }
3282
3283    fn started(command: &str) -> String {
3284        json!({"method":"item/started","params":{"item":{
3285            "type":"commandExecution","id":"item-1","command":command}}})
3286        .to_string()
3287    }
3288
3289    fn approval(command: &str) -> String {
3290        json!({"id": 901, "method": COMMAND_APPROVAL, "params": {
3291            "threadId": "t", "turnId": "u", "itemId": "item-1",
3292            "command": command, "cwd": "/work", "kind": "command"}})
3293        .to_string()
3294    }
3295
3296    #[test]
3297    fn an_approval_is_declined_unless_read_as_written_after_its_item_started() {
3298        let declined_event = |events: &[AgentEvent]| {
3299            events
3300                .iter()
3301                .find(|event| event.kind == "declined")
3302                .and_then(|event| event.text.clone())
3303        };
3304        let whole = format!(
3305            "{}\r\n{}\r\n",
3306            started("cargo test"),
3307            approval("cargo test")
3308        );
3309        let (decision, events) = answered(whole.as_bytes());
3310        assert_eq!(decision, "accept", "{events:?}");
3311
3312        let (decision, events) = answered(format!("{}\r\n", approval("cargo test")).as_bytes());
3313        assert_eq!(decision, "decline");
3314        assert!(
3315            declined_event(&events)
3316                .unwrap()
3317                .contains("no command execution item")
3318        );
3319
3320        let other = format!(
3321            "{}\r\n{}\r\n",
3322            started("cargo build"),
3323            approval("cargo test")
3324        );
3325        assert_eq!(answered(other.as_bytes()).0, "decline", "another command");
3326
3327        let line = approval("cargo test");
3328        let (head, tail) = line.split_at(line.find("cargo").unwrap());
3329        let broken = format!(
3330            "{}\r\n{head}\r\n\x1b[23;80H{tail}\r\n",
3331            started("cargo test")
3332        );
3333        let (decision, events) = answered(broken.as_bytes());
3334        assert_eq!(decision, "decline", "a line the terminal broke");
3335        assert!(declined_event(&events).unwrap().contains("rebuilt"));
3336
3337        let inside = format!("{}\r\n{head}\x1b[?25l{tail}\r\n", started("cargo test"));
3338        assert_eq!(
3339            answered(inside.as_bytes()).0,
3340            "decline",
3341            "a control other than colour inside the line"
3342        );
3343        let colour = format!("{}\r\n{head}\x1b[0m{tail}\r\n", started("cargo test"));
3344        assert_eq!(answered(colour.as_bytes()).0, "accept", "colour alone");
3345    }
3346
3347    /// The `item/started` and request Codex 0.164.0 sends on an `apply_patch` in a gated
3348    /// (`approvalPolicy` untrusted) thread, field for field, for `path`.
3349    fn file_change(path: &str, grant_root: Value) -> String {
3350        format!(
3351            "{}\r\n{}\r\n",
3352            json!({"method": "item/started", "params": {
3353                "threadId": "01a19a10-25e3-74e3-8584-f85797bbe59f",
3354                "turnId": "01a19a10-2834-7e90-b669-8320d3df8e45",
3355                "item": {
3356                    "type": "fileChange",
3357                    "id": "exec-43c043eb-e8cf-4952-ab6b-7f8306cf9b5e",
3358                    "changes": [{"path": path, "kind": {"type": "add"}, "diff": "x\n"}],
3359                    "status": "inProgress",
3360                },
3361            }}),
3362            json!({"method": FILE_APPROVAL, "id": 0, "params": {
3363                "threadId": "01a19a10-25e3-74e3-8584-f85797bbe59f",
3364                "turnId": "01a19a10-2834-7e90-b669-8320d3df8e45",
3365                "itemId": "exec-43c043eb-e8cf-4952-ab6b-7f8306cf9b5e",
3366                "startedAtMs": 1_793_586_113_669_u64,
3367                "reason": null,
3368                "grantRoot": grant_root,
3369            }}),
3370        )
3371    }
3372
3373    /// What a gated run working in `directory` answers to `stream`, and what it told the turn.
3374    fn answered_in(directory: &Path, stream: &str) -> (Value, String) {
3375        let (run, writes) = scripted_run(
3376            stream.as_bytes(),
3377            &directory.to_string_lossy(),
3378            approvals_gate(Arc::new(Mutex::new(Vec::new()))),
3379            None,
3380        );
3381        let _ = events_until_quiet(&run);
3382        written_decision(&writes).expect("the file change was answered, not left waiting")
3383    }
3384
3385    #[test]
3386    fn a_file_change_inside_the_working_directory_is_accepted_and_any_other_declined() {
3387        let root = tempfile::tempdir().unwrap();
3388        let work = root.path().join("work");
3389        std::fs::create_dir_all(work.join("notes")).unwrap();
3390        let path = |path: &Path| path.to_string_lossy().into_owned();
3391
3392        let (decision, written) = answered_in(
3393            &work,
3394            &file_change(&path(&work.join("notes").join("p.md")), Value::Null),
3395        );
3396        assert_eq!(decision, "accept", "{written}");
3397        assert!(!written.contains("turn/steer"), "{written}");
3398        let (decision, _) = answered_in(
3399            &work,
3400            &file_change(
3401                &path(&work.join("new").join("deep").join("p.md")),
3402                Value::Null,
3403            ),
3404        );
3405        assert_eq!(decision, "accept", "a directory the change makes");
3406
3407        for (why, stream) in [
3408            (
3409                "outside",
3410                file_change(&path(&root.path().join("outside.md")), Value::Null),
3411            ),
3412            (
3413                "climbing out",
3414                file_change(&format!("{}/../outside.md", path(&work)), Value::Null),
3415            ),
3416            (
3417                "a wider root",
3418                file_change(&path(&work.join("p.md")), json!(path(root.path()))),
3419            ),
3420        ] {
3421            let (decision, written) = answered_in(&work, &stream);
3422            assert_eq!(decision, "decline", "{why}");
3423            assert!(written.contains("turn/steer"), "{why}: the Agent is told");
3424        }
3425
3426        let unseen = json!({"method": FILE_APPROVAL, "id": 0, "params": {
3427            "threadId": "t", "turnId": "u", "itemId": "never-started",
3428            "reason": null, "grantRoot": null}});
3429        let (decision, _) = answered_in(&work, &format!("{unseen}\r\n"));
3430        assert_eq!(decision, "decline", "no item started");
3431    }
3432
3433    /// What a `desk` run working in `directory`, without a gate, answers to `stream`.
3434    fn answered_at_desk(directory: &Path, stream: &str) -> Value {
3435        let (run, writes) = scripted_run(
3436            stream.as_bytes(),
3437            &directory.to_string_lossy(),
3438            None,
3439            restriction(false, None, Some(&BTreeMap::new()), false),
3440        );
3441        let _ = events_until_quiet(&run);
3442        written_decision(&writes)
3443            .expect("the file change was answered, not left waiting")
3444            .0
3445    }
3446
3447    #[test]
3448    fn a_thread_held_to_its_plan_changes_no_file_and_one_at_desk_or_field_may() {
3449        let root = tempfile::tempdir().unwrap();
3450        let work = root.path().join("work");
3451        std::fs::create_dir_all(&work).unwrap();
3452        let inside = file_change(&work.join("p.md").to_string_lossy(), Value::Null);
3453        let answered = |reads_only: bool| {
3454            let (run, writes) = scripted_run(
3455                inside.as_bytes(),
3456                &work.to_string_lossy(),
3457                None,
3458                restriction(false, None, Some(&BTreeMap::new()), reads_only),
3459            );
3460            let events = events_until_quiet(&run);
3461            (written_decision(&writes).map(|written| written.0), events)
3462        };
3463        let (decision, events) = answered(true);
3464        assert_ne!(decision, Some(json!("accept")), "{events:?}");
3465        assert!(
3466            events.iter().any(|event| event.kind == "failed"),
3467            "a patch ends a thread held to its plan: {events:?}"
3468        );
3469        assert_eq!(
3470            answered(false).0,
3471            Some(json!("accept")),
3472            "after the pass it may"
3473        );
3474        assert!(
3475            held_to_desk(ai6::READ_CLEARANCE, false, None),
3476            "and it never runs a command"
3477        );
3478    }
3479
3480    #[test]
3481    fn this_handler_can_hold_a_thread_to_its_plan() {
3482        let handler = CodexHandler::try_from(CodexConfig::default()).unwrap();
3483        assert_eq!(handler.read_only_refusal().unwrap(), None);
3484    }
3485
3486    #[test]
3487    fn a_desk_thread_without_a_gate_may_change_files_only_inside_its_directory() {
3488        let root = tempfile::tempdir().unwrap();
3489        let work = root.path().join("work");
3490        std::fs::create_dir_all(&work).unwrap();
3491        let path = |path: &Path| path.to_string_lossy().into_owned();
3492        assert_eq!(
3493            answered_at_desk(&work, &file_change(&path(&work.join("p.md")), Value::Null)),
3494            "accept"
3495        );
3496        for (why, stream) in [
3497            (
3498                "outside",
3499                file_change(&path(&root.path().join("outside.md")), Value::Null),
3500            ),
3501            (
3502                "climbing out",
3503                file_change(&format!("{}/../outside.md", path(&work)), Value::Null),
3504            ),
3505            (
3506                "a wider root",
3507                file_change(&path(&work.join("p.md")), json!(path(root.path()))),
3508            ),
3509        ] {
3510            assert_eq!(answered_at_desk(&work, &stream), "decline", "{why}");
3511        }
3512    }
3513
3514    /// The settings a start, then a resume, at `clearance` hand the app server, and the policy each
3515    /// thread was started with.
3516    fn launched_at(
3517        clearance: &str,
3518        executable: &str,
3519        environment: BTreeMap<String, String>,
3520    ) -> Launched {
3521        let mut environment = environment;
3522        environment.insert(
3523            "CODEX_FIXTURE_THREAD_ID".to_owned(),
3524            "codex-clearance-thread".to_owned(),
3525        );
3526        environment.insert("CODEX_FIXTURE_SHOW_POLICY".to_owned(), "1".to_owned());
3527        let terminal = ProcessTerminal::new();
3528        let handler = CodexHandler::try_from(CodexConfig {
3529            executable: executable.to_owned(),
3530            ..CodexConfig::default()
3531        })
3532        .unwrap();
3533        let cwd = std::env::current_dir()
3534            .unwrap()
3535            .to_string_lossy()
3536            .into_owned();
3537        let started = handler
3538            .start(
3539                AgentStart {
3540                    mission_id: "mission-clearance".parse().unwrap(),
3541                    agent_id: "007".to_owned(),
3542                    prompt: "work".to_owned(),
3543                    initial_context: Vec::new(),
3544                    working_directory: cwd.clone(),
3545                    clearance: clearance.to_owned(),
3546                    environment: environment.clone(),
3547                    model: None,
3548                    effort: None,
3549                    max_cost_micro_usd: None,
3550                    project_settings: false,
3551                    project_mcp: false,
3552                    answer_only: false,
3553                    assistant: None,
3554                    overlays: Default::default(),
3555                    loadout: Default::default(),
3556                    ledger: None,
3557                },
3558                terminal.clone().into_object(),
3559            )
3560            .unwrap();
3561        let first = read_to_completion(&started);
3562        started.close().unwrap();
3563        let resumed = handler
3564            .resume(
3565                AgentResume {
3566                    mission_id: "mission-clearance".parse().unwrap(),
3567                    run_id: RunId::try_new("codex-clearance-thread").unwrap(),
3568                    message: Some("more".to_owned()),
3569                    working_directory: cwd,
3570                    clearance: clearance.to_owned(),
3571                    environment,
3572                    model: None,
3573                    effort: None,
3574                    max_cost_micro_usd: None,
3575                    project_settings: false,
3576                    project_mcp: false,
3577                    answer_only: false,
3578                    assistant: None,
3579                    initial_context: Vec::new(),
3580                    overlays: Default::default(),
3581                    loadout: Default::default(),
3582                },
3583                terminal.clone().into_object(),
3584            )
3585            .unwrap();
3586        let second = read_to_completion(&resumed);
3587        resumed.close().unwrap();
3588        let policy = |events: &[AgentEvent]| -> Value {
3589            let text = events
3590                .iter()
3591                .find_map(|event| event.text.as_deref()?.strip_prefix("policy: "))
3592                .expect("the thread's policy was reported");
3593            serde_json::from_str(text).unwrap()
3594        };
3595        let policies = [policy(&first), policy(&second)];
3596        let specs = terminal.specs.lock().unwrap();
3597        let servers: Vec<_> = specs
3598            .iter()
3599            .filter(|spec| spec.argv[1] == "app-server")
3600            .map(|spec| spec.argv[2..].to_vec())
3601            .collect();
3602        let rendered = specs
3603            .iter()
3604            .filter(|spec| spec.argv.len() > 2 && spec.argv[1..3] == ["debug", "prompt-input"])
3605            .count();
3606        assert_eq!(servers.len(), 2);
3607        Launched {
3608            servers,
3609            policies,
3610            rendered,
3611        }
3612    }
3613
3614    struct Launched {
3615        servers: Vec<Vec<String>>,
3616        policies: [Value; 2],
3617        /// How many times `codex debug prompt-input` ran.
3618        rendered: usize,
3619    }
3620
3621    fn cable() -> BTreeMap<String, String> {
3622        BTreeMap::from([
3623            (
3624                "AI6_CABLE_MCP_URL".to_owned(),
3625                "http://127.0.0.1:1/mcp".to_owned(),
3626            ),
3627            ("AI6_CABLE_MCP_TOKEN".to_owned(), "token".to_owned()),
3628        ])
3629    }
3630
3631    /// The `-c` values of a list of arguments, with the working directory's `projects` entry left
3632    /// out, since it holds a path.
3633    fn settings(arguments: &[String]) -> Vec<&str> {
3634        arguments
3635            .iter()
3636            .filter(|argument| *argument != "-c" && !argument.starts_with("projects="))
3637            .map(String::as_str)
3638            .collect()
3639    }
3640
3641    #[test]
3642    fn a_threads_settings_follow_its_clearance_on_start_and_resume() {
3643        let station = [
3644            "mcp_servers.ai6-cables.url=\"http://127.0.0.1:1/mcp\"",
3645            "mcp_servers.ai6-cables.bearer_token_env_var=\"AI6_CABLE_MCP_TOKEN\"",
3646            "mcp_servers.ai6-cables.default_tools_approval_mode=\"approve\"",
3647        ];
3648        for (index, clearance) in ["field", "00"].iter().enumerate() {
3649            let launched = launched_at(
3650                clearance,
3651                &format!("codex-field-clearance-fixture-{index}"),
3652                cable(),
3653            );
3654            assert_eq!(launched.rendered, 0, "{clearance}: no tool check");
3655            for server in &launched.servers {
3656                assert_eq!(settings(server), station, "{clearance}");
3657            }
3658            for policy in &launched.policies {
3659                assert_eq!(policy["sandbox"], Value::Null, "{clearance}");
3660                assert_eq!(policy["approvalPolicy"], "untrusted", "{clearance}");
3661            }
3662        }
3663        // A value the handler does not know, an empty one included, gets the least it can give.
3664        // The fake lists `code_mode_host`, kept, and `tool_suggest`, switched off.
3665        let desk: Vec<&str> = station
3666            .iter()
3667            .copied()
3668            .chain(NO_BUILT_IN_TOOLS)
3669            .chain(["features.tool_suggest=false"])
3670            .collect();
3671        for (index, clearance) in ["desk", "developer", ""].iter().enumerate() {
3672            let launched = launched_at(
3673                clearance,
3674                &format!("codex-desk-clearance-fixture-{index}"),
3675                cable(),
3676            );
3677            assert_eq!(launched.rendered, 2, "{clearance:?}: checked each time");
3678            for server in &launched.servers {
3679                assert_eq!(settings(server), desk, "{clearance:?}");
3680            }
3681            for policy in &launched.policies {
3682                assert_eq!(policy["sandbox"], "read-only", "{clearance:?}");
3683                assert_eq!(policy["approvalPolicy"], "untrusted", "{clearance:?}");
3684            }
3685        }
3686    }
3687
3688    #[test]
3689    fn the_theater_server_waits_as_long_as_the_station_says_a_call_may_take() {
3690        let mut environment = cable();
3691        environment.extend([
3692            (
3693                "AI6_THEATER_MCP_URL".to_owned(),
3694                "http://127.0.0.1:2/mcp".to_owned(),
3695            ),
3696            ("AI6_THEATER_MCP_TOKEN".to_owned(), "token".to_owned()),
3697        ]);
3698        let without = app_server_argv("codex", &environment);
3699        assert!(
3700            !without
3701                .iter()
3702                .any(|argument| argument.contains("tool_timeout_sec")),
3703            "no timeout named, none set"
3704        );
3705        environment.insert(
3706            "AI6_THEATER_MCP_TIMEOUT_MS".to_owned(),
3707            "3630001".to_owned(),
3708        );
3709        let argv = app_server_argv("codex", &environment);
3710        let timeouts: Vec<&String> = argv
3711            .iter()
3712            .filter(|argument| argument.contains("tool_timeout_sec"))
3713            .collect();
3714        assert_eq!(timeouts, ["mcp_servers.ai6-theater.tool_timeout_sec=3631"]);
3715        let cables_only = app_server_argv("codex", &cable());
3716        assert!(
3717            !cables_only
3718                .iter()
3719                .any(|argument| argument.contains("tool_timeout_sec"))
3720        );
3721    }
3722
3723    #[test]
3724    fn a_native_theater_is_codexs_own_environment_and_keeps_its_shell_tool() {
3725        let mut environment = BTreeMap::from([
3726            (
3727                "AI6_THEATER_MCP_URL".to_owned(),
3728                "http://127.0.0.1:2/mcp".to_owned(),
3729            ),
3730            ("AI6_THEATER_MCP_TOKEN".to_owned(), "theater".to_owned()),
3731        ]);
3732        assert!(native_environment(&environment).is_none());
3733        assert!(
3734            app_server_argv("codex", &environment)
3735                .contains(&"features.shell_tool=false".to_owned()),
3736            "the tools way turns the shell off"
3737        );
3738        environment.extend([
3739            ("AI6_THEATER_EXEC_ID".to_owned(), "theater".to_owned()),
3740            (
3741                "AI6_THEATER_EXEC_URL".to_owned(),
3742                "ws://127.0.0.1:9".to_owned(),
3743            ),
3744            ("AI6_THEATER_EXEC_TOKEN".to_owned(), "bearer".to_owned()),
3745            ("AI6_THEATER_EXEC_CWD".to_owned(), "/work".to_owned()),
3746        ]);
3747        let native = native_environment(&environment).expect("a native environment");
3748        assert_eq!(
3749            (native.id.as_str(), native.url.as_str(), native.cwd.as_str()),
3750            ("theater", "ws://127.0.0.1:9", "/work")
3751        );
3752        assert!(
3753            !app_server_argv("codex", &environment)
3754                .contains(&"features.shell_tool=false".to_owned()),
3755            "its shell runs in the Theater"
3756        );
3757    }
3758
3759    #[test]
3760    fn a_desk_thread_on_a_remote_theater_has_no_tool_that_runs_or_writes() {
3761        let mut environment = cable();
3762        environment.extend([
3763            (
3764                "AI6_THEATER_MCP_URL".to_owned(),
3765                "http://127.0.0.1:2/mcp".to_owned(),
3766            ),
3767            ("AI6_THEATER_MCP_TOKEN".to_owned(), "token".to_owned()),
3768        ]);
3769        let launched = launched_at("desk", "codex-desk-remote-fixture", environment.clone());
3770        for server in &launched.servers {
3771            assert!(settings(server).contains(&THEATER_TOOLS_OFF), "{server:?}");
3772        }
3773        for policy in &launched.policies {
3774            assert_eq!(policy["sandbox"], "read-only");
3775            assert_eq!(
3776                policy["approvalPolicy"], "never",
3777                "nothing lands on the Station"
3778            );
3779        }
3780        let launched = launched_at("field", "codex-field-remote-fixture", environment);
3781        for server in &launched.servers {
3782            assert!(!settings(server).contains(&THEATER_TOOLS_OFF), "{server:?}");
3783        }
3784    }
3785
3786    /// `codex debug prompt-input` of Codex 0.164.0 for a `desk` thread. `SCRIPTS_PROMPT` stands for
3787    /// a thread whose `exec` still nests the command tools.
3788    const DESK_PROMPT: &str =
3789        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-desk.json");
3790
3791    fn desk_start(
3792        executable: &str,
3793        prompt: &str,
3794        extra: &[(&str, &str)],
3795    ) -> Result<Object<dyn AgentSession>, ProviderError> {
3796        desk_start_on(ProcessTerminal::new(), executable, prompt, extra)
3797    }
3798
3799    fn desk_start_on(
3800        terminal: ProcessTerminal,
3801        executable: &str,
3802        prompt: &str,
3803        extra: &[(&str, &str)],
3804    ) -> Result<Object<dyn AgentSession>, ProviderError> {
3805        let mut environment = cable();
3806        environment.insert(
3807            "CODEX_FIXTURE_THREAD_ID".to_owned(),
3808            "codex-desk-thread".to_owned(),
3809        );
3810        environment.extend(
3811            extra
3812                .iter()
3813                .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())),
3814        );
3815        CodexHandler::try_from(CodexConfig {
3816            executable: executable.to_owned(),
3817            ..CodexConfig::default()
3818        })
3819        .unwrap()
3820        .start(
3821            AgentStart {
3822                mission_id: "mission-desk".parse().unwrap(),
3823                agent_id: "007".to_owned(),
3824                prompt: prompt.to_owned(),
3825                initial_context: Vec::new(),
3826                working_directory: std::env::current_dir()
3827                    .unwrap()
3828                    .to_string_lossy()
3829                    .into_owned(),
3830                clearance: "desk".to_owned(),
3831                environment,
3832                model: Some("gpt-6.1-sol".to_owned()),
3833                effort: None,
3834                max_cost_micro_usd: None,
3835                project_settings: false,
3836                project_mcp: false,
3837                answer_only: false,
3838                assistant: None,
3839                overlays: Default::default(),
3840                loadout: Default::default(),
3841                ledger: None,
3842            },
3843            terminal.into_object(),
3844        )
3845    }
3846
3847    /// `codex mcp list --json` prints each server's environment values: only the app server, the
3848    /// Run itself, may run where its viewers read it.
3849    #[test]
3850    fn the_tool_check_runs_out_of_the_viewers_sight_and_the_app_server_in_it() {
3851        let terminal = ProcessTerminal::new();
3852        let desk = DESK_PROMPT.replace('\n', "");
3853        let run = desk_start_on(
3854            terminal.clone(),
3855            "codex-private-probe-fixture",
3856            "work",
3857            &[("CODEX_FIXTURE_PROMPT_INPUT", &desk)],
3858        )
3859        .unwrap();
3860        read_to_completion(&run);
3861        run.close().unwrap();
3862        let private = terminal.private.lock().unwrap();
3863        for command in ["--version", "features", "mcp", "debug"] {
3864            assert!(private.iter().any(|word| word == command), "{private:?}");
3865        }
3866        assert!(
3867            !private.iter().any(|word| word == "app-server"),
3868            "{private:?}"
3869        );
3870        assert!(
3871            terminal
3872                .specs
3873                .lock()
3874                .unwrap()
3875                .iter()
3876                .any(|spec| spec.argv[1] == "app-server")
3877        );
3878    }
3879
3880    #[test]
3881    fn a_desk_thread_starts_only_if_codex_gives_it_no_command_tool() {
3882        let desk = DESK_PROMPT.replace('\n', "");
3883        let run = desk_start(
3884            "codex-desk-offered-fixture",
3885            "work",
3886            &[("CODEX_FIXTURE_PROMPT_INPUT", &desk)],
3887        )
3888        .unwrap();
3889        let events = read_to_completion(&run);
3890        assert!(
3891            !events.iter().any(|event| event.kind == "weakened"),
3892            "{events:?}"
3893        );
3894        run.close().unwrap();
3895
3896        let nests_commands = SCRIPTS_PROMPT.replace('\n', "");
3897        let refused = match desk_start(
3898            "codex-desk-commands-fixture",
3899            "work",
3900            &[("CODEX_FIXTURE_PROMPT_INPUT", &nests_commands)],
3901        ) {
3902            Ok(_) => panic!("a desk thread with exec_command started"),
3903            Err(error) => error.to_string(),
3904        };
3905        assert!(
3906            refused.contains("exec_command") && refused.contains(TOOL_CHECK_ENV),
3907            "{refused}"
3908        );
3909        let run = desk_start(
3910            "codex-desk-commands-warned-fixture",
3911            "work",
3912            &[
3913                ("CODEX_FIXTURE_PROMPT_INPUT", &nests_commands),
3914                (TOOL_CHECK_ENV, "warn"),
3915            ],
3916        )
3917        .unwrap();
3918        let events = read_to_completion(&run);
3919        assert!(
3920            events.iter().any(|event| event.kind == "weakened"
3921                && event.text.as_deref().unwrap().contains("exec_command")),
3922            "{events:?}"
3923        );
3924        run.close().unwrap();
3925    }
3926
3927    #[test]
3928    fn a_desk_thread_is_told_it_has_no_tool_that_reads_the_checkout() {
3929        let desk = DESK_PROMPT.replace('\n', "");
3930        let run = desk_start(
3931            "codex-desk-told-fixture",
3932            "work",
3933            &[
3934                ("CODEX_FIXTURE_PROMPT_INPUT", &desk),
3935                ("CODEX_FIXTURE_SHOW_POLICY", "1"),
3936            ],
3937        )
3938        .unwrap();
3939        let events = read_to_completion(&run);
3940        let told = reported_policy(&events)["developerInstructions"]
3941            .as_str()
3942            .unwrap_or_default()
3943            .to_owned();
3944        assert!(told.contains("no tool that reads a file"), "{told:?}");
3945        run.close().unwrap();
3946    }
3947
3948    #[test]
3949    fn a_desk_thread_that_runs_a_command_anyway_is_ended() {
3950        for (executable, prompt) in [
3951            ("codex-desk-item-fixture", "item: commandExecution"),
3952            ("codex-desk-ask-fixture", "run: rm -rf /"),
3953        ] {
3954            let run = desk_start(executable, prompt, &[]).unwrap();
3955            let deadline = Instant::now() + Duration::from_secs(30);
3956            let reason = loop {
3957                assert!(Instant::now() < deadline, "{prompt}: never ended");
3958                if let Some(event) = run.next_event(100).unwrap()
3959                    && event.kind == "failed"
3960                {
3961                    break event.text.unwrap();
3962                }
3963            };
3964            assert!(reason.contains("restricted Codex thread used"), "{reason}");
3965            run.close().unwrap();
3966        }
3967    }
3968
3969    #[test]
3970    fn a_gated_run_asks_before_every_untrusted_command() {
3971        let cable = std::collections::BTreeMap::from([
3972            (
3973                "AI6_CABLE_MCP_URL".to_owned(),
3974                "http://127.0.0.1:1/mcp".to_owned(),
3975            ),
3976            ("AI6_CABLE_MCP_TOKEN".to_owned(), "token".to_owned()),
3977        ]);
3978        let mut params = ThreadPolicy::default();
3979        set_approval_policy(&mut params, &cable, false, Scripts::None, false);
3980        assert_eq!(params.approval_policy, Some("untrusted"));
3981
3982        let mut params = ThreadPolicy::default();
3983        set_approval_policy(&mut params, &cable, true, Scripts::None, false);
3984        assert_eq!(
3985            params.sandbox,
3986            Some("read-only"),
3987            "answer-only wins over the gate"
3988        );
3989        assert_eq!(params.approval_policy, Some("never"));
3990        assert_eq!(
3991            params.config,
3992            Some(ThreadConfig {
3993                web_search: "disabled"
3994            })
3995        );
3996
3997        let mut remote = cable.clone();
3998        remote.insert(
3999            "AI6_THEATER_MCP_URL".to_owned(),
4000            "http://127.0.0.1:2/mcp".to_owned(),
4001        );
4002        remote.insert("AI6_THEATER_MCP_TOKEN".to_owned(), "theater".to_owned());
4003        let mut params = ThreadPolicy::default();
4004        set_approval_policy(&mut params, &remote, false, Scripts::None, false);
4005        assert_eq!(
4006            params.approval_policy,
4007            Some("never"),
4008            "the Station gates the Theater tools"
4009        );
4010
4011        let mut params = ThreadPolicy::default();
4012        set_approval_policy(
4013            &mut params,
4014            &std::collections::BTreeMap::new(),
4015            false,
4016            Scripts::None,
4017            false,
4018        );
4019        assert_eq!(
4020            params,
4021            ThreadPolicy::default(),
4022            "no gate, Codex's own policy"
4023        );
4024    }
4025
4026    /// How a scripted app server's output ends once everything scripted was read.
4027    #[derive(Clone, Copy, PartialEq, Eq)]
4028    enum Ending {
4029        /// Never: the terminal keeps its output open.
4030        Open,
4031        /// The terminal closes its output.
4032        Eof,
4033        /// The program exits with this code and the terminal keeps its output open.
4034        Exited(i64),
4035    }
4036
4037    /// A terminal whose app server answers by script: the n-th request written (a message with an
4038    /// id and a method) releases the n-th chunk of output, and the request `handshake` releases
4039    /// every chunk left, so a stream is read only once the driver is waiting for it.
4040    struct ScriptedTerminal {
4041        spec: Arc<Mutex<Option<Spec>>>,
4042        chunks: Vec<Vec<u8>>,
4043        handshake: usize,
4044        ending: Ending,
4045        writes: Arc<Mutex<Vec<u8>>>,
4046        killed: Arc<AtomicBool>,
4047    }
4048
4049    impl ScriptedTerminal {
4050        fn new(chunks: Vec<Vec<u8>>, handshake: usize) -> Self {
4051            Self {
4052                spec: Arc::new(Mutex::new(None)),
4053                chunks,
4054                handshake,
4055                ending: Ending::Open,
4056                writes: Arc::new(Mutex::new(Vec::new())),
4057                killed: Arc::new(AtomicBool::new(false)),
4058            }
4059        }
4060
4061        fn ending(mut self, ending: Ending) -> Self {
4062            self.ending = ending;
4063            self
4064        }
4065    }
4066
4067    impl AgentTerminal for ScriptedTerminal {
4068        fn spawn_private(
4069            &self,
4070            value: &ai6::guatiao::Value,
4071        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
4072            self.spawn(value)
4073        }
4074
4075        fn spawn(
4076            &self,
4077            value: &ai6::guatiao::Value,
4078        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
4079            *self.spec.lock().unwrap() = Some(Spec::from_value(value).map_err(internal)?);
4080            Ok(ScriptedRun {
4081                script: Mutex::new(Script {
4082                    output: VecDeque::new(),
4083                    chunks: self.chunks.iter().cloned().collect(),
4084                    requests: 0,
4085                }),
4086                arrived: Condvar::new(),
4087                handshake: self.handshake,
4088                ending: self.ending,
4089                writes: self.writes.clone(),
4090                killed: self.killed.clone(),
4091            }
4092            .into_object())
4093        }
4094    }
4095
4096    struct Script {
4097        output: VecDeque<u8>,
4098        chunks: VecDeque<Vec<u8>>,
4099        requests: usize,
4100    }
4101
4102    struct ScriptedRun {
4103        script: Mutex<Script>,
4104        arrived: Condvar,
4105        handshake: usize,
4106        ending: Ending,
4107        writes: Arc<Mutex<Vec<u8>>>,
4108        killed: Arc<AtomicBool>,
4109    }
4110
4111    impl TerminalRun for ScriptedRun {
4112        fn pid(&self) -> i64 {
4113            8
4114        }
4115
4116        fn read(&self, dst: &mut [u8], timeout_ms: i64) -> Result<i64, ProviderError> {
4117            let mut script = self.script.lock().unwrap();
4118            if script.output.is_empty() {
4119                script = self
4120                    .arrived
4121                    .wait_timeout(script, Duration::from_millis(timeout_ms.max(0) as u64))
4122                    .unwrap()
4123                    .0;
4124            }
4125            if script.output.is_empty() {
4126                let finished = script.chunks.is_empty() && script.requests > 0;
4127                return Ok(if self.ending == Ending::Eof && finished {
4128                    0
4129                } else {
4130                    READ_TIMED_OUT
4131                });
4132            }
4133            let count = dst.len().min(script.output.len());
4134            for byte in &mut dst[..count] {
4135                *byte = script.output.pop_front().unwrap();
4136            }
4137            Ok(count as i64)
4138        }
4139
4140        fn write(&self, data: &[u8]) -> Result<(), ProviderError> {
4141            self.writes.lock().unwrap().extend_from_slice(data);
4142            for line in data.split(|byte| *byte == b'\n') {
4143                let Ok(message) = serde_json::from_slice::<Value>(line) else {
4144                    continue;
4145                };
4146                if message.get("id").is_none() || message.get("method").is_none() {
4147                    continue;
4148                }
4149                let mut script = self.script.lock().unwrap();
4150                script.requests += 1;
4151                let released = if script.requests >= self.handshake {
4152                    script.chunks.drain(..).collect::<Vec<_>>()
4153                } else {
4154                    script.chunks.pop_front().into_iter().collect()
4155                };
4156                for chunk in released {
4157                    script.output.extend(chunk);
4158                }
4159                self.arrived.notify_all();
4160            }
4161            Ok(())
4162        }
4163
4164        fn resize(&self, _rows: i64, _cols: i64) -> Result<(), ProviderError> {
4165            Ok(())
4166        }
4167
4168        fn kill(&self) -> Result<(), ProviderError> {
4169            self.killed.store(true, Ordering::Release);
4170            Ok(())
4171        }
4172
4173        fn exit_status(&self, _timeout_ms: i64) -> Result<ai6::guatiao::Value, ProviderError> {
4174            let script = self.script.lock().unwrap();
4175            match self.ending {
4176                Ending::Exited(code)
4177                    if script.requests > 0
4178                        && script.chunks.is_empty()
4179                        && script.output.is_empty() =>
4180                {
4181                    ExitInfo {
4182                        running: false,
4183                        code: Some(code),
4184                        signal: None,
4185                    }
4186                    .to_value()
4187                    .map_err(internal)
4188                }
4189                Ending::Exited(_) => ExitInfo {
4190                    running: true,
4191                    code: None,
4192                    signal: None,
4193                }
4194                .to_value()
4195                .map_err(internal),
4196                _ => Err(refuse(Status::GUATIAO_ERR_INTERNAL, "unused in this test")),
4197            }
4198        }
4199    }
4200
4201    /// A run on a scripted app server that opens a thread, takes a turn, and then writes `stream`;
4202    /// what it wrote back is in the second value.
4203    fn scripted_run(
4204        stream: &[u8],
4205        directory: &str,
4206        gate: Option<Gate>,
4207        restriction: Option<Restriction>,
4208    ) -> (CodexRun, Arc<Mutex<Vec<u8>>>) {
4209        let mut turn = b"{\"id\":4,\"result\":{\"turn\":{\"id\":\"u\"}}}\n".to_vec();
4210        turn.extend_from_slice(stream);
4211        let terminal = ScriptedTerminal::new(
4212            vec![
4213                b"{\"id\":1,\"result\":{}}\n".to_vec(),
4214                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"t\"}}}\n".to_vec(),
4215                b"{\"id\":3,\"result\":{\"data\":[]}}\n".to_vec(),
4216                turn,
4217            ],
4218            4,
4219        );
4220        let writes = terminal.writes.clone();
4221        let config = CodexConfig::default();
4222        let run = open(Opening {
4223            config: &config,
4224            terminal: terminal.into_object(),
4225            cwd: directory,
4226            environment: &BTreeMap::new(),
4227            mode: Mode {
4228                config: &config,
4229                project_settings: true,
4230                answer_only: false,
4231                desk: false,
4232                assistant: None,
4233                model: None,
4234                profile: None,
4235            },
4236            thread: ThreadStart::New,
4237            model: None,
4238            effort: None,
4239            instructions: None,
4240            gate,
4241            restriction,
4242            profile: None,
4243            loadout: Default::default(),
4244        })
4245        .unwrap();
4246        run.send_message(AgentMessage {
4247            text: "go".to_owned(),
4248        })
4249        .unwrap();
4250        (run, writes)
4251    }
4252
4253    /// Every event the run tells until it has been quiet for a moment.
4254    fn events_until_quiet(run: &CodexRun) -> Vec<AgentEvent> {
4255        let mut events = Vec::new();
4256        while let Ok(Some(event)) = run.next_event(400) {
4257            events.push(event);
4258        }
4259        events
4260    }
4261
4262    /// Opens a thread on `terminal` with the settings of an ungated Mission's.
4263    fn open_on(
4264        terminal: ScriptedTerminal,
4265        config: &CodexConfig,
4266    ) -> Result<CodexRun, ProviderError> {
4267        open(Opening {
4268            config,
4269            terminal: terminal.into_object(),
4270            cwd: "/work",
4271            environment: &BTreeMap::new(),
4272            mode: Mode {
4273                config,
4274                project_settings: true,
4275                answer_only: false,
4276                desk: false,
4277                assistant: None,
4278                model: None,
4279                profile: None,
4280            },
4281            thread: ThreadStart::New,
4282            model: None,
4283            effort: None,
4284            instructions: None,
4285            gate: None,
4286            restriction: None,
4287            profile: None,
4288            loadout: Default::default(),
4289        })
4290    }
4291
4292    /// The decision the app server was sent, once it has been.
4293    fn written_decision(writes: &Arc<Mutex<Vec<u8>>>) -> Option<(Value, String)> {
4294        let deadline = Instant::now() + Duration::from_secs(3);
4295        loop {
4296            let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4297            if let Some(decision) = written
4298                .lines()
4299                .filter_map(|line| serde_json::from_str::<Value>(line).ok())
4300                .find_map(|message| message.pointer("/result/decision").cloned())
4301            {
4302                // What follows a decision (the steer) is written in the same moment.
4303                std::thread::sleep(Duration::from_millis(100));
4304                let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4305                return Some((decision, written));
4306            }
4307            if Instant::now() > deadline {
4308                return None;
4309            }
4310            std::thread::sleep(Duration::from_millis(20));
4311        }
4312    }
4313
4314    /// The Theater's environment `native_environment` reads, as the Station serves one.
4315    fn theater_environment() -> BTreeMap<String, String> {
4316        BTreeMap::from([
4317            ("AI6_THEATER_EXEC_ID".to_owned(), "theater".to_owned()),
4318            (
4319                "AI6_THEATER_EXEC_URL".to_owned(),
4320                "ws://127.0.0.1:9".to_owned(),
4321            ),
4322            ("AI6_THEATER_EXEC_TOKEN".to_owned(), "bearer".to_owned()),
4323            ("AI6_THEATER_EXEC_CWD".to_owned(), "/work".to_owned()),
4324        ])
4325    }
4326
4327    #[test]
4328    fn a_thread_in_a_theaters_environment_is_never_resumed_onto_the_station() {
4329        let terminal = ScriptedTerminal::new(Vec::new(), 0);
4330        let spec = terminal.spec.clone();
4331        let handler = CodexHandler::try_from(CodexConfig {
4332            executable: "codex-test".to_owned(),
4333            ..CodexConfig::default()
4334        })
4335        .unwrap();
4336        let Err(refused) = handler.resume(
4337            AgentResume {
4338                clearance: "field".to_owned(),
4339                mission_id: "mission-42".parse().unwrap(),
4340                run_id: RunId::try_new("codex-thread-42").unwrap(),
4341                message: Some("continue".to_owned()),
4342                working_directory: "/work".to_owned(),
4343                environment: theater_environment(),
4344                model: None,
4345                effort: None,
4346                max_cost_micro_usd: None,
4347                project_settings: false,
4348                project_mcp: false,
4349                answer_only: false,
4350                assistant: None,
4351                initial_context: Vec::new(),
4352                overlays: Default::default(),
4353                loadout: Default::default(),
4354            },
4355            terminal.into_object(),
4356        ) else {
4357            panic!("a resumed thread would run its commands on the Station");
4358        };
4359        assert!(refused.to_string().contains("on the Station"), "{refused}");
4360        assert!(
4361            spec.lock().unwrap().is_none(),
4362            "the app server was never started"
4363        );
4364        // A thread with no environment of its own (a desk or answer-only thread) is no such risk.
4365        assert!(refuse_resume_in_theater(&theater_environment(), true).is_ok());
4366        assert!(refuse_resume_in_theater(&BTreeMap::new(), false).is_ok());
4367    }
4368
4369    #[test]
4370    fn resume_reattaches_and_submits_a_turn_to_the_same_provider_thread() {
4371        let run_id = RunId::try_new("codex-thread-42").unwrap();
4372        let terminal = ScriptedTerminal::new(
4373            vec![
4374                b"{\"id\":1,\"result\":{}}\n".to_vec(),
4375                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"codex-thread-42\"}}}\n".to_vec(),
4376                b"{\"id\":3,\"result\":{\"data\":[]}}\n".to_vec(),
4377                b"{\"id\":4,\"result\":{\"turn\":{\"id\":\"turn-1\"}}}\n".to_vec(),
4378            ],
4379            4,
4380        );
4381        let (spec, writes, killed) = (
4382            terminal.spec.clone(),
4383            terminal.writes.clone(),
4384            terminal.killed.clone(),
4385        );
4386        let handler = CodexHandler::try_from(CodexConfig {
4387            executable: "codex-test".to_owned(),
4388            ..CodexConfig::default()
4389        })
4390        .unwrap();
4391        let run = handler
4392            .resume(
4393                AgentResume {
4394                    clearance: "field".to_owned(),
4395                    mission_id: "mission-42".parse().unwrap(),
4396                    run_id: run_id.clone(),
4397                    message: Some("continue the same Run".to_owned()),
4398                    working_directory: "C:\\station\\mission-42".to_owned(),
4399                    environment: BTreeMap::from([("TOKEN".to_owned(), "fresh".to_owned())]),
4400                    model: Some("gpt-5".to_owned()),
4401                    effort: Some("high".to_owned()),
4402                    max_cost_micro_usd: None,
4403                    project_settings: false,
4404                    project_mcp: false,
4405                    answer_only: false,
4406                    assistant: None,
4407                    initial_context: Vec::new(),
4408                    overlays: Default::default(),
4409                    loadout: Default::default(),
4410                },
4411                terminal.into_object(),
4412            )
4413            .unwrap();
4414
4415        assert_eq!(run.session_id().unwrap(), Some(run_id.to_string()));
4416
4417        let spec = spec.lock().unwrap().clone().unwrap();
4418        assert_eq!(
4419            spec.argv,
4420            [
4421                vec!["codex-test".to_owned(), "app-server".to_owned()],
4422                untrusted_project("C:\\station\\mission-42").to_vec(),
4423            ]
4424            .concat()
4425        );
4426        assert_eq!(spec.cwd.as_deref(), Some("C:\\station\\mission-42"));
4427        assert_eq!(
4428            spec.env.as_ref().unwrap().get("TOKEN").map(String::as_str),
4429            Some("fresh")
4430        );
4431
4432        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4433        let messages = written
4434            .lines()
4435            .map(|line| serde_json::from_str::<Value>(line).unwrap())
4436            .collect::<Vec<_>>();
4437        assert_eq!(messages[0]["method"], "initialize");
4438        assert_eq!(messages[1]["method"], "initialized");
4439        assert_eq!(messages[2]["method"], "thread/resume");
4440        assert_eq!(messages[2]["params"]["threadId"], "codex-thread-42");
4441        assert_eq!(messages[2]["params"]["excludeTurns"], true);
4442        assert_eq!(messages[2]["params"]["model"], "gpt-5");
4443        assert_eq!(messages[2]["params"]["cwd"], "C:\\station\\mission-42");
4444        assert_eq!(messages[3]["method"], "skills/list");
4445        assert_eq!(messages[4]["method"], "turn/start");
4446        assert_eq!(messages[4]["params"]["threadId"], "codex-thread-42");
4447        assert_eq!(messages[4]["params"]["effort"], "high");
4448        assert_eq!(
4449            messages[4]["params"]["input"][0]["text"],
4450            "continue the same Run"
4451        );
4452        assert!(!killed.load(Ordering::Acquire));
4453    }
4454
4455    /// A resumed Run whose app server answers the requests in order with `answers`.
4456    fn resumed_with(
4457        answers: Vec<Vec<u8>>,
4458        expected: usize,
4459    ) -> (Object<dyn AgentSession>, Arc<Mutex<Vec<u8>>>) {
4460        let terminal = ScriptedTerminal::new(answers, expected);
4461        let writes = terminal.writes.clone();
4462        let handler = CodexHandler::try_from(CodexConfig {
4463            executable: "codex-test".to_owned(),
4464            ..CodexConfig::default()
4465        })
4466        .unwrap();
4467        let run = handler
4468            .resume(
4469                AgentResume {
4470                    clearance: "field".to_owned(),
4471                    mission_id: "mission-42".parse().unwrap(),
4472                    run_id: RunId::try_new("codex-thread-42").unwrap(),
4473                    message: None,
4474                    working_directory: "C:\\station\\mission-42".to_owned(),
4475                    environment: BTreeMap::new(),
4476                    model: None,
4477                    effort: None,
4478                    max_cost_micro_usd: None,
4479                    project_settings: false,
4480                    project_mcp: false,
4481                    answer_only: false,
4482                    assistant: None,
4483                    initial_context: Vec::new(),
4484                    overlays: Default::default(),
4485                    loadout: Default::default(),
4486                },
4487                terminal.into_object(),
4488            )
4489            .unwrap();
4490        (run, writes)
4491    }
4492
4493    fn lines_of(messages: &[Value]) -> Vec<u8> {
4494        let mut out = Vec::new();
4495        for message in messages {
4496            out.extend_from_slice(message.to_string().as_bytes());
4497            out.push(b'\n');
4498        }
4499        out
4500    }
4501
4502    fn usage(last: u64) -> Value {
4503        json!({"method": "thread/tokenUsage/updated", "params": {
4504            "threadId": "codex-thread-42", "turnId": "turn-c",
4505            "tokenUsage": {"total": {"totalTokens": 99999, "inputTokens": 99999},
4506                "last": {"totalTokens": last, "inputTokens": last, "outputTokens": 0},
4507                "modelContextWindow": 190000}}})
4508    }
4509
4510    /// `thread/compact/start` answers `{}` at once and the compaction is a turn of its own with
4511    /// one `contextCompaction` item; Codex 0.166.0 counts the thread's context again before the
4512    /// item completes (the lines are what it wrote, cut to what the handler reads).
4513    #[test]
4514    fn a_compaction_asks_the_thread_and_counts_the_tokens_before_and_after() {
4515        let answer = [
4516            json!({"id": 4, "result": {}}),
4517            json!({"method": "turn/started", "params": {"threadId": "codex-thread-42", "turn": {"id": "turn-c"}}}),
4518            usage(28857),
4519            json!({"method": "item/started", "params": {"item": {"type": "contextCompaction", "id": "c1"}}}),
4520            usage(34965),
4521            usage(14185),
4522            json!({"method": "item/completed", "params": {"item": {"type": "contextCompaction", "id": "c1"}}}),
4523            json!({"method": "turn/completed", "params": {"turn": {"id": "turn-c", "status": "completed"}}}),
4524        ];
4525        let (run, writes) = resumed_with(
4526            vec![
4527                b"{\"id\":1,\"result\":{}}\n".to_vec(),
4528                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"codex-thread-42\"}}}\n".to_vec(),
4529                b"{\"id\":3,\"result\":{\"data\":[]}}\n".to_vec(),
4530                lines_of(&answer),
4531            ],
4532            4,
4533        );
4534        run.send_message(AgentMessage {
4535            text: SessionCommand::Compact {
4536                focus: Some("ignored: the request takes none".to_owned()),
4537            }
4538            .encode(),
4539        })
4540        .unwrap();
4541        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4542        let request = written
4543            .lines()
4544            .map(|line| serde_json::from_str::<Value>(line).unwrap())
4545            .find(|message| message["method"] == "thread/compact/start")
4546            .expect("the compaction is asked of the thread");
4547        assert_eq!(request["params"], json!({"threadId": "codex-thread-42"}));
4548
4549        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4550        let compacted = events
4551            .iter()
4552            .find(|event| event.kind == ai6::COMPACTED_EVENT)
4553            .expect("the compaction is an event");
4554        let change = SessionChange::of(compacted).unwrap();
4555        assert_eq!(change.trigger.as_deref(), Some("manual"));
4556        assert_eq!(
4557            (change.tokens_before, change.tokens_after),
4558            (Some(28857), Some(14185))
4559        );
4560        let kinds = events.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>();
4561        let at = |kind: &str| kinds.iter().position(|k| *k == kind).unwrap();
4562        assert!(at("item/completed") < at(ai6::COMPACTED_EVENT));
4563        assert!(at(ai6::COMPACTED_EVENT) < at("completed"));
4564    }
4565
4566    /// A turn the Station asked to compact that ends with no compaction says why, before it ends.
4567    #[test]
4568    fn a_compaction_turn_that_does_not_compact_is_reported_before_it_ends() {
4569        let answer = [
4570            json!({"id": 4, "result": {}}),
4571            json!({"method": "turn/completed", "params": {"turn": {"id": "turn-c", "status": "failed",
4572                "error": {"message": "context compaction failed"}}}}),
4573        ];
4574        let (run, _writes) = resumed_with(
4575            vec![
4576                b"{\"id\":1,\"result\":{}}\n".to_vec(),
4577                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"codex-thread-42\"}}}\n".to_vec(),
4578                b"{\"id\":3,\"result\":{\"data\":[]}}\n".to_vec(),
4579                lines_of(&answer),
4580            ],
4581            4,
4582        );
4583        run.send_message(AgentMessage {
4584            text: SessionCommand::Compact { focus: None }.encode(),
4585        })
4586        .unwrap();
4587        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4588        let kinds = events.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>();
4589        assert_eq!(kinds.first().copied(), Some(ai6::COMPACT_FAILED_EVENT));
4590        assert_eq!(events[0].text.as_deref(), Some("context compaction failed"));
4591        assert!(!kinds.contains(&ai6::COMPACTED_EVENT));
4592    }
4593
4594    /// A clear is `thread/start` on the same app server: the Run takes the new thread, which the
4595    /// next message is a turn of, and the old thread's token count is forgotten.
4596    #[test]
4597    fn a_clear_opens_another_thread_on_the_same_app_server() {
4598        let (run, writes) = resumed_with(
4599            vec![
4600                b"{\"id\":1,\"result\":{}}\n".to_vec(),
4601                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"codex-thread-42\"}}}\n".to_vec(),
4602                b"{\"id\":3,\"result\":{\"data\":[]}}\n".to_vec(),
4603                b"{\"id\":4,\"result\":{\"thread\":{\"id\":\"codex-thread-43\"}}}\n".to_vec(),
4604                b"{\"id\":5,\"result\":{}}\n".to_vec(),
4605            ],
4606            5,
4607        );
4608        assert_eq!(
4609            run.session_id().unwrap().as_deref(),
4610            Some("codex-thread-42")
4611        );
4612        run.send_message(AgentMessage {
4613            text: SessionCommand::Clear.encode(),
4614        })
4615        .unwrap();
4616        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4617        let kinds = events.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>();
4618        assert_eq!(kinds, [ai6::CLEARED_EVENT, "completed"], "{events:?}");
4619        let change = SessionChange::of(&events[0]).unwrap();
4620        assert_eq!(change.session_id.as_deref(), Some("codex-thread-43"));
4621        assert_eq!(
4622            run.session_id().unwrap().as_deref(),
4623            Some("codex-thread-43")
4624        );
4625        run.send_message(AgentMessage {
4626            text: "after the clear".to_owned(),
4627        })
4628        .unwrap();
4629        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4630        let messages = written
4631            .lines()
4632            .map(|line| serde_json::from_str::<Value>(line).unwrap())
4633            .collect::<Vec<_>>();
4634        assert!(
4635            messages
4636                .iter()
4637                .any(|message| message["method"] == "thread/start")
4638        );
4639        let turn = messages
4640            .iter()
4641            .find(|message| message["method"] == "turn/start")
4642            .expect("the next message is a turn");
4643        assert_eq!(turn["params"]["threadId"], "codex-thread-43");
4644        let handler = CodexHandler::try_from(CodexConfig::default()).unwrap();
4645        let commands = handler.session_commands().unwrap();
4646        assert!(commands.compact && commands.clear);
4647    }
4648
4649    /// The app server's replies as ConPTY renders them on Windows: mode and title sequences
4650    /// first, CRLF line ends, a cursor move between lines, and a reply longer than the
4651    /// terminal broken with CRLF and a cursor move.
4652    #[test]
4653    fn replies_rendered_by_conpty_read_as_the_lines_codex_wrote() {
4654        let delta = "d".repeat(5_000);
4655        let notification = format!(
4656            "{{\"method\":\"item/agentMessage/delta\",\"params\":{{\"delta\":\"{delta}\"}}}}"
4657        );
4658        let (head, tail) = notification.split_at(2_000);
4659        let input =
4660            b"\x1b[?9001h\x1b[?1004h\x1b[m\x1b]0;C:\\bin\\codex.exe\x07\x1b[?25h\r\n".to_vec();
4661        let mut first = input;
4662        let mut second =
4663            b"\x1b[5;1H{\"id\":2,\"result\":{\"thread\":{\"id\":\"codex-thread-42\"}}}\r\n"
4664                .to_vec();
4665        second.extend_from_slice(head.as_bytes());
4666        second.extend_from_slice(b"\r\n\x1b[23;2000H");
4667        second.extend_from_slice(tail.as_bytes());
4668        second.extend_from_slice(b"\r\n");
4669        first.extend_from_slice(b"{\"id\":1,\"result\":{}}\r\n\x1b[?25l");
4670        let terminal = ScriptedTerminal::new(vec![first, second], 2);
4671        let spec = terminal.spec.clone();
4672        let handler = CodexHandler::try_from(CodexConfig {
4673            executable: "codex-test".to_owned(),
4674            ..CodexConfig::default()
4675        })
4676        .unwrap();
4677        let run = handler
4678            .resume(
4679                AgentResume {
4680                    clearance: "field".to_owned(),
4681                    mission_id: "mission-42".parse().unwrap(),
4682                    run_id: RunId::try_new("codex-thread-42").unwrap(),
4683                    message: None,
4684                    working_directory: "C:\\station\\mission-42".to_owned(),
4685                    environment: BTreeMap::new(),
4686                    model: None,
4687                    effort: None,
4688                    max_cost_micro_usd: None,
4689                    project_settings: false,
4690                    project_mcp: false,
4691                    answer_only: false,
4692                    assistant: None,
4693                    initial_context: Vec::new(),
4694                    overlays: Default::default(),
4695                    loadout: Default::default(),
4696                },
4697                terminal.into_object(),
4698            )
4699            .unwrap();
4700        let event = run.next_event(50).unwrap().unwrap();
4701        assert_eq!(
4702            (event.kind.as_str(), event.text.as_deref()),
4703            ("text", Some(&*delta))
4704        );
4705        assert_eq!(spec.lock().unwrap().as_ref().unwrap().cols, STREAM_COLS);
4706    }
4707
4708    #[test]
4709    fn resume_rejects_a_different_thread_and_closes_the_provider_process() {
4710        let terminal = ScriptedTerminal::new(
4711            vec![
4712                b"{\"id\":1,\"result\":{}}\n".to_vec(),
4713                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"different-thread\"}}}\n".to_vec(),
4714            ],
4715            2,
4716        );
4717        let killed = terminal.killed.clone();
4718        let handler = CodexHandler::try_from(CodexConfig {
4719            executable: "codex-test".to_owned(),
4720            ..CodexConfig::default()
4721        })
4722        .unwrap();
4723
4724        let result = handler.resume(
4725            AgentResume {
4726                clearance: "field".to_owned(),
4727                mission_id: "mission-42".parse().unwrap(),
4728                run_id: RunId::try_new("codex-thread-42").unwrap(),
4729                message: None,
4730                working_directory: "C:\\station\\mission-42".to_owned(),
4731                environment: BTreeMap::new(),
4732                model: None,
4733                effort: None,
4734                max_cost_micro_usd: None,
4735                project_settings: false,
4736                project_mcp: false,
4737                answer_only: false,
4738                assistant: None,
4739                initial_context: Vec::new(),
4740                overlays: Default::default(),
4741                loadout: Default::default(),
4742            },
4743            terminal.into_object(),
4744        );
4745
4746        assert!(result.is_err());
4747        assert!(killed.load(Ordering::Acquire));
4748    }
4749
4750    #[test]
4751    fn delta_fixture_maps_to_text_without_losing_provider_data() {
4752        let message = json!({
4753            "method": "item/agentMessage/delta",
4754            "params": { "delta": "hello from Codex" }
4755        });
4756        let event = decoded(&message, None).unwrap();
4757        assert_eq!(event.kind, "text");
4758        assert_eq!(event.text.as_deref(), Some("hello from Codex"));
4759        assert_eq!(
4760            serde_json::from_slice::<Value>(event.data.as_deref().unwrap()).unwrap(),
4761            message
4762        );
4763    }
4764
4765    #[test]
4766    fn a_usage_limit_error_becomes_a_limit_with_the_reset_it_names() {
4767        let message = json!({
4768            "method": "error",
4769            "params": {
4770                "error": {
4771                    "message": "You've hit your usage limit.",
4772                    "codexErrorInfo": "usageLimitExceeded",
4773                    "resetsAt": 1_790_000_000
4774                },
4775                "willRetry": false
4776            }
4777        });
4778        let event = decoded(&message, None).unwrap();
4779        assert_eq!(event.kind, LIMIT_EVENT);
4780        assert_eq!(event.text.as_deref(), Some("You've hit your usage limit."));
4781        let limit = event.limit.unwrap();
4782        assert_eq!(limit.resets_at, Some(1_790_000_000));
4783        assert_eq!(limit.kind, Some(LimitKind::UsageQuota));
4784        assert_eq!(limit.continuable, Some(true));
4785    }
4786
4787    #[test]
4788    fn a_rate_limit_error_is_a_rate_limit_that_another_account_meets_differently() {
4789        let message = json!({
4790            "method": "error",
4791            "params": { "error": {
4792                "message": "too many requests, try again in 90 seconds",
4793                "codexErrorInfo": "rate_limit_exceeded"
4794            } }
4795        });
4796        let limit = decoded(&message, None).unwrap().limit.unwrap();
4797        assert_eq!(limit.kind, Some(LimitKind::RateLimit));
4798        assert!(limit.can_continue());
4799    }
4800
4801    #[test]
4802    fn a_failed_turn_with_a_usage_limit_uses_the_exhausted_window_for_the_reset() {
4803        let snapshot = json!({
4804            "method": "account/rateLimits/updated",
4805            "params": { "rateLimits": {
4806                "primary": { "usedPercent": 100.0, "windowDurationMins": 300, "resetsAt": 1_790_000_000 },
4807                "secondary": { "usedPercent": 40.0, "windowDurationMins": 10_080, "resetsAt": 1_790_500_000 }
4808            } }
4809        });
4810        let hint = exhausted_window(&read_message(&snapshot)).unwrap();
4811        assert_eq!(hint.bucket.as_deref(), Some("five_hour"));
4812
4813        let failed = json!({
4814            "method": "turn/completed",
4815            "params": { "turn": { "status": "failed", "error": {
4816                "message": "usage limit",
4817                "codexErrorInfo": "usage_limit_exceeded"
4818            } } }
4819        });
4820        let event = decoded(&failed, Some(&hint)).unwrap();
4821        assert_eq!(event.kind, LIMIT_EVENT);
4822        let limit = event.limit.unwrap();
4823        assert_eq!(limit.resets_at, Some(1_790_000_000));
4824        assert_eq!(limit.bucket.as_deref(), Some("five_hour"));
4825        assert_eq!(
4826            decoded(&failed, None).unwrap().limit.unwrap().resets_at,
4827            None
4828        );
4829    }
4830
4831    #[test]
4832    fn every_rate_limit_snapshot_reports_its_windows_as_quota() {
4833        let snapshot = json!({
4834            "method": "account/rateLimits/updated",
4835            "params": { "rateLimits": {
4836                "primary": { "usedPercent": 42.5, "windowDurationMins": 300, "resetsAt": 1_790_000_000 },
4837                "secondary": { "usedPercent": 40.0, "windowDurationMins": 10_080, "resetsAt": 1_790_500_000 }
4838            } }
4839        });
4840        let event = decoded(&snapshot, None).unwrap();
4841        assert_eq!(event.kind, "account/rateLimits/updated");
4842        let quota = event.report.unwrap().buckets;
4843        assert_eq!(
4844            quota
4845                .iter()
4846                .map(|bucket| (
4847                    bucket.id.as_str(),
4848                    UsageReport::fraction_permille(bucket),
4849                    bucket.refill.clone()
4850                ))
4851                .collect::<Vec<_>>(),
4852            [
4853                (
4854                    "five_hour",
4855                    Some(425),
4856                    Refill::FixedWindow {
4857                        length: Some(std::time::Duration::from_secs(300 * 60)),
4858                        resets_at: Some(1_790_000_000)
4859                    }
4860                ),
4861                (
4862                    "weekly",
4863                    Some(400),
4864                    Refill::FixedWindow {
4865                        length: Some(std::time::Duration::from_secs(10_080 * 60)),
4866                        resets_at: Some(1_790_500_000)
4867                    }
4868                ),
4869            ]
4870        );
4871        let partial = json!({
4872            "method": "account/rateLimits/updated",
4873            "params": { "rateLimits": { "primary": { "usedPercent": 99.0, "resetsAt": 1 } } }
4874        });
4875        let quota = decoded(&partial, None).unwrap().report.unwrap().buckets;
4876        assert_eq!(quota.len(), 1);
4877        assert_eq!(
4878            quota[0].id, "primary",
4879            "an unnamed window keeps its position"
4880        );
4881        assert_eq!(UsageReport::fraction_permille(&quota[0]), Some(990));
4882        let other = json!({ "method": "turn/completed", "params": {} });
4883        assert!(decoded(&other, None).unwrap().report.is_none());
4884    }
4885
4886    #[test]
4887    fn a_usage_snapshot_below_the_limit_and_other_errors_are_not_limits() {
4888        let below = json!({
4889            "method": "account/rateLimits/updated",
4890            "params": { "rateLimits": { "primary": { "usedPercent": 99.0, "resetsAt": 1 } } }
4891        });
4892        assert_eq!(exhausted_window(&read_message(&below)), None);
4893        let other = json!({
4894            "method": "error",
4895            "params": { "error": { "message": "boom", "codexErrorInfo": "internalServerError" } }
4896        });
4897        let event = decoded(&other, None).unwrap();
4898        assert_eq!(event.kind, "error");
4899        assert_eq!(event.limit, None);
4900    }
4901
4902    #[test]
4903    fn a_token_cap_refusal_that_will_retry_fails_the_turn_with_the_gateways_words() {
4904        let words = "400 Request rejected: Current cap is 300000 tokens";
4905        let capped = json!({
4906            "method": "error",
4907            "params": {
4908                "error": { "message": words, "codexErrorInfo": "badRequest" },
4909                "willRetry": true
4910            }
4911        });
4912        let event = decoded(&capped, None).unwrap();
4913        assert_eq!(event.kind, "failed");
4914        assert_eq!(event.text.as_deref(), Some(words));
4915        let transient = json!({
4916            "method": "error",
4917            "params": {
4918                "error": { "message": "stream disconnected", "codexErrorInfo": "other" },
4919                "willRetry": true
4920            }
4921        });
4922        assert_eq!(decoded(&transient, None).unwrap().kind, "error");
4923    }
4924
4925    #[test]
4926    fn turn_completed_fixture_maps_to_completed() {
4927        let event = decoded(&json!({ "method": "turn/completed", "params": {} }), None).unwrap();
4928        assert_eq!(event.kind, "completed");
4929    }
4930
4931    #[test]
4932    fn a_start_from_a_ledger_that_fails_leaves_no_rollout_behind() {
4933        let codex_home = tempfile::tempdir().unwrap();
4934        let ledger = ai6::StartLedger::from_text(&format!("{}\n", [r#"{"format":"coqui-acp-history","version":1,"id":"5f0f6d6e-3f3c-4f1a-8a52-1c1e6f0b9a77","origin":{"harness":"claude"}}"#,
4935                r#"{"method":"session/prompt","params":{"prompt":[{"type":"text","text":"fix the parser"}]}}"#,
4936                r#"{"method":"history/turn_end","params":{"stopReason":"end_turn"}}"#,
4937            ].join("\n"))).unwrap();
4938        let handler = CodexHandler::try_from(CodexConfig {
4939            executable: "codex-test".to_owned(),
4940            ..CodexConfig::default()
4941        })
4942        .unwrap();
4943        let terminal = ScriptedTerminal::new(Vec::new(), 1).ending(Ending::Eof);
4944        let request = AgentStart {
4945            mission_id: "mission-42".parse().unwrap(),
4946            agent_id: "007".to_owned(),
4947            prompt: "continue".to_owned(),
4948            initial_context: Vec::new(),
4949            working_directory: "/work".to_owned(),
4950            clearance: "field".to_owned(),
4951            environment: BTreeMap::from([(
4952                "CODEX_HOME".to_owned(),
4953                codex_home.path().to_string_lossy().into_owned(),
4954            )]),
4955            model: None,
4956            effort: None,
4957            max_cost_micro_usd: None,
4958            project_settings: false,
4959            project_mcp: false,
4960            answer_only: false,
4961            assistant: None,
4962            overlays: Default::default(),
4963            loadout: Default::default(),
4964            ledger: Some(ledger),
4965        };
4966        assert!(handler.start(request, terminal.into_object()).is_err());
4967        let sessions = codex_home.path().join("sessions");
4968        let mut left = Vec::new();
4969        let mut pending = vec![sessions];
4970        while let Some(directory) = pending.pop() {
4971            for entry in std::fs::read_dir(directory).into_iter().flatten().flatten() {
4972                if entry.path().is_dir() {
4973                    pending.push(entry.path());
4974                } else {
4975                    left.push(entry.path());
4976                }
4977            }
4978        }
4979        assert!(left.is_empty(), "{left:?}");
4980    }
4981
4982    #[test]
4983    fn terminal_eof_is_a_provider_failure_not_an_idle_timeout() {
4984        let config = CodexConfig::default();
4985        let terminal = ScriptedTerminal::new(Vec::new(), 1).ending(Ending::Eof);
4986        let error = open_on(terminal, &config)
4987            .err()
4988            .expect("an app server with no output is not a thread")
4989            .to_string();
4990
4991        assert!(error.contains("closed its terminal"), "{error}");
4992    }
4993
4994    #[test]
4995    fn an_app_server_that_exits_fails_the_run_with_its_status_and_last_output() {
4996        // Behind a terminal that keeps its output open (ConPTY): it exits after its thread opened.
4997        let terminal = ScriptedTerminal::new(
4998            vec![
4999                b"{\"id\":1,\"result\":{}}\n".to_vec(),
5000                b"{\"id\":2,\"result\":{\"thread\":{\"id\":\"t\"}}}\nerror: unknown model \"nope\"\r\n"
5001                    .to_vec(),
5002            ],
5003            2,
5004        )
5005        .ending(Ending::Exited(2));
5006        let config = CodexConfig::default();
5007        let run = open_on(terminal, &config).unwrap();
5008        let output = run.next_event(2_000).unwrap().unwrap();
5009        assert_eq!(output.kind, "output");
5010        let failed = run.next_event(2_000).unwrap().unwrap();
5011        assert_eq!(failed.kind, "failed");
5012        let reason = failed.text.unwrap();
5013        assert!(reason.contains("exited with code 2"), "{reason}");
5014        assert!(reason.contains("unknown model"), "{reason}");
5015        assert_eq!(run.next_event(100).unwrap(), None, "reported once");
5016
5017        // And one that exits before its thread opened is why the start failed.
5018        let terminal =
5019            ScriptedTerminal::new(vec![b"error: unknown model \"nope\"\r\n".to_vec()], 1)
5020                .ending(Ending::Exited(2));
5021        let error = open_on(terminal, &config)
5022            .err()
5023            .expect("no thread opened")
5024            .to_string();
5025        assert!(error.contains("exited with code 2"), "{error}");
5026        assert!(error.contains("unknown model"), "{error}");
5027    }
5028
5029    #[test]
5030    fn the_configured_tail_bounds_what_a_failed_run_quotes() {
5031        let config = CodexConfig {
5032            tail_lines: 2,
5033            tail_line_bytes: 4,
5034            ..CodexConfig::default()
5035        };
5036        let terminal =
5037            ScriptedTerminal::new(vec![b"one one\r\ntwo two\r\nthree three\r\n".to_vec()], 1)
5038                .ending(Ending::Exited(1));
5039        let reason = open_on(terminal, &config)
5040            .err()
5041            .expect("no thread opened")
5042            .to_string();
5043        let reason = reason.trim_end_matches(" (GUATIAO_ERR_INTERNAL)");
5044        assert!(reason.ends_with("its last output:\ntwo \nthre"), "{reason}");
5045    }
5046
5047    #[test]
5048    fn the_configured_size_bounds_an_assistants_context_file() {
5049        let directory = tempfile::tempdir().unwrap();
5050        let file = directory.path().join("context.md");
5051        std::fs::write(&file, "twelve bytes").unwrap();
5052        let mut mode = AssistantMode::moneypenny();
5053        mode.context_file = Some(file.to_string_lossy().into_owned());
5054
5055        let error = assistant_instructions(&mode, Scripts::None, 11).unwrap_err();
5056        assert!(error.to_string().contains("more than 11"), "{error}");
5057        let told = assistant_instructions(&mode, Scripts::None, 12).unwrap();
5058        assert!(told.iter().any(|part| part == "twelve bytes"), "{told:?}");
5059    }
5060
5061    #[test]
5062    fn remote_hands_adds_the_theater_server_and_a_read_only_sandbox() {
5063        let environment = std::collections::BTreeMap::from([
5064            (
5065                "AI6_THEATER_MCP_URL".to_owned(),
5066                "http://127.0.0.1:43211/mcp".to_owned(),
5067            ),
5068            (
5069                "AI6_THEATER_MCP_TOKEN".to_owned(),
5070                "theater-secret-token".to_owned(),
5071            ),
5072        ]);
5073        assert!(is_remote_hands(&environment));
5074        assert!(!is_remote_hands(&std::collections::BTreeMap::new()));
5075
5076        let argv = app_server_argv("codex", &environment);
5077        assert!(argv.iter().any(|argument| {
5078            argument == "mcp_servers.ai6-theater.url=\"http://127.0.0.1:43211/mcp\""
5079        }));
5080        assert!(argv.iter().any(|argument| {
5081            argument == "mcp_servers.ai6-theater.bearer_token_env_var=\"AI6_THEATER_MCP_TOKEN\""
5082        }));
5083        assert!(argv.iter().any(|argument| {
5084            argument == "mcp_servers.ai6-theater.default_tools_approval_mode=\"approve\""
5085        }));
5086        assert!(
5087            argv.iter()
5088                .all(|argument| !argument.contains("theater-secret-token"))
5089        );
5090
5091        assert!(
5092            argv.iter()
5093                .any(|argument| argument == "features.shell_tool=false"),
5094            "on Linux its read-only sandbox lets a command read any file of the Station: {argv:?}"
5095        );
5096        assert!(
5097            !app_server_argv("codex", &std::collections::BTreeMap::new())
5098                .iter()
5099                .any(|argument| argument == "features.shell_tool=false"),
5100            "a field Run on the Station keeps its commands"
5101        );
5102
5103        let mut params = ThreadPolicy::default();
5104        restrict_to_remote_hands(&mut params);
5105        assert_eq!(params.sandbox, Some("read-only"));
5106        assert_eq!(params.approval_policy, Some("never"));
5107    }
5108
5109    /// Codex reads `projects.<path>.trust_level` (`trusted` or `untrusted`), and an untrusted
5110    /// project skips its `.codex/` layer: config, hooks and rules (Codex config reference).
5111    #[test]
5112    fn an_ignored_project_is_marked_untrusted_in_one_inline_table() {
5113        let [flag, value] = untrusted_project("C:\\safe houses\\m.1");
5114        assert_eq!(flag, "-c");
5115        let (key, table) = value.split_once('=').unwrap();
5116        assert_eq!(key, "projects", "no dotted key for a path that holds dots");
5117        let parsed: toml::Table = toml::from_str(&format!("projects = {table}")).unwrap();
5118        assert_eq!(
5119            parsed["projects"]["C:\\safe houses\\m.1"]["trust_level"].as_str(),
5120            Some("untrusted")
5121        );
5122    }
5123
5124    /// `mcp_servers.<name>.url` and `bearer_token_env_var` are Codex's streamable HTTP server
5125    /// keys, and `sandbox`, `approvalPolicy` and `config` are `thread/start` and
5126    /// `thread/resume` parameters, as the app-server schema this handler already speaks has
5127    /// them.
5128    #[test]
5129    fn an_assistant_thread_has_only_its_mcp_servers_read_only_on_start_and_resume() {
5130        let terminal = ProcessTerminal::new();
5131        let run_id = RunId::try_new("codex-assistant-thread").unwrap();
5132        let environment = BTreeMap::from([
5133            ("CODEX_FIXTURE_THREAD_ID".to_owned(), run_id.to_string()),
5134            ("CODEX_FIXTURE_SHOW_POLICY".to_owned(), "1".to_owned()),
5135            (
5136                "AI6_MONEYPENNY_MCP_URL".to_owned(),
5137                "https://exports.example/v1/moneypenny/mcp".to_owned(),
5138            ),
5139            (
5140                "AI6_MONEYPENNY_MCP_TOKEN".to_owned(),
5141                "conversation-token".to_owned(),
5142            ),
5143            (
5144                "AI6_CABLE_MCP_URL".to_owned(),
5145                "http://127.0.0.1:1/mcp".to_owned(),
5146            ),
5147            ("AI6_CABLE_MCP_TOKEN".to_owned(), "cable-token".to_owned()),
5148            (
5149                "CODEX_FIXTURE_MCP_LIST".to_owned(),
5150                MCP_LIST_ASSISTANT.replace('\n', ""),
5151            ),
5152        ]);
5153        let handler = CodexHandler::try_from(CodexConfig {
5154            executable: "codex-assistant-fixture".to_owned(),
5155            ..CodexConfig::default()
5156        })
5157        .unwrap();
5158        let cwd = std::env::current_dir()
5159            .unwrap()
5160            .to_string_lossy()
5161            .into_owned();
5162        let started = handler
5163            .start(
5164                AgentStart {
5165                    mission_id: "assistant-conversation".parse().unwrap(),
5166                    agent_id: "moneypenny".to_owned(),
5167                    prompt: "Which Stations are busy?".to_owned(),
5168                    initial_context: vec!["You are Moneypenny.".to_owned()],
5169                    working_directory: cwd.clone(),
5170                    clearance: "desk".to_owned(),
5171                    environment: environment.clone(),
5172                    model: None,
5173                    effort: None,
5174                    max_cost_micro_usd: None,
5175                    project_settings: true,
5176                    project_mcp: true,
5177                    answer_only: false,
5178                    assistant: Some(AssistantMode::moneypenny()),
5179                    overlays: Default::default(),
5180                    loadout: Default::default(),
5181                    ledger: None,
5182                },
5183                terminal.clone().into_object(),
5184            )
5185            .unwrap();
5186        let started_events = read_to_completion(&started);
5187        started.close().unwrap();
5188        let resumed = handler
5189            .resume(
5190                AgentResume {
5191                    clearance: "desk".to_owned(),
5192                    mission_id: "assistant-conversation".parse().unwrap(),
5193                    run_id,
5194                    message: Some("And now?".to_owned()),
5195                    working_directory: cwd.clone(),
5196                    environment,
5197                    model: None,
5198                    effort: None,
5199                    max_cost_micro_usd: None,
5200                    project_settings: true,
5201                    project_mcp: true,
5202                    answer_only: false,
5203                    assistant: Some(AssistantMode::moneypenny()),
5204                    initial_context: Vec::new(),
5205                    overlays: Default::default(),
5206                    loadout: Default::default(),
5207                },
5208                terminal.clone().into_object(),
5209            )
5210            .unwrap();
5211        let resumed_events = read_to_completion(&resumed);
5212        resumed.close().unwrap();
5213        for events in [started_events, resumed_events] {
5214            let policy = events
5215                .iter()
5216                .find_map(|event| event.text.as_deref()?.strip_prefix("policy: "))
5217                .expect("the thread's policy was reported");
5218            let policy: Value = serde_json::from_str(policy).unwrap();
5219            assert_eq!(policy["sandbox"], "read-only");
5220            assert_eq!(policy["approvalPolicy"], "never");
5221            assert_eq!(policy["config"]["web_search"], "disabled");
5222        }
5223        let all_specs = terminal.specs.lock().unwrap();
5224        let specs = all_specs
5225            .iter()
5226            .filter(|spec| spec.argv[1] == "app-server")
5227            .collect::<Vec<_>>();
5228        assert_eq!(specs.len(), 2);
5229        let settings = [
5230            vec![
5231                "-c".to_owned(),
5232                "mcp_servers={moneypenny={url=\"https://exports.example/v1/moneypenny/mcp\",\
5233                 bearer_token_env_var=\"AI6_MONEYPENNY_MCP_TOKEN\",\
5234                 default_tools_approval_mode=\"approve\"}}"
5235                    .to_owned(),
5236            ],
5237            no_built_in_tools(false),
5238            vec!["-c".to_owned(), "project_doc_max_bytes=0".to_owned()],
5239            untrusted_project(&cwd).to_vec(),
5240        ]
5241        .concat();
5242        // The fixture's feature list enables code_mode_host, secret_auth_storage and
5243        // tool_suggest; the kept one stays on. Codex lists the user's node_repl beside the
5244        // thread's own server.
5245        let features_off = [
5246            "-c",
5247            "features.code_mode_host=false",
5248            "-c",
5249            "features.tool_suggest=false",
5250        ]
5251        .map(str::to_owned);
5252        let switched_off = [
5253            features_off.to_vec(),
5254            vec![
5255                "-c".to_owned(),
5256                "mcp_servers.node_repl.enabled=false".to_owned(),
5257            ],
5258        ]
5259        .concat();
5260        let listed = all_specs
5261            .iter()
5262            .find(|spec| spec.argv[1] == "mcp")
5263            .expect("the MCP servers were listed");
5264        assert_eq!(
5265            listed.argv[1..],
5266            [
5267                vec!["mcp".to_owned(), "list".to_owned(), "--json".to_owned()],
5268                settings.clone(),
5269                features_off.to_vec()
5270            ]
5271            .concat(),
5272            "with the thread's settings and features"
5273        );
5274        let expected = [
5275            vec![
5276                "codex-assistant-fixture".to_owned(),
5277                "app-server".to_owned(),
5278            ],
5279            settings.clone(),
5280            switched_off.to_vec(),
5281        ]
5282        .concat();
5283        let checked = all_specs
5284            .iter()
5285            .find(|spec| spec.argv.len() > 2 && spec.argv[1..3] == ["debug", "prompt-input"])
5286            .expect("the tools were checked");
5287        assert_eq!(
5288            checked.argv[3..],
5289            [settings, switched_off.to_vec()].concat(),
5290            "with the app server's own settings"
5291        );
5292        assert_eq!(checked.env, specs[0].env, "and environment");
5293        assert_eq!(checked.cwd, specs[0].cwd, "and working directory");
5294        assert_no_built_in_tools(&specs[0].argv);
5295        assert_no_built_in_tools(&specs[1].argv);
5296        assert_eq!(
5297            specs[0].argv, expected,
5298            "only Moneypenny's server, no Cables"
5299        );
5300        assert_eq!(specs[1].argv, expected, "and so on resume");
5301        let (key, value) = expected[3].split_once('=').unwrap();
5302        let parsed: toml::Table = toml::from_str(&format!("{key} = {value}")).unwrap();
5303        let servers = parsed["mcp_servers"].as_table().unwrap();
5304        assert_eq!(servers.len(), 1);
5305        assert_eq!(
5306            servers["moneypenny"]["bearer_token_env_var"].as_str(),
5307            Some("AI6_MONEYPENNY_MCP_TOKEN")
5308        );
5309        assert!(all_specs.iter().all(|spec| {
5310            spec.argv
5311                .iter()
5312                .all(|argument| !argument.contains("conversation-token"))
5313        }));
5314    }
5315
5316    /// `codex debug prompt-input` of Codex 0.164.0 for an assistant with scripts.
5317    const SCRIPTS_PROMPT: &str =
5318        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-scripts.json");
5319
5320    /// An assistant Run's environment and start request, with `mode`.
5321    fn assistant_start(mode: AssistantMode, prompt: &str) -> AgentStart {
5322        let environment = BTreeMap::from([
5323            (
5324                "CODEX_FIXTURE_THREAD_ID".to_owned(),
5325                "codex-scripts-thread".to_owned(),
5326            ),
5327            ("CODEX_FIXTURE_SHOW_POLICY".to_owned(), "1".to_owned()),
5328            (
5329                "CODEX_FIXTURE_PROMPT_INPUT".to_owned(),
5330                SCRIPTS_PROMPT.replace('\n', ""),
5331            ),
5332            (
5333                "AI6_MONEYPENNY_MCP_URL".to_owned(),
5334                "https://exports.example/v1/moneypenny/mcp".to_owned(),
5335            ),
5336            (
5337                "AI6_MONEYPENNY_MCP_TOKEN".to_owned(),
5338                "conversation-token".to_owned(),
5339            ),
5340        ]);
5341        AgentStart {
5342            mission_id: "assistant--scripts".parse().unwrap(),
5343            agent_id: "moneypenny".to_owned(),
5344            prompt: prompt.to_owned(),
5345            initial_context: vec!["You are Moneypenny.".to_owned()],
5346            working_directory: std::env::current_dir()
5347                .unwrap()
5348                .to_string_lossy()
5349                .into_owned(),
5350            clearance: "desk".to_owned(),
5351            environment,
5352            model: Some("gpt-6.1-sol".to_owned()),
5353            effort: None,
5354            max_cost_micro_usd: None,
5355            project_settings: false,
5356            project_mcp: false,
5357            answer_only: false,
5358            assistant: Some(mode),
5359            overlays: Default::default(),
5360            loadout: Default::default(),
5361            ledger: None,
5362        }
5363    }
5364
5365    fn reported_policy(events: &[AgentEvent]) -> Value {
5366        let policy = events
5367            .iter()
5368            .find_map(|event| event.text.as_deref()?.strip_prefix("policy: "))
5369            .expect("the thread's policy was reported");
5370        serde_json::from_str(policy).unwrap()
5371    }
5372
5373    #[test]
5374    fn an_assistant_with_scripts_runs_them_in_the_sandbox_profile_as_a_weakening() {
5375        let context =
5376            std::env::temp_dir().join(format!("ai6-codex-context-{}.md", std::process::id()));
5377        std::fs::write(&context, "CONTEXT-FILE-MARKER: her memory\n").unwrap();
5378        let mut mode = AssistantMode::moneypenny();
5379        mode.network.policy = "limited".to_owned();
5380        mode.interpreters.push("python3".to_owned());
5381        mode.files = vec!["personal".to_owned(), "scratch".to_owned()];
5382        mode.context_file = Some(context.to_string_lossy().into_owned());
5383        mode.network.allowed_hosts.push("example.com".to_owned());
5384        let handler = CodexHandler::try_from(CodexConfig {
5385            executable: "codex-scripts-fixture".to_owned(),
5386            ..CodexConfig::default()
5387        })
5388        .unwrap();
5389        let terminal = ProcessTerminal::new();
5390        let start = assistant_start(mode.clone(), "Chart it.");
5391        let run = handler
5392            .start(start.clone(), terminal.clone().into_object())
5393            .unwrap();
5394        let events = read_to_completion(&run);
5395        run.close().unwrap();
5396        let _ = std::fs::remove_file(&context);
5397        assert_eq!(events[0].kind, "weakened", "{events:?}");
5398        let weakening = events[0].text.clone().unwrap();
5399        assert!(
5400            weakening.contains("functions.exec and functions.wait")
5401                && weakening.contains("inside Codex's sandbox, not only python3"),
5402            "{weakening}"
5403        );
5404        let policy = reported_policy(&events);
5405        assert_eq!(
5406            policy["sandbox"],
5407            Value::Null,
5408            "the profile decides: {policy}"
5409        );
5410        assert_eq!(policy["approvalPolicy"], "never");
5411        let instructions = policy["developerInstructions"].as_str().unwrap();
5412        assert!(
5413            instructions.starts_with("You are Moneypenny.")
5414                && instructions.contains("CONTEXT-FILE-MARKER: her memory")
5415                && instructions.contains("no network access"),
5416            "{instructions}"
5417        );
5418
5419        let specs = terminal.specs.lock().unwrap();
5420        let server = specs
5421            .iter()
5422            .find(|spec| spec.argv[1] == "app-server")
5423            .unwrap();
5424        let has = |setting: &str| server.argv.iter().any(|argument| argument == setting);
5425        let starts = |prefix: &str| {
5426            server
5427                .argv
5428                .iter()
5429                .any(|argument| argument.starts_with(prefix))
5430        };
5431        assert!(
5432            starts("permissions.ai6_assistant={filesystem={")
5433                && has("default_permissions=\"ai6_assistant\"")
5434                && starts("shell_environment_policy.include_only=[")
5435                && has("project_doc_max_bytes=0"),
5436            "{:?}",
5437            server.argv
5438        );
5439        assert_eq!(has("windows.sandbox=\"mxc\""), cfg!(windows));
5440        assert!(
5441            !has("features.shell_tool=false") && !has("features.code_mode_host=false"),
5442            "exec and its command tools stay on: {:?}",
5443            server.argv
5444        );
5445        assert!(has("features.tool_suggest=false"), "other features go");
5446        let checked = specs
5447            .iter()
5448            .find(|spec| spec.argv.len() > 2 && spec.argv[1..3] == ["debug", "prompt-input"])
5449            .unwrap();
5450        assert!(
5451            !checked
5452                .argv
5453                .iter()
5454                .any(|a| a == "features.shell_tool=false")
5455        );
5456        drop(specs);
5457
5458        let resumed = handler
5459            .resume(
5460                AgentResume {
5461                    clearance: "desk".to_owned(),
5462                    mission_id: start.mission_id.clone(),
5463                    run_id: RunId::try_new("codex-scripts-thread").unwrap(),
5464                    message: Some("Again.".to_owned()),
5465                    working_directory: start.working_directory.clone(),
5466                    environment: start.environment.clone(),
5467                    model: start.model.clone(),
5468                    effort: None,
5469                    max_cost_micro_usd: None,
5470                    project_settings: false,
5471                    project_mcp: false,
5472                    answer_only: false,
5473                    assistant: Some(mode),
5474                    initial_context: Vec::new(),
5475                    overlays: Default::default(),
5476                    loadout: Default::default(),
5477                },
5478                terminal.clone().into_object(),
5479            )
5480            .unwrap();
5481        let events = read_to_completion(&resumed);
5482        resumed.close().unwrap();
5483        let policy = reported_policy(&events);
5484        assert_eq!(policy["sandbox"], Value::Null);
5485        assert_eq!(policy["approvalPolicy"], "never");
5486    }
5487
5488    #[test]
5489    fn a_users_codex_configuration_that_widens_the_scripts_sandbox_refuses_the_thread() {
5490        let handler = CodexHandler::try_from(CodexConfig {
5491            executable: "codex-widened-fixture".to_owned(),
5492            ..CodexConfig::default()
5493        })
5494        .unwrap();
5495        let mut mode = AssistantMode::moneypenny();
5496        mode.interpreters.push("python3".to_owned());
5497        mode.files = vec!["personal".to_owned()];
5498        for user in [
5499            json!({"permissions": {"ai6_assistant": {"network": {"enabled": true}}}}),
5500            json!({"shell_environment_policy": {"set": {"TMPDIR": "/elsewhere"}}}),
5501        ] {
5502            let mut start = assistant_start(mode.clone(), "Chart it.");
5503            start
5504                .environment
5505                .insert("CODEX_FIXTURE_USER_CONFIG".to_owned(), user.to_string());
5506            let terminal = ProcessTerminal::new();
5507            let refused = handler
5508                .start(start.clone(), terminal.clone().into_object())
5509                .err()
5510                .unwrap_or_else(|| panic!("started with {user}"));
5511            assert!(
5512                refused.to_string().contains("changes the sandbox"),
5513                "{refused}"
5514            );
5515            let refused = handler
5516                .resume(
5517                    AgentResume {
5518                        clearance: "desk".to_owned(),
5519                        mission_id: start.mission_id.clone(),
5520                        run_id: RunId::try_new("codex-scripts-thread").unwrap(),
5521                        message: None,
5522                        working_directory: start.working_directory.clone(),
5523                        environment: start.environment.clone(),
5524                        model: start.model.clone(),
5525                        effort: None,
5526                        max_cost_micro_usd: None,
5527                        project_settings: false,
5528                        project_mcp: false,
5529                        answer_only: false,
5530                        assistant: Some(mode.clone()),
5531                        initial_context: Vec::new(),
5532                        overlays: Default::default(),
5533                        loadout: Default::default(),
5534                    },
5535                    terminal.into_object(),
5536                )
5537                .err()
5538                .unwrap_or_else(|| panic!("resumed with {user}"));
5539            assert!(
5540                refused.to_string().contains("changes the sandbox"),
5541                "{refused}"
5542            );
5543        }
5544    }
5545
5546    #[test]
5547    fn scripted_commands_run_and_are_reported_as_a_tool() {
5548        let handler = CodexHandler::try_from(CodexConfig {
5549            executable: "codex-commands-fixture".to_owned(),
5550            ..CodexConfig::default()
5551        })
5552        .unwrap();
5553        for unsandboxed in [false, true] {
5554            let mut mode = AssistantMode::moneypenny();
5555            mode.interpreters.push("python3".to_owned());
5556            mode.files = vec!["personal".to_owned()];
5557            mode.unsandboxed = unsandboxed;
5558            let terminal = ProcessTerminal::new();
5559            let run = handler
5560                .start(
5561                    assistant_start(mode, "item: commandExecution"),
5562                    terminal.clone().into_object(),
5563                )
5564                .unwrap();
5565            let events = until_end(&run);
5566            run.close().unwrap();
5567            assert_eq!(events.last().unwrap().kind, "completed", "{events:?}");
5568            let reported = events
5569                .iter()
5570                .any(|event| event.tools.iter().any(|tool| tool == "exec_command"));
5571            assert!(reported, "a script may read her files: {events:?}");
5572            let policy = reported_policy(&events);
5573            let specs = terminal.specs.lock().unwrap();
5574            let server = specs
5575                .iter()
5576                .find(|spec| spec.argv[1] == "app-server")
5577                .unwrap();
5578            let profiled = server
5579                .argv
5580                .iter()
5581                .any(|argument| argument.starts_with("permissions."));
5582            if unsandboxed {
5583                assert_eq!(policy["sandbox"], "danger-full-access");
5584                assert!(!profiled);
5585            } else {
5586                assert_eq!(policy["sandbox"], Value::Null);
5587                assert!(profiled);
5588            }
5589        }
5590    }
5591
5592    fn answer_only_start(environment: BTreeMap<String, String>) -> AgentStart {
5593        let mut environment = environment;
5594        environment.insert(
5595            "CODEX_FIXTURE_THREAD_ID".to_owned(),
5596            "codex-review-thread".to_owned(),
5597        );
5598        AgentStart {
5599            mission_id: "review--brief".parse().unwrap(),
5600            agent_id: "m".to_owned(),
5601            prompt: "Review this.".to_owned(),
5602            initial_context: Vec::new(),
5603            working_directory: std::env::current_dir()
5604                .unwrap()
5605                .to_string_lossy()
5606                .into_owned(),
5607            clearance: "desk".to_owned(),
5608            environment,
5609            model: Some("gpt-6.1-sol".to_owned()),
5610            effort: None,
5611            max_cost_micro_usd: None,
5612            project_settings: false,
5613            project_mcp: false,
5614            answer_only: true,
5615            assistant: None,
5616            overlays: Default::default(),
5617            loadout: Default::default(),
5618            ledger: None,
5619        }
5620    }
5621
5622    /// Codex 0.164.0's own answer with the settings this handler passed before the tool check.
5623    const OFFERS_EXEC: &str =
5624        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-main.json");
5625    /// Codex 0.164.0's answer with the settings it passes now: the model's catalog entry still
5626    /// brings `functions.exec` and `functions.wait`.
5627    const ANSWER_ONLY_PROMPT: &str =
5628        include_str!("../tests/fixtures/codex-0.164.0/prompt-input-answer-only.json");
5629    /// `codex mcp list --json` of Codex 0.164.0 for a user with one stdio server, `node_repl`,
5630    /// alone and beside an assistant's `moneypenny`.
5631    const MCP_LIST: &str = include_str!("../tests/fixtures/codex-0.164.0/mcp-list.json");
5632    const MCP_LIST_ASSISTANT: &str =
5633        include_str!("../tests/fixtures/codex-0.164.0/mcp-list-assistant.json");
5634
5635    #[test]
5636    fn an_answer_only_thread_codex_still_gives_exec_and_wait_is_not_started() {
5637        let terminal = ProcessTerminal::new();
5638        let handler = CodexHandler::try_from(CodexConfig {
5639            executable: "codex-catalog-fixture".to_owned(),
5640            ..CodexConfig::default()
5641        })
5642        .unwrap();
5643        let environment = BTreeMap::from([
5644            (
5645                "CODEX_FIXTURE_PROMPT_INPUT".to_owned(),
5646                ANSWER_ONLY_PROMPT.replace('\n', ""),
5647            ),
5648            (
5649                "CODEX_FIXTURE_FEATURES".to_owned(),
5650                include_str!("../tests/fixtures/codex-0.164.0/features-list.txt").to_owned(),
5651            ),
5652            (
5653                "CODEX_FIXTURE_MCP_LIST".to_owned(),
5654                MCP_LIST.replace('\n', ""),
5655            ),
5656        ]);
5657        let refused = match handler.start(
5658            answer_only_start(environment),
5659            terminal.clone().into_object(),
5660        ) {
5661            Ok(_) => panic!("a thread offered functions.exec and functions.wait started"),
5662            Err(error) => error.to_string(),
5663        };
5664        assert!(
5665            refused.contains("functions.exec, functions.wait"),
5666            "{refused}"
5667        );
5668        let specs = terminal.specs.lock().unwrap();
5669        assert!(specs.iter().all(|spec| spec.argv[1] != "app-server"));
5670        let checked = specs
5671            .iter()
5672            .find(|spec| spec.argv.len() > 2 && spec.argv[1..3] == ["debug", "prompt-input"])
5673            .unwrap();
5674        let has = |setting: &str| checked.argv.iter().any(|argument| argument == setting);
5675        assert!(
5676            has("mcp_servers.node_repl.enabled=false") && has("features.code_mode_host=false"),
5677            "rendered with the user's server and the features off: {:?}",
5678            checked.argv
5679        );
5680        assert!(
5681            !checked
5682                .argv
5683                .iter()
5684                .any(|argument| argument.starts_with("features.incremental_tools")),
5685            "kept on, or prompt-input renders no tool"
5686        );
5687    }
5688
5689    #[test]
5690    fn the_users_mcp_servers_are_switched_off_on_the_app_server() {
5691        let terminal = ProcessTerminal::new();
5692        let handler = CodexHandler::try_from(CodexConfig {
5693            executable: "codex-user-servers-fixture".to_owned(),
5694            ..CodexConfig::default()
5695        })
5696        .unwrap();
5697        let environment = BTreeMap::from([(
5698            "CODEX_FIXTURE_MCP_LIST".to_owned(),
5699            MCP_LIST.replace('\n', ""),
5700        )]);
5701        let run = handler
5702            .start(
5703                answer_only_start(environment),
5704                terminal.clone().into_object(),
5705            )
5706            .unwrap();
5707        run.close().unwrap();
5708        let specs = terminal.specs.lock().unwrap();
5709        let server = specs
5710            .iter()
5711            .find(|spec| spec.argv[1] == "app-server")
5712            .unwrap();
5713        assert!(
5714            server
5715                .argv
5716                .windows(2)
5717                .any(|pair| pair == ["-c", "mcp_servers.node_repl.enabled=false"]),
5718            "{:?}",
5719            server.argv
5720        );
5721    }
5722
5723    #[test]
5724    fn an_mcp_list_it_cannot_read_refuses_unless_warned() {
5725        for (index, output, found) in [
5726            (
5727                0,
5728                "Error: failed to load bootstrap configuration",
5729                "none of the user's is switched off",
5730            ),
5731            (
5732                1,
5733                "[{\"name\":\"we.ird\",\"enabled\":true}]",
5734                "\"we.ird\" of Codex's configuration cannot be switched off",
5735            ),
5736        ] {
5737            // An executable of its own, so the warned start reads its own list.
5738            let handler = CodexHandler::try_from(CodexConfig {
5739                executable: format!("codex-mcp-unread-fixture-{index}"),
5740                ..CodexConfig::default()
5741            })
5742            .unwrap();
5743            let mut environment =
5744                BTreeMap::from([("CODEX_FIXTURE_MCP_LIST".to_owned(), output.to_owned())]);
5745            let terminal = ProcessTerminal::new();
5746            let refused = match handler.start(
5747                answer_only_start(environment.clone()),
5748                terminal.clone().into_object(),
5749            ) {
5750                Ok(_) => panic!("{output}: started"),
5751                Err(error) => error.to_string(),
5752            };
5753            assert!(refused.contains(found), "{refused}");
5754            assert!(
5755                terminal
5756                    .specs
5757                    .lock()
5758                    .unwrap()
5759                    .iter()
5760                    .all(|spec| spec.argv[1] != "app-server" && spec.argv[1] != "debug"),
5761                "refused before anything else ran"
5762            );
5763            environment.insert(TOOL_CHECK_ENV.to_owned(), "warn".to_owned());
5764            let run = handler
5765                .start(
5766                    answer_only_start(environment),
5767                    ProcessTerminal::new().into_object(),
5768                )
5769                .unwrap();
5770            let first = run.next_event(1_000).unwrap().unwrap();
5771            assert_eq!(first.kind, "weakened");
5772            let text = first.text.unwrap();
5773            assert!(text.contains(found), "{text}");
5774            run.close().unwrap();
5775        }
5776    }
5777
5778    #[test]
5779    fn an_answer_only_thread_offered_extra_tools_is_not_started() {
5780        let terminal = ProcessTerminal::new();
5781        let handler = CodexHandler::try_from(CodexConfig {
5782            executable: "codex-strict-fixture".to_owned(),
5783            ..CodexConfig::default()
5784        })
5785        .unwrap();
5786        let environment = BTreeMap::from([(
5787            "CODEX_FIXTURE_PROMPT_INPUT".to_owned(),
5788            OFFERS_EXEC.replace('\n', ""),
5789        )]);
5790        let refused = match handler.start(
5791            answer_only_start(environment),
5792            terminal.clone().into_object(),
5793        ) {
5794            Ok(_) => panic!("a thread offered functions.exec started"),
5795            Err(error) => error.to_string(),
5796        };
5797        assert!(refused.contains("functions.exec"), "{refused}");
5798        let specs = terminal.specs.lock().unwrap();
5799        assert!(
5800            specs.iter().all(|spec| spec.argv[1] != "app-server"),
5801            "no app server was started"
5802        );
5803        let checked = specs
5804            .iter()
5805            .find(|spec| spec.argv.len() > 2 && spec.argv[1..3] == ["debug", "prompt-input"])
5806            .unwrap();
5807        assert!(
5808            checked
5809                .argv
5810                .ends_with(&["-c".to_owned(), "model=\"gpt-6.1-sol\"".to_owned()]),
5811            "what Codex offers depends on the model: {:?}",
5812            checked.argv
5813        );
5814    }
5815
5816    #[test]
5817    fn a_warned_thread_starts_and_reports_the_extra_tools_first() {
5818        let handler = CodexHandler::try_from(CodexConfig {
5819            executable: "codex-warn-fixture".to_owned(),
5820            ..CodexConfig::default()
5821        })
5822        .unwrap();
5823        let environment = BTreeMap::from([
5824            (
5825                "CODEX_FIXTURE_PROMPT_INPUT".to_owned(),
5826                OFFERS_EXEC.replace('\n', ""),
5827            ),
5828            (TOOL_CHECK_ENV.to_owned(), "warn".to_owned()),
5829        ]);
5830        let run = handler
5831            .start(
5832                answer_only_start(environment),
5833                ProcessTerminal::new().into_object(),
5834            )
5835            .unwrap();
5836        let first = run.next_event(1_000).unwrap().unwrap();
5837        assert_eq!(first.kind, "weakened");
5838        let text = first.text.unwrap();
5839        assert!(
5840            text.contains("functions.exec") && text.contains("mcp__cua_repl.js"),
5841            "{text}"
5842        );
5843        run.close().unwrap();
5844    }
5845
5846    #[test]
5847    fn an_answer_only_thread_with_no_tool_passes_and_keeps_its_plumbing() {
5848        let terminal = ProcessTerminal::new();
5849        let handler = CodexHandler::try_from(CodexConfig {
5850            executable: "codex-pass-fixture".to_owned(),
5851            ..CodexConfig::default()
5852        })
5853        .unwrap();
5854        let run = handler
5855            .start(
5856                answer_only_start(BTreeMap::new()),
5857                terminal.clone().into_object(),
5858            )
5859            .unwrap();
5860        run.close().unwrap();
5861        let specs = terminal.specs.lock().unwrap();
5862        let server = specs
5863            .iter()
5864            .find(|spec| spec.argv[1] == "app-server")
5865            .unwrap();
5866        assert!(
5867            server
5868                .argv
5869                .iter()
5870                .any(|a| a == "features.code_mode_host=false")
5871        );
5872        assert!(
5873            !server
5874                .argv
5875                .iter()
5876                .any(|a| a.starts_with("features.secret_auth_storage"))
5877        );
5878    }
5879
5880    #[test]
5881    fn the_feature_list_is_reused_only_for_the_same_codex_home_and_the_tools_rendered_every_time() {
5882        let terminal = ProcessTerminal::new();
5883        let handler = CodexHandler::try_from(CodexConfig {
5884            executable: "codex-cache-fixture".to_owned(),
5885            ..CodexConfig::default()
5886        })
5887        .unwrap();
5888        for home in ["C:\\agents\\one", "C:\\agents\\one", "C:\\agents\\two"] {
5889            let environment = BTreeMap::from([("CODEX_HOME".to_owned(), home.to_owned())]);
5890            let run = handler
5891                .start(
5892                    answer_only_start(environment),
5893                    terminal.clone().into_object(),
5894                )
5895                .unwrap();
5896            run.close().unwrap();
5897        }
5898        let specs = terminal.specs.lock().unwrap();
5899        let count = |command: &str| {
5900            specs
5901                .iter()
5902                .filter(|spec| spec.argv.get(1).map(String::as_str) == Some(command))
5903                .count()
5904        };
5905        assert_eq!(count("--version"), 3, "the version is asked every time");
5906        assert_eq!(
5907            count("features"),
5908            2,
5909            "another CODEX_HOME is another configuration"
5910        );
5911        assert_eq!(
5912            count("mcp"),
5913            2,
5914            "the MCP servers are reused with the features"
5915        );
5916        assert_eq!(
5917            count("debug"),
5918            3,
5919            "what Codex offers is rendered on every start"
5920        );
5921        assert_eq!(count("app-server"), 3);
5922    }
5923
5924    #[test]
5925    fn a_feature_list_with_lines_it_cannot_read_refuses_unless_warned() {
5926        let handler = CodexHandler::try_from(CodexConfig {
5927            executable: "codex-unread-fixture".to_owned(),
5928            ..CodexConfig::default()
5929        })
5930        .unwrap();
5931        let features = "code_mode_host stable true\nWARNING: the plugin cache is stale";
5932        let mut environment =
5933            BTreeMap::from([("CODEX_FIXTURE_FEATURES".to_owned(), features.to_owned())]);
5934        let refused = match handler.start(
5935            answer_only_start(environment.clone()),
5936            ProcessTerminal::new().into_object(),
5937        ) {
5938            Ok(_) => panic!("a feature list with a line it cannot read was accepted"),
5939            Err(error) => error.to_string(),
5940        };
5941        assert!(refused.contains("plugin cache is stale"), "{refused}");
5942        environment.insert(TOOL_CHECK_ENV.to_owned(), "warn".to_owned());
5943        let run = handler
5944            .start(
5945                answer_only_start(environment),
5946                ProcessTerminal::new().into_object(),
5947            )
5948            .unwrap();
5949        let first = run.next_event(1_000).unwrap().unwrap();
5950        assert_eq!(first.kind, "weakened");
5951        assert!(first.text.unwrap().contains("not a feature"));
5952        run.close().unwrap();
5953    }
5954
5955    /// Events until the Run ends (`completed` or `failed`), at most a minute.
5956    fn until_end(run: &Object<dyn AgentSession>) -> Vec<AgentEvent> {
5957        let deadline = Instant::now() + Duration::from_secs(60);
5958        let mut events = Vec::new();
5959        while Instant::now() < deadline {
5960            match run.next_event(200) {
5961                Ok(Some(event)) => {
5962                    let end = matches!(event.kind.as_str(), "completed" | "failed");
5963                    events.push(event);
5964                    if end {
5965                        break;
5966                    }
5967                }
5968                Ok(None) => {}
5969                Err(_) => break,
5970            }
5971        }
5972        events
5973    }
5974
5975    #[test]
5976    fn a_restricted_thread_that_uses_a_tool_is_ended() {
5977        let handler = CodexHandler::try_from(CodexConfig {
5978            executable: "codex-trip-fixture".to_owned(),
5979            ..CodexConfig::default()
5980        })
5981        .unwrap();
5982        for item in [
5983            "commandExecution",
5984            "fileChange",
5985            "webSearch",
5986            "mcpToolCall other",
5987        ] {
5988            let mut start = answer_only_start(BTreeMap::new());
5989            start.prompt = format!("item: {item}");
5990            let run = handler
5991                .start(start, ProcessTerminal::new().into_object())
5992                .unwrap();
5993            let events = until_end(&run);
5994            let last = events.last().expect("the Run ended");
5995            assert_eq!(last.kind, "failed", "{item}: {events:?}");
5996            let reason = last.text.as_deref().unwrap_or_default();
5997            assert!(reason.contains("restricted Codex thread used"), "{reason}");
5998            assert!(
5999                !events
6000                    .iter()
6001                    .any(|event| event.text.as_deref() == Some("after")),
6002                "nothing after the tool use is read: {events:?}"
6003            );
6004        }
6005    }
6006
6007    #[test]
6008    fn a_restricted_thread_may_call_its_own_servers_and_talk() {
6009        let nothing = Restriction::default();
6010        assert_eq!(
6011            forbidden_use(
6012                &read_message(&json!({"method":"item/started","params":{"item":{
6013                    "type":"mcpToolCall","server":"moneypenny","tool":"board"}}})),
6014                &Restriction {
6015                    servers: vec!["moneypenny".to_owned()],
6016                    ..Restriction::default()
6017                }
6018            ),
6019            None
6020        );
6021        for kind in ["agentMessage", "reasoning", "userMessage"] {
6022            let message = json!({"method":"item/completed","params":{"item":{"type":kind}}});
6023            assert_eq!(
6024                forbidden_use(&read_message(&message), &nothing),
6025                None,
6026                "{kind}"
6027            );
6028        }
6029        let unknown = json!({"method":"item/started","params":{"item":{"type":"hologram"}}});
6030        assert!(
6031            forbidden_use(&read_message(&unknown), &nothing).is_some(),
6032            "an unknown item is a tool"
6033        );
6034        let question = json!({"id": 4, "method": "item/tool/requestUserInput", "params": {}});
6035        assert!(forbidden_use(&read_message(&question), &nothing).is_some());
6036        let refresh = json!({"id": 5, "method": "account/chatgptAuthTokens/refresh"});
6037        assert_eq!(
6038            forbidden_use(&read_message(&refresh), &nothing),
6039            None,
6040            "plumbing is not a tool"
6041        );
6042    }
6043
6044    #[test]
6045    fn scripts_admit_commands_and_only_with_directories_file_changes() {
6046        let item = |kind: &str| json!({"method":"item/started","params":{"item":{"type":kind}}});
6047        let mut mode = AssistantMode::moneypenny();
6048        mode.interpreters.push("python3".to_owned());
6049        let scripts = restriction(false, Some(&mode), None, false).unwrap();
6050        assert_eq!(
6051            forbidden_use(&read_message(&item("commandExecution")), &scripts),
6052            None
6053        );
6054        assert!(
6055            forbidden_use(&read_message(&item("fileChange")), &scripts).is_some(),
6056            "no directory to write"
6057        );
6058        assert!(forbidden_use(&read_message(&item("webSearch")), &scripts).is_some());
6059        mode.files.push("personal".to_owned());
6060        let files = restriction(false, Some(&mode), None, false).unwrap();
6061        assert_eq!(
6062            forbidden_use(&read_message(&item("fileChange")), &files),
6063            None
6064        );
6065        let approval = json!({"id": 3, "method": COMMAND_APPROVAL, "params": {}});
6066        assert!(
6067            forbidden_use(&read_message(&approval), &files).is_some(),
6068            "a thread that never asks has nothing to approve"
6069        );
6070    }
6071
6072    #[test]
6073    fn a_resume_codex_would_run_outside_the_hosts_environment_is_an_unsupported_start_naming_why() {
6074        let words = "this thread would run in Codex's own environment, not in the environment \
6075                     `theater` it was given: start a new thread";
6076        let failed = started_with(CodexError::Refused(words.to_owned()));
6077        assert_eq!(failed.status, Status::GUATIAO_ERR_UNSUPPORTED);
6078        assert!(
6079            failed.to_string().contains("start a new thread"),
6080            "{failed}"
6081        );
6082    }
6083
6084    #[test]
6085    fn an_assistant_mode_the_codex_handler_cannot_confine_is_refused() {
6086        let environment = BTreeMap::from([
6087            (
6088                "AI6_MONEYPENNY_MCP_URL".to_owned(),
6089                "https://exports.example/v1/moneypenny/mcp".to_owned(),
6090            ),
6091            ("AI6_MONEYPENNY_MCP_TOKEN".to_owned(), "token".to_owned()),
6092        ]);
6093        let mut skills = AssistantMode::moneypenny();
6094        skills.skills.push("pdf".to_owned());
6095        skills.skills_dir = Some(
6096            std::env::temp_dir()
6097                .join(".claude")
6098                .to_string_lossy()
6099                .into_owned(),
6100        );
6101        let refused = assistant_argv("codex", &environment, &skills, None).unwrap_err();
6102        assert_eq!(refused.status, Status::GUATIAO_ERR_UNSUPPORTED);
6103        assert!(
6104            refused.to_string().contains("no list of allowed skills"),
6105            "{refused}"
6106        );
6107        assert!(
6108            assistant_argv(
6109                "codex",
6110                &BTreeMap::new(),
6111                &AssistantMode::moneypenny(),
6112                None
6113            )
6114            .is_err(),
6115            "no endpoint in the environment"
6116        );
6117        let handler = CodexHandler::try_from(CodexConfig {
6118            executable: "codex".to_owned(),
6119            ..CodexConfig::default()
6120        })
6121        .unwrap();
6122        assert!(
6123            handler.assistant_skills().unwrap().is_some(),
6124            "a Station installs no skill for it"
6125        );
6126    }
6127
6128    #[test]
6129    fn her_default_network_is_denied_and_the_handler_keeps_to_it() {
6130        assert_eq!(AssistantMode::moneypenny().network.policy, "denied");
6131        let handler = CodexHandler::try_from(CodexConfig {
6132            executable: "codex".to_owned(),
6133            ..CodexConfig::default()
6134        })
6135        .unwrap();
6136        assert_eq!(handler.assistant_network().unwrap(), None);
6137    }
6138
6139    #[test]
6140    fn without_interpreters_files_and_a_network_add_no_tool_and_she_is_told() {
6141        let environment = BTreeMap::from([
6142            (
6143                "AI6_MONEYPENNY_MCP_URL".to_owned(),
6144                "https://exports.example/v1/moneypenny/mcp".to_owned(),
6145            ),
6146            ("AI6_MONEYPENNY_MCP_TOKEN".to_owned(), "token".to_owned()),
6147        ]);
6148        let mut mode = AssistantMode::moneypenny();
6149        mode.files.push("personal".to_owned());
6150        mode.network.policy = "open".to_owned();
6151        let argv = assistant_argv("codex", &environment, &mode, None).unwrap();
6152        assert_no_built_in_tools(&argv);
6153        assert!(
6154            !argv
6155                .iter()
6156                .any(|argument| argument.starts_with("permissions.")),
6157            "no sandbox profile without scripts: {argv:?}"
6158        );
6159        assert_eq!(
6160            restriction(false, Some(&mode), None, false),
6161            Some(Restriction {
6162                servers: vec!["moneypenny".to_owned()],
6163                commands: false,
6164                file_changes: false,
6165                asks_file_changes: false,
6166            })
6167        );
6168        let told = assistant_instructions(
6169            &mode,
6170            Scripts::None,
6171            CodexConfig::default().context_file_bytes,
6172        )
6173        .unwrap();
6174        assert!(
6175            told.iter().any(|line| line.contains("no file tools")),
6176            "{told:?}"
6177        );
6178        let mut params = ThreadPolicy::default();
6179        set_approval_policy(&mut params, &environment, true, Scripts::None, false);
6180        assert_eq!(params.sandbox, Some("read-only"));
6181    }
6182
6183    #[test]
6184    fn an_assistant_with_cable_grants_gets_both_servers() {
6185        let environment = BTreeMap::from([
6186            (
6187                "AI6_MONEYPENNY_MCP_URL".to_owned(),
6188                "https://exports.example/v1/moneypenny/mcp".to_owned(),
6189            ),
6190            ("AI6_MONEYPENNY_MCP_TOKEN".to_owned(), "token".to_owned()),
6191            (
6192                "AI6_ASSISTANT_CABLE_MCP_URL".to_owned(),
6193                "http://127.0.0.1:4100/mcp".to_owned(),
6194            ),
6195            (
6196                "AI6_ASSISTANT_CABLE_MCP_TOKEN".to_owned(),
6197                "cable-token".to_owned(),
6198            ),
6199        ]);
6200        let argv = assistant_argv(
6201            "codex",
6202            &environment,
6203            &AssistantMode::moneypenny().with_cables(),
6204            None,
6205        )
6206        .unwrap();
6207        let (key, value) = argv[3].split_once('=').unwrap();
6208        let parsed: toml::Table = toml::from_str(&format!("{key} = {value}")).unwrap();
6209        assert_eq!(
6210            parsed["mcp_servers"],
6211            toml::Value::Table(
6212                toml::from_str(
6213                    "moneypenny = { url = \"https://exports.example/v1/moneypenny/mcp\", \
6214                     bearer_token_env_var = \"AI6_MONEYPENNY_MCP_TOKEN\", \
6215                     default_tools_approval_mode = \"approve\" }\n\
6216                     cables = { url = \"http://127.0.0.1:4100/mcp\", \
6217                     bearer_token_env_var = \"AI6_ASSISTANT_CABLE_MCP_TOKEN\", \
6218                     default_tools_approval_mode = \"approve\" }"
6219                )
6220                .unwrap()
6221            )
6222        );
6223        assert!(!argv.iter().any(|a| a.contains("cable-token")));
6224    }
6225
6226    #[test]
6227    fn an_answer_only_app_server_has_no_mcp_server_at_all() {
6228        let argv = answer_only_argv("codex");
6229        assert_eq!(argv[..4], ["codex", "app-server", "-c", "mcp_servers={}"]);
6230        let (key, value) = argv[3].split_once('=').unwrap();
6231        let parsed: toml::Table = toml::from_str(&format!("{key} = {value}")).unwrap();
6232        assert!(parsed["mcp_servers"].as_table().unwrap().is_empty());
6233        assert_no_built_in_tools(&argv);
6234        assert!(
6235            argv.windows(2)
6236                .any(|pair| pair == ["-c", "project_doc_max_bytes=0"]),
6237            "the checkout's AGENTS.md is no input of an answer-only thread: {argv:?}"
6238        );
6239    }
6240
6241    /// Asserts the `-c` overrides that leave Codex no shell, no exec, no image reading, no web
6242    /// search, no sub-agents and no app connectors, each parsed as Codex parses a `-c` value.
6243    fn assert_no_built_in_tools(argv: &[String]) {
6244        let mut settings = toml::Table::new();
6245        for pair in argv.windows(2).filter(|pair| pair[0] == "-c") {
6246            let parsed: toml::Table = toml::from_str(&pair[1]).unwrap();
6247            for (key, value) in parsed {
6248                match (settings.get_mut(&key), value) {
6249                    (Some(toml::Value::Table(merged)), toml::Value::Table(more)) => {
6250                        merged.extend(more);
6251                    }
6252                    (_, value) => {
6253                        settings.insert(key, value);
6254                    }
6255                }
6256            }
6257        }
6258        let off = |table: &str, key: &str| settings[table][key].as_bool();
6259        assert_eq!(off("features", "shell_tool"), Some(false), "{argv:?}");
6260        assert_eq!(
6261            settings["tools"]["experimental_request_user_input"]["enabled"].as_bool(),
6262            Some(false),
6263            "{argv:?}"
6264        );
6265        assert!(
6266            settings["tools"].get("view_image").is_none(),
6267            "Codex 0.164.0 ignores it as unrecognized: {argv:?}"
6268        );
6269        assert_eq!(off("features", "multi_agent"), Some(false), "{argv:?}");
6270        assert_eq!(off("agents", "enabled"), Some(false), "{argv:?}");
6271        assert_eq!(off("features", "apps"), Some(false), "{argv:?}");
6272        assert_eq!(
6273            settings["skills"]["max_context_tokens"].as_integer(),
6274            Some(1),
6275            "{argv:?}"
6276        );
6277        assert_eq!(
6278            settings["web_search"].as_str(),
6279            Some("disabled"),
6280            "{argv:?}"
6281        );
6282    }
6283
6284    #[test]
6285    fn cable_mcp_config_passes_url_and_token_name_without_token_value() {
6286        let environment = std::collections::BTreeMap::from([
6287            (
6288                "AI6_CABLE_MCP_URL".to_owned(),
6289                "http://127.0.0.1:43210/mcp".to_owned(),
6290            ),
6291            (
6292                "AI6_CABLE_MCP_TOKEN".to_owned(),
6293                "run-secret-token".to_owned(),
6294            ),
6295        ]);
6296
6297        let argv = app_server_argv("codex", &environment);
6298        assert!(argv.iter().any(|argument| {
6299            argument == "mcp_servers.ai6-cables.url=\"http://127.0.0.1:43210/mcp\""
6300        }));
6301        assert!(argv.iter().any(|argument| {
6302            argument == "mcp_servers.ai6-cables.bearer_token_env_var=\"AI6_CABLE_MCP_TOKEN\""
6303        }));
6304        assert!(argv.iter().any(|argument| {
6305            argument == "mcp_servers.ai6-cables.default_tools_approval_mode=\"approve\""
6306        }));
6307        assert!(
6308            argv.iter()
6309                .all(|argument| !argument.contains("run-secret-token"))
6310        );
6311    }
6312
6313    /// The `thread/tokenUsage/updated` notification as the app-server protocol's schema
6314    /// describes it; the figures are invented.
6315    fn token_usage_notification() -> Value {
6316        json!({
6317            "method": "thread/tokenUsage/updated",
6318            "params": {
6319                "threadId": "thread-1",
6320                "turnId": "turn-1",
6321                "tokenUsage": {
6322                    "total": { "totalTokens": 9000, "inputTokens": 8000, "cachedInputTokens": 3000,
6323                               "outputTokens": 1000, "reasoningOutputTokens": 200 },
6324                    "last": { "totalTokens": 1500, "inputTokens": 1200, "cachedInputTokens": 700,
6325                              "outputTokens": 300, "reasoningOutputTokens": 50 },
6326                    "modelContextWindow": 272000
6327                }
6328            }
6329        })
6330    }
6331
6332    #[test]
6333    fn a_token_usage_notification_reports_the_last_request_as_an_addition() {
6334        let event = decoded(&token_usage_notification(), None).unwrap();
6335        assert_eq!(event.kind, "thread/tokenUsage/updated");
6336        let spend = event.report.unwrap().spend.unwrap();
6337        assert_eq!(
6338            (
6339                spend.input,
6340                spend.output,
6341                spend.cache_read,
6342                spend.cache_write
6343            ),
6344            (500, 300, 700, 0)
6345        );
6346        assert_eq!(spend.cost_micro_usd, None, "Codex reports no cost");
6347    }
6348
6349    #[test]
6350    fn a_started_web_search_or_tool_call_names_its_tool() {
6351        let search = json!({
6352            "method": "item/started",
6353            "params": { "item": { "type": "webSearch", "id": "i1", "query": "rust" } }
6354        });
6355        assert_eq!(decoded(&search, None).unwrap().tools, ["WebSearch"]);
6356        let call = json!({
6357            "method": "item/started",
6358            "params": { "item": { "type": "mcpToolCall", "server": "docs", "tool": "fetch_page" } }
6359        });
6360        assert_eq!(decoded(&call, None).unwrap().tools, ["fetch_page"]);
6361        let command = json!({
6362            "method": "item/started",
6363            "params": { "item": { "type": "commandExecution", "command": "ls" } }
6364        });
6365        assert!(decoded(&command, None).unwrap().tools.is_empty());
6366    }
6367
6368    #[test]
6369    fn other_notifications_and_a_total_without_last_carry_no_usage() {
6370        let delta = json!({ "method": "item/agentMessage/delta", "params": { "delta": "hi" } });
6371        assert!(decoded(&delta, None).unwrap().report.is_none());
6372        let total_only = json!({
6373            "method": "thread/tokenUsage/updated",
6374            "params": { "tokenUsage": { "total": { "totalTokens": 1 } } }
6375        });
6376        assert!(decoded(&total_only, None).unwrap().report.is_none());
6377    }
6378
6379    /// Real Codex 0.164.0 listed skills of its home and of the project only: `skills.*` settings and
6380    /// `skills/list` with extra roots added none, so the routing line is the delivery.
6381    #[test]
6382    fn an_overlays_skill_is_a_routing_line_in_the_developer_instructions() {
6383        let handler = CodexHandler::try_from(CodexConfig {
6384            executable: "codex-overlay-fixture".to_owned(),
6385            ..CodexConfig::default()
6386        })
6387        .unwrap();
6388        let terminal = ProcessTerminal::new();
6389        let mut start = assistant_start(AssistantMode::moneypenny(), "Do it.");
6390        start.assistant = None;
6391        start.clearance = "field".to_owned();
6392        start.overlays.skills.push(ai6::OverlaySkill {
6393            name: "review".to_owned(),
6394            overlay: "tools".to_owned(),
6395            description: "Reviews a change.".to_owned(),
6396            path: "/store/tools/skills/review".to_owned(),
6397            native: true,
6398        });
6399        let run = handler.start(start, terminal.into_object()).unwrap();
6400        let events = read_to_completion(&run);
6401        let instructions = reported_policy(&events)["developerInstructions"]
6402            .as_str()
6403            .unwrap()
6404            .to_owned();
6405        assert!(
6406            instructions.starts_with("You are Moneypenny."),
6407            "{instructions}"
6408        );
6409        assert!(
6410            instructions.contains("Skill `review` (overlay `tools`)"),
6411            "{instructions}"
6412        );
6413        assert!(
6414            instructions.contains("/store/tools/skills/review/SKILL.md"),
6415            "{instructions}"
6416        );
6417        run.close().unwrap();
6418    }
6419
6420    /// Opens a Mission thread with `applied` on the fixture app server, which reports the policy.
6421    fn open_with_loadout(
6422        terminal: &ProcessTerminal,
6423        environment: &BTreeMap<String, String>,
6424        cwd: &str,
6425        applied: loadout::Applied,
6426    ) -> Result<CodexRun, ProviderError> {
6427        let config = CodexConfig {
6428            executable: "codex-loadout-fixture".to_owned(),
6429            ..CodexConfig::default()
6430        };
6431        open(Opening {
6432            config: &config,
6433            terminal: terminal.clone().into_object(),
6434            cwd,
6435            environment,
6436            mode: Mode {
6437                config: &config,
6438                project_settings: false,
6439                answer_only: false,
6440                desk: false,
6441                assistant: None,
6442                model: None,
6443                profile: None,
6444            },
6445            thread: ThreadStart::New,
6446            model: None,
6447            effort: None,
6448            instructions: None,
6449            gate: None,
6450            restriction: None,
6451            profile: None,
6452            loadout: applied,
6453        })
6454    }
6455
6456    fn loadout_for(servers: Vec<ai6::LoadoutMcp>, write: &[&str]) -> ai6::RunLoadout {
6457        ai6::RunLoadout {
6458            mcp_servers: servers,
6459            sandbox: (!write.is_empty()).then(|| ai6::LoadoutSandbox {
6460                name: "tight".to_owned(),
6461                read_write: write.iter().map(|path| (*path).to_owned()).collect(),
6462                read_only: vec!["$WORKTREE/.git".to_owned()],
6463                network: Vec::new(),
6464            }),
6465            ..ai6::RunLoadout::default()
6466        }
6467    }
6468
6469    #[test]
6470    fn a_missions_loadout_reaches_the_app_server_and_its_profile_is_the_one_codex_runs() {
6471        let cwd = std::env::current_dir()
6472            .unwrap()
6473            .to_string_lossy()
6474            .into_owned();
6475        let server = ai6::LoadoutMcp {
6476            name: "files".to_owned(),
6477            command: vec!["mcp-files".to_owned()],
6478            deny: vec!["delete".to_owned()],
6479        };
6480        let loadout = loadout_for(vec![server], &["$WORKTREE"]);
6481        let applied =
6482            loadout::apply_with(&loadout, &loadout::support(None), false, &cwd, false).unwrap();
6483        let environment = BTreeMap::from([
6484            (
6485                "CODEX_FIXTURE_THREAD_ID".to_owned(),
6486                "codex-loadout-thread".to_owned(),
6487            ),
6488            ("CODEX_FIXTURE_SHOW_POLICY".to_owned(), "1".to_owned()),
6489        ]);
6490        let terminal = ProcessTerminal::new();
6491        let run = open_with_loadout(&terminal, &environment, &cwd, applied).unwrap();
6492        run.send_message(AgentMessage {
6493            text: "go".to_owned(),
6494        })
6495        .unwrap();
6496        let events = read_to_completion(&run.into_object());
6497        let policy = reported_policy(&events);
6498        assert_eq!(
6499            policy["sandbox"],
6500            Value::Null,
6501            "the profile decides: {policy}"
6502        );
6503        let specs = terminal.specs.lock().unwrap();
6504        let argv = &specs
6505            .iter()
6506            .find(|spec| spec.argv[1] == "app-server")
6507            .unwrap()
6508            .argv;
6509        let has = |setting: &str| argv.iter().any(|argument| argument == setting);
6510        assert!(has("mcp_servers.files.command=\"mcp-files\""), "{argv:?}");
6511        assert!(
6512            has("mcp_servers.files.disabled_tools=[\"delete\"]"),
6513            "{argv:?}"
6514        );
6515        assert!(has("default_permissions=\"ai6_loadout\""), "{argv:?}");
6516        assert!(
6517            argv.iter()
6518                .any(|a| a.starts_with("permissions.ai6_loadout={filesystem={")),
6519            "{argv:?}"
6520        );
6521        assert!(
6522            !argv
6523                .iter()
6524                .any(|a| a.starts_with("shell_environment_policy")),
6525            "a Mission's commands keep their environment: {argv:?}"
6526        );
6527    }
6528
6529    #[test]
6530    fn a_users_codex_configuration_that_widens_the_loadouts_profile_refuses_the_thread() {
6531        let cwd = std::env::current_dir()
6532            .unwrap()
6533            .to_string_lossy()
6534            .into_owned();
6535        let loadout = loadout_for(Vec::new(), &["$WORKTREE"]);
6536        let applied =
6537            loadout::apply_with(&loadout, &loadout::support(None), false, &cwd, false).unwrap();
6538        for user in [
6539            json!({"permissions": {"ai6_loadout": {"network": {"enabled": true}}}}),
6540            json!({"permissions": {"ai6_loadout": {"filesystem": {"/": "write"}}}}),
6541        ] {
6542            let environment = BTreeMap::from([
6543                (
6544                    "CODEX_FIXTURE_THREAD_ID".to_owned(),
6545                    "codex-loadout-thread".to_owned(),
6546                ),
6547                ("CODEX_FIXTURE_USER_CONFIG".to_owned(), user.to_string()),
6548            ]);
6549            let Err(refused) =
6550                open_with_loadout(&ProcessTerminal::new(), &environment, &cwd, applied.clone())
6551            else {
6552                panic!("started with {user}");
6553            };
6554            assert!(
6555                refused.to_string().contains("changes the sandbox profile"),
6556                "{refused}"
6557            );
6558        }
6559        // The positive control: nothing merged, and it starts.
6560        assert!(
6561            open_with_loadout(
6562                &ProcessTerminal::new(),
6563                &BTreeMap::from([(
6564                    "CODEX_FIXTURE_THREAD_ID".to_owned(),
6565                    "codex-loadout-thread".to_owned()
6566                )]),
6567                &cwd,
6568                applied,
6569            )
6570            .is_ok()
6571        );
6572    }
6573
6574    #[test]
6575    fn start_with_a_claude_ledger_writes_a_codex_rollout_and_resumes_it() {
6576        let codex_home = tempfile::tempdir().unwrap();
6577        let session = "7a1f0d3e-0c11-4a55-9d1e-2f6c4b8a9e10";
6578        let ledger = ai6::StartLedger::from_text(&format!("{}\n", [r#"{"format":"coqui-acp-history","version":1,"id":"5f0f6d6e-3f3c-4f1a-8a52-1c1e6f0b9a77","origin":{"harness":"claude"}}"#,
6579                r#"{"method":"session/prompt","params":{"prompt":[{"type":"text","text":"fix the parser"}]}}"#,
6580                // The tool call as the Station records it: its title, no input or output.
6581                r#"{"method":"session/update","params":{"update":{"sessionUpdate":"tool_call","toolCallId":"ai6-call-1","title":"Read","kind":"other","status":"completed"}}}"#,
6582                r#"{"method":"session/update","params":{"update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"done"}}}}"#,
6583                r#"{"method":"history/turn_end","params":{"stopReason":"end_turn"}}"#,
6584            ].join("\n"))).unwrap()
6585        .with_session(session);
6586        let terminal = ScriptedTerminal::new(
6587            vec![
6588                b"{\"id\":1,\"result\":{}}\n".to_vec(),
6589                format!("{{\"id\":2,\"result\":{{\"thread\":{{\"id\":\"{session}\"}}}}}}\n")
6590                    .into_bytes(),
6591                b"{\"id\":3,\"result\":{\"data\":[]}}\n".to_vec(),
6592                b"{\"id\":4,\"result\":{\"turn\":{\"id\":\"turn-1\"}}}\n".to_vec(),
6593            ],
6594            4,
6595        );
6596        let writes = terminal.writes.clone();
6597        let handler = CodexHandler::try_from(CodexConfig {
6598            executable: "codex-test".to_owned(),
6599            ..CodexConfig::default()
6600        })
6601        .unwrap();
6602        let run = handler
6603            .start(
6604                AgentStart {
6605                    mission_id: "mission-42".parse().unwrap(),
6606                    agent_id: "007".to_owned(),
6607                    prompt: "continue".to_owned(),
6608                    initial_context: Vec::new(),
6609                    working_directory: "/work".to_owned(),
6610                    clearance: "field".to_owned(),
6611                    environment: BTreeMap::from([(
6612                        "CODEX_HOME".to_owned(),
6613                        codex_home.path().to_string_lossy().into_owned(),
6614                    )]),
6615                    model: None,
6616                    effort: None,
6617                    max_cost_micro_usd: None,
6618                    project_settings: false,
6619                    project_mcp: false,
6620                    answer_only: false,
6621                    assistant: None,
6622                    overlays: Default::default(),
6623                    loadout: Default::default(),
6624                    ledger: Some(ledger),
6625                },
6626                terminal.into_object(),
6627            )
6628            .unwrap();
6629        assert_eq!(run.session_id().unwrap().as_deref(), Some(session));
6630        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
6631        let messages: Vec<Value> = written
6632            .lines()
6633            .map(|line| serde_json::from_str(line).unwrap())
6634            .collect();
6635        assert_eq!(messages[2]["method"], "thread/resume");
6636        assert_eq!(messages[2]["params"]["threadId"], session);
6637        assert_eq!(messages[4]["method"], "turn/start");
6638        assert_eq!(messages[4]["params"]["input"][0]["text"], "continue");
6639
6640        let mut rollouts = Vec::new();
6641        fn walk(dir: &Path, found: &mut Vec<std::path::PathBuf>) {
6642            if let Ok(entries) = std::fs::read_dir(dir) {
6643                for entry in entries.flatten() {
6644                    let path = entry.path();
6645                    if path.is_dir() {
6646                        walk(&path, found);
6647                    } else {
6648                        found.push(path);
6649                    }
6650                }
6651            }
6652        }
6653        walk(&codex_home.path().join("sessions"), &mut rollouts);
6654        assert_eq!(rollouts.len(), 1, "{rollouts:?}");
6655        let body = std::fs::read_to_string(&rollouts[0]).unwrap();
6656        assert!(body.contains("fix the parser"), "{body}");
6657        assert!(body.contains("Read"), "the tool call by its title: {body}");
6658    }
6659}