Skip to main content

ai6_agent_claude/
lib.rs

1//! Claude Code's stream-json implementation of AI6's AgentHandler contract.
2
3#![doc = include_str!("../README.md")]
4#![forbid(unsafe_code)]
5
6ai6::guatiao::providers!(ClaudeHandler);
7
8mod loadout;
9mod settings;
10mod stream;
11mod terminal;
12
13#[cfg(test)]
14mod fixed;
15
16use std::collections::{BTreeMap, VecDeque};
17use std::ffi::OsString;
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::sync::{Arc, Condvar, Mutex};
20use std::time::{Duration, Instant};
21
22use ai6::directorates::m::assistant::SKILLS_PLUGIN;
23use ai6::directorates::m::identity::RunId;
24use ai6::directorates::q::terminal::{AgentTerminal, exit_code_text};
25use ai6::directorates::section_00::agent::{
26    AgentHandler, AgentResume, AgentStart, Answer, AssistantMode, ChoiceInfo, ModelInfo,
27    RunOverlays, RunRecordFile, RunRecordQuery, StartOptions, clearance_reads_only,
28    clearance_runs_commands,
29};
30use ai6::directorates::section_00::assistant::{SCRIPT_ENVIRONMENT, credential_dir_var};
31use ai6::directorates::section_00::denied::DenyList;
32use ai6::directorates::section_00::gate::{GATE_PROGRAM_ENV, WEB_GATE_ARGS};
33use ai6::directorates::section_00::ledger_seed::{
34    CLAUDE, SeedRequest, discard_transcript, new_session_id, write_transcript,
35};
36use ai6::directorates::section_00::listing;
37use ai6::directorates::section_00::loadout::LoadoutSupport;
38use ai6::directorates::section_00::programs;
39use ai6::directorates::section_00::records;
40use ai6::guatiao::library::{Object, ProviderError};
41use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
42use ai6::micro_usd;
43use ai6::{
44    AgentEvent, AgentMessage, AgentSession, Bucket, BucketStatus, DENIED_EVENT, LIMIT_EVENT,
45    LimitHit, Refill, SessionChange, SessionCommand, Spend, UsageReport, UsageSource, UsageSupport,
46    infer_limit,
47};
48use coqui_acp_claude::harness::event::{Content, Event as ClaudeEvent};
49use coqui_acp_claude::harness::mode::Mode as NeutralMode;
50use coqui_acp_claude::{
51    ClaudeLaunch, ClaudeSession as Session, ClaudeSettings as DriverSettings, Error as ClaudeError,
52    SessionStart,
53};
54use serde::Deserialize;
55#[cfg(test)]
56use serde_json::Value;
57#[cfg(test)]
58use serde_json::json;
59use settings::{
60    Credentials, Denied, DeniedFile, HookCommand, HookGroup, HttpServer, InitializeRequest,
61    McpConfig, McpServer, Permissions, Sandbox, ScriptFilesystem, ScriptNetwork, ScriptSandbox,
62    SettingsDocument,
63};
64use stream::{InitializeAnswer, JsonObject, StreamLine};
65
66use terminal::{Link, TerminalSpawn};
67
68/// Claude Code AgentHandler configuration.
69#[derive(Debug, Clone, ToValue, FromValue, Schema)]
70#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
71pub struct ClaudeConfig {
72    /// Executable visible to the AI6-owned terminal environment.
73    #[map(default = String::from("claude"))]
74    pub executable: String,
75    /// Bytes of one line of Claude Code's output the Run holds before handing over what it
76    /// has. Default 67108864 (64 MiB).
77    #[map(default = 64 * 1024 * 1024)]
78    pub json_line_bytes: u64,
79    /// Bytes of one terminal control sequence before it is dropped. Default 64.
80    #[map(default = 64)]
81    pub csi_bytes: u64,
82    /// How many of the last non-JSON lines a failed Run quotes. Default 8.
83    #[map(default = 8)]
84    pub tail_lines: u64,
85    /// Bytes of each of those lines a failed Run quotes. Default 512.
86    #[map(default = 512)]
87    pub tail_line_bytes: u64,
88    /// Milliseconds a closing Run waits for Claude Code to have exited. Default 2000.
89    #[map(default = 2_000)]
90    pub close_wait_ms: u64,
91    /// Milliseconds the end of the output waits for Claude Code's exit status. Default 1000.
92    #[map(default = 1_000)]
93    pub exit_wait_ms: u64,
94    /// Milliseconds a listing of the models an account may use waits for Claude Code to answer.
95    /// Default 30000.
96    #[map(default = 30_000)]
97    pub models_wait_ms: u64,
98    /// Milliseconds a starting Run waits for Claude Code to answer its `initialize` request.
99    /// Claude Code answers only after its `SessionStart` hooks have run, so a slow host or a
100    /// user with several hooks needs more. Default 30000.
101    #[map(default = 30_000)]
102    pub initialize_wait_ms: u64,
103    /// Claude Code permission rules added to the allow list of a Mission's tools. A rule for a
104    /// tool the list keeps out (`WebFetch(domain:example.com)`, or `Bash` at `desk`) offers that
105    /// tool and lifts its default denial. Each rule starts with a letter.
106    #[schema(section = "agent")]
107    #[map(default)]
108    pub allowed_tools: Vec<String>,
109    /// Permission rules added to the deny list; a deny rule beats an allow rule.
110    #[schema(section = "agent")]
111    #[map(default)]
112    pub denied_tools: Vec<String>,
113}
114
115impl Default for ClaudeConfig {
116    fn default() -> Self {
117        Self {
118            executable: String::from("claude"),
119            json_line_bytes: 64 * 1024 * 1024,
120            csi_bytes: 64,
121            tail_lines: 8,
122            tail_line_bytes: 512,
123            close_wait_ms: 2_000,
124            exit_wait_ms: 1_000,
125            models_wait_ms: 30_000,
126            initialize_wait_ms: 30_000,
127            allowed_tools: Vec::new(),
128            denied_tools: Vec::new(),
129        }
130    }
131}
132
133/// What an Agent's `handler_settings` change about a Mission's tools, on top of [`FIELD_ALLOWED`]
134/// and [`FIELD_DENIED`] and, at `desk`, [`DESK_DENIED`]. Answer-only and assistant Runs ignore
135/// them. Unknown keys are refused.
136#[derive(Debug, Clone, Default, PartialEq, Eq)]
137struct ClaudeSettings {
138    /// Claude Code permission rules added to the allow list. A rule for a tool the list keeps
139    /// out (`WebFetch(domain:example.com)`, or `Bash` at `desk`) offers that tool and lifts its
140    /// default denial.
141    allowed_tools: Vec<String>,
142    /// Claude Code permission rules added to the deny list; a deny rule beats an allow rule.
143    denied_tools: Vec<String>,
144}
145
146impl ClaudeSettings {
147    /// Reads an Agent's settings. Each rule must start with a letter, so that none is read as
148    /// another option of the variadic flag it goes in.
149    fn of(config: &ClaudeConfig) -> Result<Self, String> {
150        let settings = Self {
151            allowed_tools: config.allowed_tools.clone(),
152            denied_tools: config.denied_tools.clone(),
153        };
154        for rule in settings.allowed_tools.iter().chain(&settings.denied_tools) {
155            if !rule.starts_with(|first: char| first.is_ascii_alphabetic()) {
156                return Err(format!("{rule:?} is not a Claude Code permission rule"));
157            }
158        }
159        Ok(settings)
160    }
161}
162
163/// The `request_id` of the `initialize` request that lists models.
164const MODELS_REQUEST: &str = "ai6-models";
165
166/// The format of Claude Code's Run transcript.
167pub const RECORD_FORMAT: &str = "claude-code-jsonl";
168
169/// Claude Code's transcript of the Run `query` names, when it is on this host.
170fn claude_record(query: &RunRecordQuery) -> Option<RunRecordFile> {
171    if !records::file_safe(&query.run_id) {
172        return None;
173    }
174    let root = records::configured_dir(&query.environment, "CLAUDE_CONFIG_DIR", ".claude")?;
175    let name = format!("{}.jsonl", query.run_id);
176    let path = records::find_file(&root.join("projects"), 1, &|file| file == name)?;
177    Some(RunRecordFile {
178        path: path.to_string_lossy().into_owned(),
179        format: RECORD_FORMAT.to_owned(),
180    })
181}
182
183/// The efforts `--effort` takes (Claude Code 2.1.318); a model takes them only where it says so.
184const EFFORTS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
185
186/// The models in Claude Code's answer to `initialize`, unknown when the answer has no list.
187fn models_of(listed: &InitializeAnswer) -> Answer<Vec<ModelInfo>> {
188    if !listed.succeeded() {
189        return Answer::unknown("Claude Code refused the request to list its models");
190    }
191    let Some(models) = listed.models() else {
192        return Answer::unknown("this Claude Code does not list its models");
193    };
194    Answer::known(
195        models
196            .filter_map(|model| {
197                let id = model.value.text()?;
198                let resolved = model
199                    .resolved_model
200                    .text()
201                    .filter(|resolved| *resolved != id);
202                let description = match (model.description.text(), resolved) {
203                    (Some(text), Some(resolved)) => {
204                        Some(format!("{text} (resolves to {resolved})"))
205                    }
206                    (Some(text), None) => Some(text.to_owned()),
207                    (None, Some(resolved)) => Some(format!("resolves to {resolved}")),
208                    (None, None) => None,
209                };
210                // A model that says it takes effort and names no levels takes the CLI's own.
211                let mut efforts: Vec<_> = (model.supports_effort.copied() == Some(true))
212                    .then(|| model.supported_effort_levels.get())
213                    .flatten()
214                    .into_iter()
215                    .flatten()
216                    .filter_map(|effort| effort.text().map(str::to_owned))
217                    .collect();
218                if efforts.is_empty()
219                    && listed.models().is_some_and(|mut models| {
220                        models.any(|entry| {
221                            entry.value.text() == Some(id)
222                                && entry.supports_effort.copied() == Some(true)
223                        })
224                    })
225                {
226                    efforts.extend(EFFORTS.map(str::to_owned));
227                }
228                Some(ModelInfo {
229                    name: model
230                        .display_name
231                        .text()
232                        .filter(|name| *name != id)
233                        .map(str::to_owned),
234                    id: id.to_owned(),
235                    description,
236                    efforts,
237                })
238            })
239            .collect(),
240    )
241}
242
243/// What Claude Code can start with: its models from `initialize` (each with the efforts it
244/// takes), the efforts its command line takes, the modes `coqui-acp-claude` maps to its
245/// permission modes, and nothing else, since it has no other option to choose and no command
246/// that lists its sessions.
247fn start_options_of(models: Answer<Vec<ModelInfo>>) -> StartOptions {
248    StartOptions {
249        models,
250        efforts: Answer::known(EFFORTS.iter().map(|id| ChoiceInfo::of(*id)).collect()),
251        modes: Answer::known(
252            NeutralMode::ALL
253                .into_iter()
254                .map(|mode| ChoiceInfo {
255                    id: mode.id().to_owned(),
256                    name: Some(mode.name().to_owned()),
257                    description: Some(mode.description().to_owned()),
258                })
259                .collect(),
260        ),
261        config: Answer::NotSupported,
262        sessions: Answer::NotSupported,
263    }
264}
265
266/// Starts and resumes Claude Code streams for AI6 Agent Runs.
267#[derive(Provider)]
268#[provider(
269    AgentHandler,
270    id = "claude",
271    name = "Claude Code",
272    crate = ::ai6::guatiao,
273    config = ClaudeConfig
274)]
275pub struct ClaudeHandler {
276    config: ClaudeConfig,
277    settings: ClaudeSettings,
278}
279
280impl TryFrom<ClaudeConfig> for ClaudeHandler {
281    type Error = ProviderError;
282
283    fn try_from(config: ClaudeConfig) -> Result<Self, Self::Error> {
284        if config.executable.trim().is_empty() {
285            return Err(refuse(
286                Status::GUATIAO_ERR_BAD_VALUE,
287                "Claude executable is empty",
288            ));
289        }
290        let settings = ClaudeSettings::of(&config).map_err(|reason| {
291            refuse(
292                Status::GUATIAO_ERR_BAD_VALUE,
293                format!("handler_settings: {reason}"),
294            )
295        })?;
296        Ok(Self { config, settings })
297    }
298}
299
300impl AgentHandler for ClaudeHandler {
301    /// Claude Code states its usage only in a turn's events: a `result` carries the process's
302    /// running spend and a `rate_limit_event` a window. Nothing reads it between turns, so a
303    /// Station keeps a timed retry for a limited account instead of polling.
304    fn usage_support(&self) -> Result<UsageSupport, ProviderError> {
305        Ok(UsageSupport::new(vec![UsageSource::Reported], true).needs_turn(true))
306    }
307
308    /// Claude Code with `-p` and stream-json reads JSON lines from standard input, which must not
309    /// be a terminal: on one it exits at once.
310    fn stdio(&self) -> Result<ai6::HarnessStdio, ProviderError> {
311        Ok(ai6::HarnessStdio::Json)
312    }
313
314    /// `/compact` and `/clear` are slash commands Claude Code runs as user turns in stream-json
315    /// input, in the process that holds the conversation.
316    fn session_commands(&self) -> Result<ai6::SessionCommands, ProviderError> {
317        Ok(ai6::SessionCommands {
318            compact: true,
319            clear: true,
320            unsupported_because: None,
321        })
322    }
323
324    fn read_only_refusal(&self) -> Result<Option<String>, ProviderError> {
325        Ok(None)
326    }
327
328    fn program(&self) -> Result<Option<String>, ProviderError> {
329        Ok(Some(self.config.executable.clone()))
330    }
331
332    /// Claude Code takes stdio MCP servers (`--mcp-config`) and filters a server's tools by rule; its
333    /// sandbox, where one runs (macOS, Linux and WSL2 with `bwrap` and `socat`), limits the commands
334    /// a Run starts to the profile's writes and hosts.
335    fn loadout_support(&self) -> Result<LoadoutSupport, ProviderError> {
336        Ok(loadout::support(std::env::var_os("PATH")))
337    }
338
339    /// stream-json's user message takes base64 `image` blocks beside its text.
340    fn image_input(&self) -> Result<Option<String>, ProviderError> {
341        Ok(None)
342    }
343
344    /// Claude Code keeps each Run as `projects/<directory>/<run>.jsonl` under its
345    /// configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`), one JSON object per
346    /// line.
347    fn run_record(&self, query: RunRecordQuery) -> Result<Option<RunRecordFile>, ProviderError> {
348        Ok(claude_record(&query))
349    }
350
351    /// Claude Code's sandbox runs on macOS (Seatbelt, built in) and on Linux and WSL2 with
352    /// `bwrap` and `socat` on the harness's `PATH`; on native Windows it runs commands
353    /// unsandboxed (code.claude.com/docs/en/sandboxing). WSL1 passes this check and is caught
354    /// by `failIfUnavailable`, which makes Claude Code exit at start.
355    fn assistant_scripts(
356        &self,
357        environment: BTreeMap<String, String>,
358    ) -> Result<Option<String>, ProviderError> {
359        Ok(script_sandbox_missing(
360            std::env::consts::OS,
361            environment
362                .iter()
363                .find(|(name, _)| name.eq_ignore_ascii_case("PATH"))
364                .map(|(_, path)| std::ffi::OsString::from(path))
365                .or_else(|| std::env::var_os("PATH")),
366        ))
367    }
368
369    /// An assistant's web tools are offered only to the hosts its network lists, and its scripts
370    /// run in the sandbox with those hosts and no other.
371    fn assistant_network(&self) -> Result<Option<String>, ProviderError> {
372        Ok(None)
373    }
374
375    /// Under `--restricted`, Claude Code 2.1.311 loads skills only from a `--plugin-dir`
376    /// plugin, which holds exactly the assistant's.
377    fn assistant_skills(&self) -> Result<Option<String>, ProviderError> {
378        Ok(None)
379    }
380
381    /// Each rule of `allowed_tools` that a default list does not hold. A rule the settings deny as
382    /// well allows nothing, so it is not one. A rule for what only `desk` keeps out is one however
383    /// the Agent is configured, since any Agent can come to work at `desk`.
384    fn weakenings(&self) -> Result<Vec<String>, ProviderError> {
385        let denied = &self.settings.denied_tools;
386        Ok(self
387            .settings
388            .allowed_tools
389            .iter()
390            .filter(|rule| !denied.contains(rule))
391            .filter_map(|rule| {
392                if DESK_DENIED.contains(&rule_tool(rule)) {
393                    Some(format!(
394                        "allowed_tools adds {rule} to what its desk Runs may call"
395                    ))
396                } else if FIELD_ALLOWED.contains(&rule.as_str()) {
397                    None
398                } else {
399                    Some(format!(
400                        "allowed_tools adds {rule} to what its field Runs may call"
401                    ))
402                }
403            })
404            .collect())
405    }
406
407    /// Claude Code answers an `initialize` control request with the models its account may
408    /// pick (`models[].value`, `displayName`, `resolvedModel`, the efforts each takes), before
409    /// any model turn and with no network. The list follows the kind of login the environment
410    /// gives it (an API key, a subscription, a gateway), not a check of the account's standing.
411    /// Its efforts and permission modes are what its command line takes; it has no other
412    /// option to choose and no command that lists its sessions, so those are not supported.
413    fn start_options(
414        &self,
415        environment: BTreeMap<String, String>,
416    ) -> Result<StartOptions, ProviderError> {
417        let wait = std::time::Duration::from_millis(self.config.models_wait_ms);
418        let asked = listing::ask(
419            &self.config.executable,
420            &[
421                "-p",
422                "--input-format",
423                "stream-json",
424                "--output-format",
425                "stream-json",
426                "--verbose",
427            ],
428            &environment,
429            wait,
430            |harness| {
431                harness.send(&InitializeRequest::new(MODELS_REQUEST))?;
432                harness.next_where(|line: &JsonObject<InitializeAnswer>| {
433                    line.0.answers(MODELS_REQUEST)
434                })
435            },
436        );
437        Ok(start_options_of(match asked {
438            Ok(answer) => models_of(&answer.0),
439            Err(reason) => Answer::unknown(reason),
440        }))
441    }
442
443    fn start(
444        &self,
445        request: AgentStart,
446        terminal: Object<dyn AgentTerminal>,
447    ) -> Result<Object<dyn ai6::AgentSession>, ProviderError> {
448        let minimum_version = request
449            .environment
450            .get(THEATER_PLUGIN_MIN_VERSION_ENV)
451            .cloned();
452        let mut argv = Vec::new();
453        let private = add_context(
454            &mut argv,
455            &request
456                .overlays
457                .with_routing(&request.initial_context, true),
458            request.assistant.as_ref(),
459        )?;
460        add_launch_options(
461            &mut argv,
462            request.model.as_deref(),
463            request.effort.as_deref(),
464        );
465        add_budget(&mut argv, request.max_cost_micro_usd);
466        if let Some(turns) = request
467            .environment
468            .get(TRIAL_MAX_TURNS_ENV)
469            .and_then(|turns| turns.parse::<std::num::NonZeroU32>().ok())
470        {
471            argv.extend(["--max-turns".to_owned(), turns.to_string()]);
472        }
473        let mode = Mode {
474            project_settings: request.project_settings,
475            project_mcp: request.project_mcp,
476            answer_only: request.answer_only,
477            commands: clearance_runs_commands(&request.clearance),
478            reads_only: clearance_reads_only(&request.clearance),
479        };
480        add_settings(
481            &mut argv,
482            &request.environment,
483            &request.working_directory,
484            mode,
485            &self.settings,
486            request.assistant.as_ref(),
487            &request.overlays,
488        )?;
489        loadout::apply(
490            &mut argv,
491            &request.loadout,
492            &request.environment,
493            &request.working_directory,
494            request.answer_only
495                || request.assistant.is_some()
496                || clearance_reads_only(&request.clearance),
497        )?;
498        // Where a transcript was written, so a start that fails leaves none behind.
499        let mut written = None;
500        let (session, expected_run_id) = if let Some(ledger) = &request.ledger {
501            let config_dir = records::configured_dir(
502                &request.environment,
503                "CLAUDE_CONFIG_DIR",
504                ".claude",
505            )
506            .ok_or_else(|| {
507                refuse(
508                    Status::GUATIAO_ERR_INTERNAL,
509                    "Claude Code's configuration directory (`CLAUDE_CONFIG_DIR` or `HOME`) is not set",
510                )
511            })?;
512            let session = ledger.session.clone().unwrap_or_else(new_session_id);
513            let expected = RunId::try_new(session.clone())
514                .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error.to_string()))?;
515            let document = &ledger.document;
516            let seed = SeedRequest::new(CLAUDE, &request.working_directory, &session);
517            write_transcript(document, &seed, &config_dir)
518                .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?;
519            written = Some((session.clone(), config_dir));
520            (SessionStart::Resume(session), Some(expected))
521        } else {
522            (SessionStart::Chosen, None)
523        };
524        let started = open(Opening {
525            config: &self.config,
526            terminal,
527            flags: argv,
528            cwd: &request.working_directory,
529            environment: harness_environment(
530                &request.environment,
531                request.answer_only || request.assistant.is_some(),
532                request.assistant.as_ref(),
533            ),
534            session,
535            expected_run_id,
536            restricted: restriction(request.answer_only, request.assistant.as_ref()),
537            private,
538            minimum_version,
539        });
540        let operation = match started {
541            Ok(operation) => operation,
542            Err(error) => {
543                if let Some((session, config_dir)) = &written {
544                    discard_transcript(CLAUDE, session, config_dir);
545                }
546                return Err(error);
547            }
548        };
549        // An empty prompt is the Station holding the first message until the hook that turns this Run's tools to
550        // its Theater is in force; it sends the message itself then.
551        if !request.prompt.is_empty()
552            && let Err(error) = operation.send(&request.prompt)
553        {
554            let _ = operation.close();
555            if let Some((session, config_dir)) = &written {
556                discard_transcript(CLAUDE, session, config_dir);
557            }
558            return Err(error);
559        }
560        Ok(operation.into_object())
561    }
562
563    fn resume(
564        &self,
565        request: AgentResume,
566        terminal: Object<dyn AgentTerminal>,
567    ) -> Result<Object<dyn ai6::AgentSession>, ProviderError> {
568        let minimum_version = request
569            .environment
570            .get(THEATER_PLUGIN_MIN_VERSION_ENV)
571            .cloned();
572        let expected_run_id = request.run_id.clone();
573        let mut argv = Vec::new();
574        // Claude Code 2.1.310 reuses the system prompt it recorded with the Run
575        // (`--system-prompt-snapshot`, on by default) until the Run is compacted; after
576        // that, or with the snapshot off, it builds the prompt from this launch's flags.
577        let private = add_context(
578            &mut argv,
579            &request
580                .overlays
581                .with_routing(&request.initial_context, true),
582            request.assistant.as_ref(),
583        )?;
584        add_launch_options(
585            &mut argv,
586            request.model.as_deref(),
587            request.effort.as_deref(),
588        );
589        add_budget(&mut argv, request.max_cost_micro_usd);
590        // Flags, not the Run's record, decide the tools: Claude Code 2.1.316 resumed a Run
591        // started with `Bash` and without it on the flags of each launch, either way round.
592        let mode = Mode {
593            project_settings: request.project_settings,
594            project_mcp: request.project_mcp,
595            answer_only: request.answer_only,
596            commands: clearance_runs_commands(&request.clearance),
597            reads_only: clearance_reads_only(&request.clearance),
598        };
599        add_settings(
600            &mut argv,
601            &request.environment,
602            &request.working_directory,
603            mode,
604            &self.settings,
605            request.assistant.as_ref(),
606            &request.overlays,
607        )?;
608        loadout::apply(
609            &mut argv,
610            &request.loadout,
611            &request.environment,
612            &request.working_directory,
613            request.answer_only
614                || request.assistant.is_some()
615                || clearance_reads_only(&request.clearance),
616        )?;
617        let operation = open(Opening {
618            config: &self.config,
619            terminal,
620            flags: argv,
621            cwd: &request.working_directory,
622            environment: harness_environment(
623                &request.environment,
624                request.answer_only || request.assistant.is_some(),
625                request.assistant.as_ref(),
626            ),
627            session: SessionStart::Resume(request.run_id.to_string()),
628            expected_run_id: Some(expected_run_id),
629            restricted: restriction(request.answer_only, request.assistant.as_ref()),
630            private,
631            minimum_version,
632        })?;
633        if let Some(message) = request.message
634            && let Err(error) = operation.send(&message)
635        {
636            let _ = operation.close();
637            return Err(error);
638        }
639        Ok(operation.into_object())
640    }
641}
642
643/// Gives Claude Code the Run's standing context: `parts`, then the assistant mode's context file
644/// when it has one, as one `--append-system-prompt-file`. A command line holds 32,767 characters
645/// on Windows and a charge's logbook alone can pass that, so the text goes through a file in a
646/// directory of its own (owner-only), which the returned guard removes when the Run ends.
647/// `None` when there is no context.
648fn add_context(
649    argv: &mut Vec<String>,
650    parts: &[String],
651    assistant: Option<&AssistantMode>,
652) -> Result<Option<tempfile::TempDir>, ProviderError> {
653    let mut text = parts.join("\n\n");
654    if let Some(path) = assistant.and_then(|mode| mode.context_file.as_ref()) {
655        let file = std::fs::read(path).map_err(|error| {
656            refuse(
657                Status::GUATIAO_ERR_INTERNAL,
658                format!("the assistant's context file: {error}"),
659            )
660        })?;
661        if !text.is_empty() {
662            text.push_str("\n\n");
663        }
664        text.push_str(&String::from_utf8_lossy(&file));
665    }
666    if text.is_empty() {
667        return Ok(None);
668    }
669    let directory = tempfile::Builder::new()
670        .prefix("ai6-claude-")
671        .tempdir()
672        .map_err(|error| {
673            refuse(
674                Status::GUATIAO_ERR_INTERNAL,
675                format!("the Run's private directory: {error}"),
676            )
677        })?;
678    #[cfg(unix)]
679    std::fs::set_permissions(
680        directory.path(),
681        std::os::unix::fs::PermissionsExt::from_mode(0o700),
682    )
683    .map_err(|error| {
684        refuse(
685            Status::GUATIAO_ERR_INTERNAL,
686            format!("the Run's private directory: {error}"),
687        )
688    })?;
689    let path = directory.path().join("context.md");
690    write_private(&path, text.as_bytes()).map_err(|error| {
691        refuse(
692            Status::GUATIAO_ERR_INTERNAL,
693            format!("the Run's context file: {error}"),
694        )
695    })?;
696    argv.extend([
697        "--append-system-prompt-file".to_owned(),
698        path.to_string_lossy().into_owned(),
699    ]);
700    Ok(Some(directory))
701}
702
703/// Writes `bytes` to a new file only its owner may read.
704fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
705    use std::io::Write;
706    let mut options = std::fs::OpenOptions::new();
707    options.write(true).create_new(true);
708    #[cfg(unix)]
709    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
710    options.open(path)?.write_all(bytes)
711}
712
713/// Adds the model and effort, each as one `--flag=VALUE` argument: a value that starts with `-`
714/// is then never read as another option.
715fn add_launch_options(argv: &mut Vec<String>, model: Option<&str>, effort: Option<&str>) {
716    if let Some(model) = model {
717        argv.push(format!("--model={model}"));
718    }
719    if let Some(effort) = effort {
720        argv.push(format!("--effort={effort}"));
721    }
722}
723
724/// The environment variable that names the plugin whose hook turns Claude Code's shell tools to the Theater: the
725/// take-over. The Station writes the plugin and its hook command; Claude Code only loads it.
726const THEATER_PLUGIN_ENV: &str = "AI6_THEATER_PLUGIN_DIR";
727
728/// The oldest Claude Code whose hook refuses a call when it fails, which the Station names beside the plugin: an
729/// older one lets a call go on when the hook cannot start, so a Run on it is refused.
730const THEATER_PLUGIN_MIN_VERSION_ENV: &str = "AI6_THEATER_PLUGIN_MIN_VERSION";
731
732/// Claude's shell tools: with the take-over they stay on in remote-hands mode, since the plugin's hook runs each
733/// command in the Theater.
734const SHELL_TOOLS: [&str; 2] = ["Bash", "PowerShell"];
735
736/// Claude's own shell and file tools, turned off in remote-hands mode so that nothing the
737/// harness does lands on the Station (the shell tools only when there is no take-over).
738const OWN_TOOLS: [&str; 8] = [
739    "Bash",
740    "PowerShell",
741    "Edit",
742    "Write",
743    "NotebookEdit",
744    "Read",
745    "Glob",
746    "Grep",
747];
748
749/// The built-in tools a Mission's Run is offered at `field` and `00` (`--tools`), and at `desk`
750/// less [`DESK_DENIED`]. `dontAsk` does not stop a tool that
751/// needs no approval: without this list Claude Code 2.1.316 ran `Agent`, `CronCreate` and
752/// `SendMessage` under it, and fetched `docs.python.org` with `WebFetch`, its rules empty. By
753/// default it offers the four `Task` tools in place of `TodoWrite`
754/// (code.claude.com/docs/en/tools-reference, "Task tool availability"), so both are named.
755const FIELD_TOOLS: [&str; 13] = [
756    "Read",
757    "Glob",
758    "Grep",
759    "Edit",
760    "Write",
761    "NotebookEdit",
762    "Bash",
763    "PowerShell",
764    "TodoWrite",
765    "TaskCreate",
766    "TaskGet",
767    "TaskList",
768    "TaskUpdate",
769];
770
771/// A Mission Run's allow rules at `field` and `00`, besides its own MCP servers, and at `desk`
772/// less [`DESK_DENIED`]. `Edit(/**)` is rooted at the
773/// working directory for a rule given as a flag, and covers `Write` and `NotebookEdit`
774/// (code.claude.com/docs/en/permissions, "Read and Edit").
775const FIELD_ALLOWED: [&str; 11] = [
776    "Read",
777    "Glob",
778    "Grep",
779    "Edit(/**)",
780    "Bash",
781    "PowerShell",
782    "TodoWrite",
783    "TaskCreate",
784    "TaskGet",
785    "TaskList",
786    "TaskUpdate",
787];
788
789/// What a field Run is denied by name, besides not being offered it: a deny rule beats any
790/// allow rule the user's or a pinned project's settings hold.
791const FIELD_DENIED: [&str; 3] = ["WebFetch", "WebSearch", "Agent"];
792
793/// What a `desk` Run is denied besides [`FIELD_DENIED`]: anything that runs a command, and
794/// the Theater's own writing tools, which take any path on the Theater where `Edit(/**)` stays in the working
795/// directory. A rule in `allowed_tools` lifts each, as a weakening.
796const DESK_DENIED: [&str; 6] = [
797    "Bash",
798    "PowerShell",
799    "mcp__ai6-theater__exec",
800    "mcp__ai6-theater__fs_write",
801    "mcp__ai6-theater__edit",
802    "mcp__ai6-theater__apply_patch",
803];
804
805/// Every tool an answer-only Run is denied by name, besides `--tools=` turning the
806/// built-in ones off: Claude's own tools, its web and sub-agent tools, and any MCP tool.
807const ANSWER_ONLY_DENIED: &str = "Bash,PowerShell,Edit,Write,NotebookEdit,Read,Glob,Grep,\
808                                  WebFetch,WebSearch,Task,Agent,TodoWrite,mcp__*";
809
810/// Turns off Claude Code's server-side advisor tool, which the API runs outside any MCP
811/// server and which neither `--restricted`, `--tools=` nor a deny rule removes
812/// (code.claude.com/docs/en/advisor; read by Claude Code 2.1.310 from its environment).
813const DISABLE_ADVISOR_ENV: &str = "CLAUDE_CODE_DISABLE_ADVISOR_TOOL";
814
815/// Turns off Claude Code's auto memory, which would keep notes under the user's own
816/// `~/.claude/projects/` beside the assistant's memory in her repository
817/// (code.claude.com/docs/en/memory, read 2026-10-27).
818const DISABLE_AUTO_MEMORY_ENV: &str = "CLAUDE_CODE_DISABLE_AUTO_MEMORY";
819
820/// Stops Claude Code loading any `CLAUDE.md` memory file, the user's own among them: with
821/// `--setting-sources user` alone the global one still reached the model
822/// (Claude Code 2.1.326, probed against the loopback stand-in).
823const DISABLE_CLAUDE_MDS_ENV: &str = "CLAUDE_CODE_DISABLE_CLAUDE_MDS";
824
825/// Turns WebFetch off altogether (code.claude.com/docs/en/env-vars, Claude Code 2.1.285 or
826/// later), beside leaving it out of `--tools`.
827const DISABLE_WEB_FETCH_ENV: &str = "CLAUDE_CODE_DISABLE_WEB_FETCH";
828
829/// Milliseconds Claude Code's MCP client waits for a tool call (default 60 s, which would end a
830/// longer `theater_run`); the Station names the longest call in `AI6_THEATER_MCP_TIMEOUT_MS`.
831const MCP_TOOL_TIMEOUT_ENV: &str = "MCP_TOOL_TIMEOUT";
832
833/// Turns off every connection Claude Code makes besides the model's and its MCP servers':
834/// telemetry (event logging to api.anthropic.com), feature-flag fetches, update checks and
835/// feedback. Measured with Claude Code 2.1.335 on Linux in a namespace with only loopback: with
836/// `ANTHROPIC_BASE_URL` on loopback it still dialled api.anthropic.com:443 at start, and with this
837/// set it dialled nothing (`DISABLE_TELEMETRY` alone left one attempt under an OAuth login).
838const DISABLE_NONESSENTIAL_TRAFFIC_ENV: &str = "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC";
839
840/// The harness's environment: `environment`, with the advisor turned off for a restricted
841/// (answer-only or assistant) Run, instruction files off for an answer-only one, auto memory off
842/// and nonessential traffic off ([`DISABLE_NONESSENTIAL_TRAFFIC_ENV`], unless the environment
843/// sets it) for an assistant, and WebFetch off for an assistant whose network reaches no host. A Run with
844/// the Theater tools gets [`MCP_TOOL_TIMEOUT_ENV`] set to the longest call, unless the Agent's own
845/// environment sets it.
846fn harness_environment(
847    environment: &BTreeMap<String, String>,
848    restricted: bool,
849    assistant: Option<&AssistantMode>,
850) -> BTreeMap<String, String> {
851    let mut environment = environment.clone();
852    if has_endpoint(&environment, "AI6_THEATER_MCP")
853        && let Some(timeout) = environment.get("AI6_THEATER_MCP_TIMEOUT_MS").cloned()
854    {
855        environment
856            .entry(MCP_TOOL_TIMEOUT_ENV.to_owned())
857            .or_insert(timeout);
858    }
859    if is_trial(&environment) {
860        environment.insert(DISABLE_WEB_FETCH_ENV.to_owned(), "1".to_owned());
861    }
862    if restricted {
863        environment.insert(DISABLE_ADVISOR_ENV.to_owned(), "1".to_owned());
864    }
865    if restricted && assistant.is_none() {
866        environment.insert(DISABLE_CLAUDE_MDS_ENV.to_owned(), "1".to_owned());
867    }
868    if let Some(mode) = assistant {
869        environment.insert(DISABLE_AUTO_MEMORY_ENV.to_owned(), "1".to_owned());
870        // The Agent's own environment wins, so an operator can turn it back on.
871        environment
872            .entry(DISABLE_NONESSENTIAL_TRAFFIC_ENV.to_owned())
873            .or_insert_with(|| "1".to_owned());
874        if mode.network.reaches_nothing() {
875            environment.insert(DISABLE_WEB_FETCH_ENV.to_owned(), "1".to_owned());
876        }
877    }
878    environment
879}
880
881/// What a restricted (answer-only or assistant) Run may call: its MCP servers' tools, and
882/// the built-in tools its mode offers ([`offered_tools`]).
883#[derive(Debug, Clone, Default, PartialEq, Eq)]
884struct Allowed {
885    servers: Vec<String>,
886    builtins: Vec<&'static str>,
887}
888
889/// What a restricted Run may call, `None` for a Run that is not restricted.
890fn restriction(answer_only: bool, assistant: Option<&AssistantMode>) -> Option<Allowed> {
891    match assistant {
892        Some(mode) => Some(Allowed {
893            servers: mode
894                .mcp_servers
895                .iter()
896                .map(|server| server.name.clone())
897                .collect(),
898            builtins: offered_tools(mode),
899        }),
900        None => answer_only.then(Allowed::default),
901    }
902}
903
904/// The built-in tools an assistant's mode offers: the file tools with directories to write,
905/// `Bash` with interpreters, `WebFetch` when the network reaches a host, `WebSearch` only
906/// when it is open (a search takes no host list), and `Skill` with skills.
907fn offered_tools(mode: &AssistantMode) -> Vec<&'static str> {
908    let mut tools = Vec::new();
909    if !mode.files.is_empty() {
910        tools.extend(ASSISTANT_FILE_TOOLS.split(','));
911    }
912    if !mode.interpreters.is_empty() {
913        tools.push("Bash");
914    }
915    if !mode.network.reaches_nothing() {
916        tools.push("WebFetch");
917    }
918    if mode.network.open() {
919        tools.push("WebSearch");
920    }
921    if !mode.skills.is_empty() {
922        tools.push(SKILL_TOOL);
923    }
924    tools
925}
926
927/// The built-in tool that loads a skill, offered to an assistant with skills.
928const SKILL_TOOL: &str = "Skill";
929
930/// What AI6 decided about the Run's settings.
931#[derive(Clone, Copy)]
932struct Mode {
933    project_settings: bool,
934    project_mcp: bool,
935    answer_only: bool,
936    /// Whether the clearance allows a command tool ([`clearance_runs_commands`]).
937    commands: bool,
938    /// Whether the Run is held to reading until its plan passes ([`clearance_reads_only`]).
939    reads_only: bool,
940}
941
942/// Every built-in tool an assistant Run is denied by name, besides `--tools=` turning the
943/// built-in ones off. Unlike [`ANSWER_ONLY_DENIED`] it leaves MCP tools alone: the assistant's
944/// servers are how it works.
945const ASSISTANT_DENIED: &str = "Bash,PowerShell,Edit,Write,NotebookEdit,Read,Glob,Grep,\
946                                WebFetch,WebSearch,Task,Agent,TodoWrite,Skill";
947
948/// The built-in tools of an assistant whose mode names directories to write.
949const ASSISTANT_FILE_TOOLS: &str = "Read,Write,Edit,Glob,Grep";
950
951/// The rules that deny writing any path with a name starting with `.` (`.git`,
952/// `.gitattributes`, `.claude`), whatever the allow rules say. Measured with Claude Code
953/// 2.1.310 on Windows against a loopback stand-in for the API: Write and Edit to `.git/config`,
954/// `.GIT/config`, `.git./config`, `PERSONAL\.git\config`, `.gitattributes`, `notes/.hidden`
955/// and `scratch/.x` were refused, and so were writes through 8.3 short names (`GIT~1\config`,
956/// `GITATT~1`), even after a read.
957const DOT_PATHS_DENIED: [&str; 2] = ["Edit(**/.*)", "Edit(**/.*/**)"];
958
959/// Model credentials Claude Code reads (code.claude.com/docs/en/env-vars), removed from every
960/// script's environment even when the harness's own environment does not name them.
961const MODEL_CREDENTIALS: [&str; 3] = [
962    "ANTHROPIC_API_KEY",
963    "ANTHROPIC_AUTH_TOKEN",
964    "CLAUDE_CODE_OAUTH_TOKEN",
965];
966
967/// Adds the settings flags: assistant ([`add_assistant`]), answer-only ([`add_answer_only`]),
968/// or the project settings AI6 allowed, the Station's MCP servers and the green ink gate.
969fn add_settings(
970    argv: &mut Vec<String>,
971    environment: &BTreeMap<String, String>,
972    working_directory: &str,
973    mode: Mode,
974    settings: &ClaudeSettings,
975    assistant: Option<&AssistantMode>,
976    overlays: &RunOverlays,
977) -> Result<(), ProviderError> {
978    if let Some(assistant) = assistant {
979        add_assistant(argv, environment, working_directory, assistant)?;
980    } else if mode.answer_only {
981        add_answer_only(argv);
982    } else if mode.reads_only {
983        add_project_settings(argv, false, false);
984        add_read_only_tools(argv, environment);
985        add_mcp(argv, environment);
986        add_overlay_skills(argv, overlays);
987        add_mission_settings(argv, environment, overlays);
988    } else {
989        add_project_settings(argv, mode.project_settings, mode.project_mcp);
990        add_field_tools(argv, environment, settings, mode.commands);
991        add_mcp(argv, environment);
992        add_overlay_skills(argv, overlays);
993        add_mission_settings(argv, environment, overlays);
994    }
995    Ok(())
996}
997
998/// Whether the launch has a native overlay skill to load: a plugin directory and a skill for it.
999fn loads_overlay_skills(overlays: &RunOverlays) -> bool {
1000    overlays.plugin_dir.is_some() && overlays.skills.iter().any(|skill| skill.native)
1001}
1002
1003/// Loads a Mission's overlay skills: `Skill` joins `--tools`, closed by the next flag, each skill is
1004/// allowed as `Skill(ai6:<name>)`, and the Station's plugin directory is `--plugin-dir`. Claude Code
1005/// 2.1.318 listed and launched the plugin's skills with this under `dontAsk`, at `field` and `desk`,
1006/// and with no `Skill` in `--tools` it answered `No such tool available`.
1007fn add_overlay_skills(argv: &mut Vec<String>, overlays: &RunOverlays) {
1008    let Some(dir) = overlays
1009        .plugin_dir
1010        .as_ref()
1011        .filter(|_| loads_overlay_skills(overlays))
1012    else {
1013        return;
1014    };
1015    let mut add_to = |flag: &str, added: &str| {
1016        if let Some(at) = argv.iter().position(|arg| arg == flag)
1017            && let Some(list) = argv.get_mut(at + 1)
1018        {
1019            if !list.is_empty() {
1020                list.push(',');
1021            }
1022            list.push_str(added);
1023        }
1024    };
1025    add_to("--tools", SKILL_TOOL);
1026    let rules: Vec<String> = overlays
1027        .skills
1028        .iter()
1029        .filter(|skill| skill.native)
1030        .map(|skill| format!("{SKILL_TOOL}({SKILLS_PLUGIN}:{})", skill.name))
1031        .collect();
1032    add_to("--allowedTools", &rules.join(","));
1033    argv.extend(["--plugin-dir".to_owned(), dir.clone()]);
1034}
1035
1036/// The one `--settings` a Mission's Run gets: the green ink gate when it has a Station to ask,
1037/// and, with overlay skills, no skill's injected command: a skill Claude Code ships or the user's
1038/// directory holds is not one the Station checked, and its command would run before the gate saw it.
1039fn add_mission_settings(
1040    argv: &mut Vec<String>,
1041    environment: &BTreeMap<String, String>,
1042    overlays: &RunOverlays,
1043) {
1044    let mut settings = gate_of(environment).unwrap_or_default();
1045    add_overlay_hooks(&mut settings, environment, overlays);
1046    if loads_overlay_skills(overlays) {
1047        settings.disable_skill_shell_execution();
1048    }
1049    if !settings.is_empty() {
1050        argv.extend(["--settings".to_owned(), settings.to_text()]);
1051    }
1052}
1053
1054/// Adds the hooks of the Run's overlays that are on to `settings`: one entry per Claude Code event,
1055/// running `ai6 overlay-hook` with that event's hooks, which runs them as the specification says and
1056/// answers in what Claude Code reads. They sit beside the green ink gate, whose deny stands over any
1057/// of their answers; an overlay's allow is never passed on.
1058fn add_overlay_hooks(
1059    settings: &mut SettingsDocument,
1060    environment: &BTreeMap<String, String>,
1061    overlays: &RunOverlays,
1062) {
1063    use ai6::directorates::section_00::overlay_hook::claude_event_named;
1064    if overlays.hooks.is_empty() {
1065        return;
1066    }
1067    let Some(program) = hook_program(environment) else {
1068        return;
1069    };
1070    let mut events: Vec<(&str, Vec<&ai6::RunHook>)> = Vec::new();
1071    for hook in &overlays.hooks {
1072        let Some(name) = claude_event_named(&hook.event) else {
1073            continue;
1074        };
1075        match events.iter_mut().find(|(held, _)| *held == name) {
1076            Some((_, group)) => group.push(hook),
1077            None => events.push((name, vec![hook])),
1078        }
1079    }
1080    settings.set_disable_all_hooks(false);
1081    for (name, group) in events {
1082        let limit: u64 = group.iter().map(|hook| hook.timeout).sum::<u64>() + 5;
1083        let tool = matches!(name, "PreToolUse" | "PostToolUse");
1084        let hooks = serde_json::to_string(&group).unwrap_or_default();
1085        let command = HookCommand::new(
1086            &program,
1087            [
1088                "overlay-hook",
1089                "--harness",
1090                "claude-code",
1091                "--hooks",
1092                &hooks,
1093            ]
1094            .map(str::to_owned)
1095            .to_vec(),
1096            limit,
1097            group.iter().any(|hook| hook.refuse),
1098        );
1099        settings.push_hook_group(
1100            name,
1101            HookGroup::of_overlay(vec![command], tool.then_some("*")),
1102        );
1103    }
1104}
1105
1106/// An assistant Run, built from its mode's parts: answer-only's restrictions
1107/// (`--restricted`, only the user's settings) with exactly the mode's MCP servers connected
1108/// (`--strict-mcp-config`) and their tools allowed without a prompt (`--allowedTools
1109/// mcp__<name>`), and only the built-in tools [`offered_tools`] names (`--tools`; none is
1110/// `--tools=`), each other one denied by name.
1111///
1112/// With any built-in tool the Run runs under `--permission-mode dontAsk`, which denies
1113/// every call no rule allows (code.claude.com/docs/en/permissions):
1114///
1115/// - `files`: the file tools, which `--restricted` confines to the working directory; reading
1116///   is allowed anywhere there, writing only under each directory (`Edit(/<dir>/**)`, relative
1117///   to the working directory; Edit rules cover Write), never to a path with a name starting
1118///   with `.`.
1119/// - `interpreters`: `Bash`, allowed only as `Bash(<interpreter> *)`, inside the sandbox
1120///   [`script_settings`] describes.
1121/// - network `limited` with hosts: `WebFetch`, allowed as `WebFetch(domain:<host>)` for each
1122///   host (which also lets the sandbox's scripts reach it); `open`: `WebFetch(domain:*)` and
1123///   `WebSearch`. WebFetch runs outside the sandbox, so its rules are its only limit.
1124/// - `skills`: `Skill`, each skill allowed as `Skill(ai6:<name>)`, and the mode's `skills_dir`
1125///   as `--plugin-dir`: under `--restricted`, Claude Code 2.1.311 loads no skill from the
1126///   working directory, the user's directory or an installed plugin, and does load a
1127///   `--plugin-dir` plugin's. Only the skills installed there can load, since an allow rule
1128///   does not keep another skill out. Without `skill_commands`, `disableSkillShellExecution`
1129///   keeps a skill's injected commands from running.
1130///
1131/// Every setting the parts call for goes in one `--settings` value. A `context_file` is joined
1132/// to the standing context by [`add_context`].
1133fn add_assistant(
1134    argv: &mut Vec<String>,
1135    environment: &BTreeMap<String, String>,
1136    working_directory: &str,
1137    mode: &AssistantMode,
1138) -> Result<(), ProviderError> {
1139    mode.validate()
1140        .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
1141    let mut servers = McpConfig::default();
1142    let mut allowed = Vec::new();
1143    for server in &mode.mcp_servers {
1144        if !has_endpoint(environment, &server.env_prefix) {
1145            return Err(refuse(
1146                Status::GUATIAO_ERR_BAD_VALUE,
1147                format!(
1148                    "the environment carries no URL and token for MCP server {:?}",
1149                    server.name
1150                ),
1151            ));
1152        }
1153        servers.add(&server.name, http_server(&server.env_prefix));
1154        allowed.push(format!("mcp__{}", server.name));
1155    }
1156    let offered = offered_tools(mode);
1157    if let Some(found) = managed_settings_at(std::env::consts::OS, std::path::Path::exists) {
1158        eprintln!(
1159            "ai6: warning: Claude Code managed settings at {} apply to Moneypenny's harness too: they \
1160             merge with AI6's sandbox and permissions, and `allowManagedHooksOnly` there would \
1161             drop the WebFetch gate",
1162            found.display()
1163        );
1164    }
1165    // Under `dontAsk` Claude Code 2.1.310 still fetches its own documentation domains
1166    // (docs.python.org, developer.mozilla.org) when no rule names them, and WebFetch runs
1167    // outside the sandbox, so a hook gates every WebFetch: a `limited` mode to its listed
1168    // hosts, both off the deny list, by name and by the addresses a name resolves to.
1169    let web_gate = if offered.contains(&"WebFetch") {
1170        Some(hook_program(environment).ok_or_else(|| {
1171            refuse(
1172                Status::GUATIAO_ERR_UNSUPPORTED,
1173                "no program to run as the assistant's WebFetch gate",
1174            )
1175        })?)
1176    } else {
1177        None
1178    };
1179    let mut denied: Vec<String> = ASSISTANT_DENIED
1180        .split(',')
1181        .filter(|tool| !offered.contains(tool))
1182        .map(str::to_owned)
1183        .collect();
1184    argv.push("--restricted".to_owned());
1185    if offered.is_empty() {
1186        argv.push("--tools=".to_owned());
1187    } else {
1188        argv.extend([
1189            "--tools".to_owned(),
1190            offered.join(","),
1191            "--permission-mode".to_owned(),
1192            "dontAsk".to_owned(),
1193        ]);
1194    }
1195    if !mode.files.is_empty() {
1196        denied.extend(DOT_PATHS_DENIED.map(str::to_owned));
1197        allowed.extend(["Read".to_owned(), "Glob".to_owned(), "Grep".to_owned()]);
1198        allowed.extend(mode.files.iter().map(|path| format!("Edit(/{path}/**)")));
1199    }
1200    allowed.extend(
1201        mode.interpreters
1202            .iter()
1203            .map(|interpreter| format!("Bash({interpreter} *)")),
1204    );
1205    if mode.network.open() {
1206        allowed.extend(["WebFetch(domain:*)".to_owned(), "WebSearch".to_owned()]);
1207    } else if !mode.network.reaches_nothing() {
1208        allowed.extend(
1209            mode.network
1210                .allowed_hosts
1211                .iter()
1212                .map(|host| format!("WebFetch(domain:{host})")),
1213        );
1214    }
1215    allowed.extend(
1216        mode.skills
1217            .iter()
1218            .map(|name| format!("{SKILL_TOOL}({SKILLS_PLUGIN}:{name})")),
1219    );
1220    argv.extend([
1221        "--disallowedTools".to_owned(),
1222        denied.join(","),
1223        "--allowedTools".to_owned(),
1224        allowed.join(","),
1225        "--setting-sources".to_owned(),
1226        "user".to_owned(),
1227        "--strict-mcp-config".to_owned(),
1228        "--mcp-config".to_owned(),
1229        servers.to_text(),
1230    ]);
1231    let skills_dir = mode.skills_dir.as_ref().filter(|_| !mode.skills.is_empty());
1232    if let Some(dir) = skills_dir {
1233        argv.extend(["--plugin-dir".to_owned(), dir.clone()]);
1234    }
1235    let mut settings = SettingsDocument::default();
1236    if !mode.interpreters.is_empty() {
1237        settings.merge(script_settings(mode, working_directory, environment)?);
1238    }
1239    if skills_dir.is_some() && !mode.skill_commands {
1240        settings.disable_skill_shell_execution();
1241    }
1242    if let Some(program) = web_gate {
1243        // A limited network allows exactly its hosts; an open one allows any but the denied.
1244        let allow = if mode.network.open() {
1245            Vec::new()
1246        } else {
1247            mode.network.allowed_hosts.clone()
1248        };
1249        settings.merge(web_gate_settings(&program, &allow, &mode.network.denied));
1250    }
1251    if !settings.is_empty() {
1252        argv.extend(["--settings".to_owned(), settings.to_text()]);
1253    }
1254    Ok(())
1255}
1256
1257/// The paths a sandboxed script may read on `os`, besides the working directory and the
1258/// install directories of its interpreters: the system's programs and libraries, only the
1259/// files under `/etc` that an interpreter, its resolver and TLS need, and the device files a
1260/// program opens. Anything else stays unreadable under `denyRead: ["/"]`: the Station's
1261/// configuration and secrets under `/etc`, `/opt`, `/var`, the home directory, `/proc` of other
1262/// processes. Measured for `python3` (stdlib, `ssl`, `sqlite3`, `os.urandom`, HTTPS through the
1263/// sandbox's proxy) on Linux with Claude Code 2.1.310; the macOS list is inferred. Other
1264/// platforms have no sandbox and never reach here.
1265fn script_read_roots(os: &str) -> &'static [&'static str] {
1266    match os {
1267        "macos" => &[
1268            "/usr",
1269            "/bin",
1270            "/sbin",
1271            "/System",
1272            "/Library/Developer/CommandLineTools",
1273            "/private/var/db/xcode_select_link",
1274            "/private/var/select",
1275            "/private/etc/ssl",
1276            "/private/etc/hosts",
1277            "/private/etc/resolv.conf",
1278            "/private/etc/localtime",
1279            "/private/etc/passwd",
1280            "/private/etc/group",
1281            "/private/etc/services",
1282            "/private/etc/protocols",
1283            "/dev/null",
1284            "/dev/zero",
1285            "/dev/random",
1286            "/dev/urandom",
1287            "/dev/tty",
1288        ],
1289        // Linux and WSL2. The two `/tmp` entries are the sandbox's own network relay sockets (a
1290        // script reaches its proxy only through them; measured with Claude Code 2.1.310), where
1291        // they are when the Run has no `CLAUDE_CODE_TMPDIR` of its own: re-opened by name,
1292        // so the rest of `/tmp`, AI6's own IPC sockets among it, stays unreadable.
1293        "linux" => &[
1294            "/usr",
1295            "/bin",
1296            "/sbin",
1297            "/lib",
1298            "/lib64",
1299            "/etc/ld.so.cache",
1300            "/etc/ld.so.conf",
1301            "/etc/ld.so.conf.d",
1302            "/etc/ssl",
1303            "/etc/pki",
1304            "/etc/crypto-policies",
1305            "/etc/ca-certificates",
1306            "/etc/localtime",
1307            "/etc/hosts",
1308            "/etc/resolv.conf",
1309            "/etc/nsswitch.conf",
1310            "/etc/host.conf",
1311            "/etc/gai.conf",
1312            "/etc/services",
1313            "/etc/protocols",
1314            "/etc/passwd",
1315            "/etc/group",
1316            "/etc/alternatives",
1317            "/dev/null",
1318            "/dev/zero",
1319            "/dev/random",
1320            "/dev/urandom",
1321            "/dev/tty",
1322            "/tmp/claude-http-*.sock",
1323            "/tmp/srt-mux-*.sock",
1324        ],
1325        _ => &[],
1326    }
1327}
1328
1329/// The Claude Code settings that confine an assistant's scripts (code.claude.com/docs/en/
1330/// sandboxing and /settings-reference): the sandbox on, Claude Code exiting at start when it
1331/// cannot run it (`failIfUnavailable`), every command still checked against the allow rules
1332/// (`autoAllowBashIfSandboxed: false`) and none retried outside it
1333/// (`allowUnsandboxedCommands: false`). Reads are denied everywhere (`denyRead: ["/"]`) but the
1334/// working directory, the system paths an interpreter needs ([`script_read_roots`]) and the
1335/// interpreters' own install directories, with the Station's own paths denied again
1336/// ([`programs::station_paths`]). Scripts write only the mode's directories, never `read_only`, `.claude`
1337/// or a `.git` under the working directory (which an unsandboxed git could act on); reach only
1338/// the mode's hosts (every host under `open`) less the deny list's names and addresses
1339/// (`deniedDomains`); see no environment variable but [`SCRIPT_ENVIRONMENT`]
1340/// (`credentials.envVars`); and read no directory a credential variable names
1341/// (`credentials.files`). The file tools are kept to the working directory too
1342/// (`blockReadsOutsideWorkingDirectories`). With `unsandboxed` the sandbox is off and none of
1343/// these applies to scripts.
1344///
1345/// Refused: a deny list with a network or a category wider than one address while scripts
1346/// reach a host, since the sandbox's proxy matches `deniedDomains` by name and by single
1347/// address, not by network; and a variable of the environment `credentials.envVars` cannot
1348/// name, which would reach scripts.
1349fn script_settings(
1350    mode: &AssistantMode,
1351    working_directory: &str,
1352    environment: &BTreeMap<String, String>,
1353) -> Result<SettingsDocument, ProviderError> {
1354    let permissions = Permissions {
1355        block_reads_outside_working_directories: true,
1356    };
1357    if mode.unsandboxed {
1358        let mut settings = SettingsDocument::default();
1359        settings.set_sandbox(Sandbox::Script(ScriptSandbox {
1360            enabled: false,
1361            fail_if_unavailable: None,
1362            auto_allow_bash_if_sandboxed: None,
1363            allow_unsandboxed_commands: None,
1364            filesystem: None,
1365            network: None,
1366            credentials: None,
1367        }));
1368        settings.set_permissions(permissions);
1369        return Ok(settings);
1370    }
1371    let denied = DenyList::parse(&mode.network.denied)
1372        .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
1373    let ranges = denied.ranges();
1374    if !mode.network.reaches_nothing() && !ranges.is_empty() {
1375        let named: Vec<String> = ranges.iter().map(|entry| format!("{entry:?}")).collect();
1376        return Err(refuse(
1377            Status::GUATIAO_ERR_UNSUPPORTED,
1378            format!(
1379                "Claude Code's sandbox proxy refuses hosts by name and by single address, not by \
1380                 network, so scripts cannot be kept from {}; deny single addresses and host \
1381                 names, or run no interpreter",
1382                named.join(", ")
1383            ),
1384        ));
1385    }
1386    if let Some(name) = environment.keys().find(|name| !variable_name(name)) {
1387        return Err(refuse(
1388            Status::GUATIAO_ERR_BAD_VALUE,
1389            format!(
1390                "the harness's environment has {name:?}, which Claude Code's sandbox cannot hide \
1391                 from scripts (credentials.envVars takes letters, digits and '_')"
1392            ),
1393        ));
1394    }
1395    let root = std::path::Path::new(working_directory);
1396    let under = |path: &str| root.join(path).to_string_lossy().into_owned();
1397    let mut deny_write: Vec<String> = mode.read_only.iter().map(|path| under(path)).collect();
1398    deny_write.push(under(".claude"));
1399    // A script could plant a `.git/config` with `core.fsmonitor` or a hook that the Station's
1400    // own unsandboxed git would run; her repositories' git directories live outside the
1401    // working directory, so nothing here needs a writable `.git`.
1402    deny_write.push(under(".git"));
1403    deny_write.extend(mode.files.iter().map(|dir| under(&format!("{dir}/.git"))));
1404    let interpreters: Vec<&str> = mode.interpreters.iter().map(String::as_str).collect();
1405    let program_dirs = programs::program_dirs(&interpreters, root, environment);
1406    let mut allow_read: Vec<String> = vec![working_directory.to_owned()];
1407    allow_read.extend(
1408        script_read_roots(std::env::consts::OS)
1409            .iter()
1410            .map(|dir| (*dir).to_owned()),
1411    );
1412    allow_read.extend(
1413        program_dirs
1414            .iter()
1415            .map(|dir| dir.to_string_lossy().into_owned()),
1416    );
1417    // With a temporary directory of the Run's own, Claude Code 2.1.310 puts the sandbox's
1418    // network relay sockets there instead of `/tmp`: they are re-opened by name, since
1419    // re-opening the whole directory read-only covers the writable `$TMPDIR` under it and
1420    // `bwrap` then fails to start.
1421    if let Some(temp) = environment
1422        .get("CLAUDE_CODE_TMPDIR")
1423        .filter(|temp| std::path::Path::new(temp.as_str()).is_absolute())
1424    {
1425        let temp = std::path::Path::new(temp.as_str());
1426        for socket in ["claude-http-*.sock", "srt-mux-*.sock"] {
1427            allow_read.push(temp.join(socket).to_string_lossy().into_owned());
1428        }
1429    }
1430    let mut deny_read = vec!["/".to_owned()];
1431    deny_read.extend(
1432        programs::station_paths(root, &program_dirs, &mode.station_paths)
1433            .iter()
1434            .map(|path| path.to_string_lossy().into_owned()),
1435    );
1436    // Claude Code 2.1.310 does not open the sandbox to `WebFetch(domain:*)` given in
1437    // `--allowedTools`, so an open network names every host here itself.
1438    let hosts: Vec<&str> = match mode.network.policy.as_str() {
1439        "open" => vec!["*"],
1440        "limited" => mode
1441            .network
1442            .allowed_hosts
1443            .iter()
1444            .map(String::as_str)
1445            .collect(),
1446        _ => Vec::new(),
1447    };
1448    let mut hidden: std::collections::BTreeSet<&str> = MODEL_CREDENTIALS.into_iter().collect();
1449    hidden.extend(environment.keys().map(String::as_str).filter(|name| {
1450        !SCRIPT_ENVIRONMENT
1451            .iter()
1452            .any(|kept| kept.eq_ignore_ascii_case(name))
1453    }));
1454    let files: Vec<DeniedFile> = environment
1455        .iter()
1456        .filter(|(name, _)| credential_dir_var(name))
1457        .map(|(_, path)| DeniedFile {
1458            path: path.clone(),
1459            mode: "deny".to_owned(),
1460        })
1461        .collect();
1462    let mut settings = SettingsDocument::default();
1463    settings.set_sandbox(Sandbox::Script(ScriptSandbox {
1464        enabled: true,
1465        fail_if_unavailable: Some(true),
1466        auto_allow_bash_if_sandboxed: Some(false),
1467        allow_unsandboxed_commands: Some(false),
1468        filesystem: Some(ScriptFilesystem {
1469            allow_write: mode.files.iter().map(|path| under(path)).collect(),
1470            deny_write,
1471            deny_read,
1472            allow_read,
1473        }),
1474        network: Some(ScriptNetwork {
1475            allowed_domains: hosts.into_iter().map(str::to_owned).collect(),
1476            denied_domains: denied.names_and_addresses(),
1477            strict_allowlist: true,
1478        }),
1479        credentials: Some(Credentials {
1480            env_vars: hidden
1481                .into_iter()
1482                .map(|name| Denied {
1483                    name: name.to_owned(),
1484                    mode: "deny".to_owned(),
1485                })
1486                .collect(),
1487            files,
1488        }),
1489    }));
1490    settings.set_permissions(permissions);
1491    Ok(settings)
1492}
1493
1494/// The Claude Code settings that keep an assistant's WebFetch to `allow` and off `deny`: a
1495/// `PreToolUse` hook on `WebFetch` running `PROGRAM assistant web-gate [--hosts …] [--deny …]`,
1496/// which denies a fetch the deployment does not allow
1497/// (`ai6::directorates::section_00::gate::web_fetch_gate`), with hooks on whatever the user's
1498/// settings say and a hook that fails to run blocking the fetch (`onFailure`, Claude Code
1499/// 2.1.295 or later), as the green ink gate's. An empty `allow` (an open network) allows every
1500/// host but the denied ones.
1501fn web_gate_settings(program: &str, allow: &[String], deny: &[String]) -> SettingsDocument {
1502    let mut args: Vec<String> = WEB_GATE_ARGS.map(str::to_owned).to_vec();
1503    if !allow.is_empty() {
1504        args.extend(["--hosts".to_owned(), allow.join(",")]);
1505    }
1506    if !deny.is_empty() {
1507        args.extend(["--deny".to_owned(), deny.join(",")]);
1508    }
1509    let mut settings = SettingsDocument::default();
1510    settings.set_disable_all_hooks(false);
1511    settings.push_hook_group(
1512        "PreToolUse",
1513        HookGroup::matching("WebFetch", vec![HookCommand::new(program, args, 60, true)]),
1514    );
1515    settings
1516}
1517
1518/// The program a harness hook runs as AI6's gate: `AI6_GREEN_INK_GATE` from the Run
1519/// environment (which only the Agent's roster can set) when not blank, else the executable
1520/// hosting this handler (`ai6` on a Station or field runner).
1521fn hook_program(environment: &BTreeMap<String, String>) -> Option<String> {
1522    environment
1523        .get(GATE_PROGRAM_ENV)
1524        .filter(|program| !program.trim().is_empty())
1525        .cloned()
1526        .or_else(|| {
1527            std::env::current_exe()
1528                .ok()
1529                .map(|path| path.to_string_lossy().into_owned())
1530        })
1531}
1532
1533/// The file-based Claude Code managed settings on `os` that `exists` finds, the first of
1534/// `managed-settings.json` and `managed-settings.d` in its system directory
1535/// (code.claude.com/docs/en/managed-settings). Settings delivered by MDM or the claude.ai
1536/// console are not files here and are not found.
1537fn managed_settings_at(
1538    os: &str,
1539    exists: impl Fn(&std::path::Path) -> bool,
1540) -> Option<std::path::PathBuf> {
1541    let dir = match os {
1542        "macos" => "/Library/Application Support/ClaudeCode",
1543        "linux" => "/etc/claude-code",
1544        "windows" => r"C:\Program Files\ClaudeCode",
1545        _ => return None,
1546    };
1547    ["managed-settings.json", "managed-settings.d"]
1548        .into_iter()
1549        .map(|name| std::path::Path::new(dir).join(name))
1550        .find(|path| exists(path))
1551}
1552
1553/// Why Claude Code's sandbox cannot run on `os` with programs found on `path`, or `None` when
1554/// it can.
1555fn script_sandbox_missing(os: &str, path: Option<std::ffi::OsString>) -> Option<String> {
1556    match os {
1557        "macos" => None,
1558        "linux" => {
1559            let missing: Vec<&str> = ["bwrap", "socat"]
1560                .into_iter()
1561                .filter(|program| {
1562                    !path.as_ref().is_some_and(|path| {
1563                        std::env::split_paths(path).any(|dir| dir.join(program).is_file())
1564                    })
1565                })
1566                .collect();
1567            (!missing.is_empty()).then(|| {
1568                format!(
1569                    "Claude Code's sandbox needs bubblewrap (bwrap) and socat on the harness's \
1570                     PATH, and {} is not there",
1571                    missing.join(" and ")
1572                )
1573            })
1574        }
1575        "windows" => Some(
1576            "Claude Code runs commands unsandboxed on native Windows; its sandbox runs on \
1577             macOS, Linux and WSL2"
1578                .to_owned(),
1579        ),
1580        other => Some(format!("Claude Code has no sandbox on {other}")),
1581    }
1582}
1583
1584/// Whether `name` is a variable `credentials.envVars` accepts: a letter or `_`, then
1585/// letters, digits and `_`.
1586fn variable_name(name: &str) -> bool {
1587    name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
1588        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
1589}
1590
1591/// A Run that only reads its prompt and answers: `--restricted` (Claude Code 2.1.248 or
1592/// later: no shell or code tools, no WebFetch, only managed settings and AI6's), no built-in
1593/// tool at all (`--tools=`), the tools above denied by name, no MCP server (an empty strict
1594/// MCP config) and only the user's settings file besides. An older Claude Code that does not
1595/// know a flag refuses to start, which ends the Run without an answer.
1596fn add_answer_only(argv: &mut Vec<String>) {
1597    argv.extend([
1598        "--restricted".to_owned(),
1599        "--tools=".to_owned(),
1600        "--disallowedTools".to_owned(),
1601        ANSWER_ONLY_DENIED.to_owned(),
1602        "--setting-sources".to_owned(),
1603        "user".to_owned(),
1604        "--strict-mcp-config".to_owned(),
1605        "--mcp-config".to_owned(),
1606        McpConfig::default().to_text(),
1607    ]);
1608}
1609
1610/// Whether `environment` carries an MCP endpoint's URL and token under `prefix`.
1611fn has_endpoint(environment: &BTreeMap<String, String>, prefix: &str) -> bool {
1612    environment.contains_key(&format!("{prefix}_URL"))
1613        && environment.contains_key(&format!("{prefix}_TOKEN"))
1614}
1615
1616/// One HTTP MCP server entry whose URL and bearer token come from the environment, so the
1617/// token never appears in the command line.
1618fn http_server(prefix: &str) -> McpServer {
1619    McpServer::Http(HttpServer::from_environment(prefix))
1620}
1621
1622/// Set by the Station on a trial Run: the turn cap the Run is held to.
1623const TRIAL_MAX_TURNS_ENV: &str = "AI6_TRIAL_MAX_TURNS";
1624
1625/// The tools a trial never has, by name.
1626const TRIAL_DENIED: [&str; 2] = ["WebFetch", "WebSearch"];
1627
1628/// Whether `environment` is a trial Run's.
1629fn is_trial(environment: &BTreeMap<String, String>) -> bool {
1630    environment.contains_key(TRIAL_MAX_TURNS_ENV)
1631}
1632
1633/// The tool a permission rule is for: `WebFetch` for `WebFetch(domain:example.com)`.
1634fn rule_tool(rule: &str) -> &str {
1635    rule.split('(').next().unwrap_or(rule).trim()
1636}
1637
1638/// A field Run's tools, each list closed by the next flag since all are variadic: under
1639/// `--permission-mode dontAsk` a call no rule allows is denied, with no prompt nobody is there to
1640/// answer (code.claude.com/docs/en/permissions). In remote-hands mode, when the Station serves a
1641/// Theater's tools, Claude's own shell and file tools are neither offered nor allowed and stay
1642/// denied whatever the settings say, so that nothing the harness does lands on the Station. With
1643/// `commands` false, the clearance's, the tools of [`DESK_DENIED`] are neither offered nor allowed
1644/// and are denied by name, unless a rule of the settings names one.
1645fn add_field_tools(
1646    argv: &mut Vec<String>,
1647    environment: &BTreeMap<String, String>,
1648    settings: &ClaudeSettings,
1649    commands: bool,
1650) {
1651    // A trial keeps no web tool whatever the Agent's settings allow: its network is the sandbox's.
1652    let trial_settings;
1653    let settings = if is_trial(environment) {
1654        trial_settings = ClaudeSettings {
1655            allowed_tools: Vec::new(),
1656            denied_tools: settings
1657                .denied_tools
1658                .iter()
1659                .cloned()
1660                .chain(TRIAL_DENIED.iter().map(|tool| (*tool).to_owned()))
1661                .collect(),
1662        };
1663        &trial_settings
1664    } else {
1665        settings
1666    };
1667    let remote_hands = has_endpoint(environment, "AI6_THEATER_MCP");
1668    let taken_over = remote_hands && environment.contains_key(THEATER_PLUGIN_ENV);
1669    let own = |tool: &str| {
1670        remote_hands && OWN_TOOLS.contains(&tool) && !(taken_over && SHELL_TOOLS.contains(&tool))
1671    };
1672    let kept_out = |tool: &str| !commands && DESK_DENIED.contains(&tool);
1673    let mut offered: Vec<&str> = FIELD_TOOLS
1674        .iter()
1675        .copied()
1676        .filter(|tool| !own(tool) && !kept_out(tool))
1677        .collect();
1678    for tool in settings.allowed_tools.iter().map(|rule| rule_tool(rule)) {
1679        if !tool.starts_with("mcp__") && !own(tool) && !offered.contains(&tool) {
1680            offered.push(tool);
1681        }
1682    }
1683    let desk_denied = DESK_DENIED.iter().copied().filter(|tool| {
1684        kept_out(tool) && !own(tool) && (remote_hands || !tool.starts_with("mcp__"))
1685    });
1686    let mut denied: Vec<&str> = FIELD_DENIED
1687        .iter()
1688        .copied()
1689        .chain(desk_denied)
1690        .filter(|tool| {
1691            !settings
1692                .allowed_tools
1693                .iter()
1694                .any(|rule| rule_tool(rule) == *tool)
1695        })
1696        .collect();
1697    if remote_hands {
1698        denied.extend(OWN_TOOLS.iter().filter(|tool| own(tool)));
1699    }
1700    denied.extend(settings.denied_tools.iter().map(String::as_str));
1701    let mut allowed = Vec::new();
1702    for (prefix, rule) in [
1703        ("AI6_CABLE_MCP", "mcp__ai6-cables"),
1704        ("AI6_THEATER_MCP", "mcp__ai6-theater"),
1705    ] {
1706        if has_endpoint(environment, prefix) {
1707            allowed.push(rule);
1708        }
1709    }
1710    allowed.extend(
1711        FIELD_ALLOWED
1712            .iter()
1713            .copied()
1714            .filter(|rule| !own(rule_tool(rule)) && !kept_out(rule_tool(rule))),
1715    );
1716    allowed.extend(settings.allowed_tools.iter().map(String::as_str));
1717    argv.extend([
1718        "--tools".to_owned(),
1719        offered.join(","),
1720        "--permission-mode".to_owned(),
1721        "dontAsk".to_owned(),
1722        "--disallowedTools".to_owned(),
1723        denied.join(","),
1724        "--allowedTools".to_owned(),
1725        allowed.join(","),
1726    ]);
1727}
1728
1729/// The tools of a Run held to reading until its plan passes: reading and searching, and AI6's
1730/// Cable server, whose only tool it then has is `submit_plan`. Reading is allowed as `Read(/**)`,
1731/// which Claude Code roots at the working directory when given as a flag and applies to `Glob` and
1732/// `Grep` too, so nothing outside the checkout is read (Claude Code 2.1.326, probed against the
1733/// loopback stand-in). What could change anything is denied by name, and no setting adds to the
1734/// list: `allowed_tools` is a field Run's. A resume at the
1735/// Mission's clearance builds the field list again, since each launch passes its own flags
1736/// (`--resume` keeps the conversation, not the tools).
1737fn add_read_only_tools(argv: &mut Vec<String>, environment: &BTreeMap<String, String>) {
1738    let mut allowed = vec![READ_WITHIN_CHECKOUT];
1739    if has_endpoint(environment, "AI6_CABLE_MCP") {
1740        allowed.insert(0, "mcp__ai6-cables");
1741    }
1742    let denied = FIELD_DENIED
1743        .iter()
1744        .chain(READ_ONLY_DENIED.iter())
1745        .copied()
1746        .collect::<Vec<_>>();
1747    argv.extend([
1748        "--tools".to_owned(),
1749        "Read,Glob,Grep".to_owned(),
1750        "--permission-mode".to_owned(),
1751        "dontAsk".to_owned(),
1752        "--disallowedTools".to_owned(),
1753        denied.join(","),
1754        "--allowedTools".to_owned(),
1755        allowed.join(","),
1756    ]);
1757}
1758
1759/// The allow rule for reading under the working directory only.
1760const READ_WITHIN_CHECKOUT: &str = "Read(/**)";
1761
1762/// What a Run held to reading is denied besides [`FIELD_DENIED`]: everything that writes or runs.
1763const READ_ONLY_DENIED: [&str; 14] = [
1764    "Edit",
1765    "Write",
1766    "NotebookEdit",
1767    "Bash",
1768    "PowerShell",
1769    "TodoWrite",
1770    "TaskCreate",
1771    "TaskGet",
1772    "TaskList",
1773    "TaskUpdate",
1774    "mcp__ai6-theater__exec",
1775    "mcp__ai6-theater__fs_write",
1776    "mcp__ai6-theater__edit",
1777    "mcp__ai6-theater__apply_patch",
1778];
1779
1780/// Adds the Station's MCP servers: Cable tools, and, when the Station serves a Theater's tools
1781/// (remote-hands mode), those. [`add_field_tools`] allows them by server.
1782fn add_mcp(argv: &mut Vec<String>, environment: &BTreeMap<String, String>) {
1783    let mut servers = McpConfig::default();
1784    if has_endpoint(environment, "AI6_CABLE_MCP") {
1785        servers.add("ai6-cables", http_server("AI6_CABLE_MCP"));
1786    }
1787    if has_endpoint(environment, "AI6_THEATER_MCP") {
1788        servers.add("ai6-theater", http_server("AI6_THEATER_MCP"));
1789    }
1790    if !servers.is_empty() {
1791        argv.extend(["--mcp-config".to_owned(), servers.to_text()]);
1792    }
1793    if has_endpoint(environment, "AI6_THEATER_MCP")
1794        && let Some(plugin) = environment.get(THEATER_PLUGIN_ENV)
1795    {
1796        argv.push(format!("--plugin-dir={plugin}"));
1797    }
1798}
1799
1800/// The Claude Code settings that hold a shell command taking a governed step until green ink
1801/// covers it: a `PreToolUse` hook on the shell tools running `PROGRAM green-ink gate
1802/// --cable-url URL`. The URL is in the hook's own arguments so a project's settings (`env`)
1803/// cannot point the gate at another endpoint; the token stays in the environment, out of every
1804/// command line, and a redirected token only makes the gate hold. A hook that fails to run
1805/// blocks the command (`onFailure`, Claude Code 2.1.295 or later), and hooks stay on whatever
1806/// the project's settings say.
1807fn gate_settings(program: &str, cable_url: &str) -> SettingsDocument {
1808    let mut settings = SettingsDocument::default();
1809    settings.set_disable_all_hooks(false);
1810    settings.push_hook_group(
1811        "PreToolUse",
1812        HookGroup::matching(
1813            "Bash|PowerShell",
1814            vec![HookCommand::new(
1815                program,
1816                ["green-ink", "gate", "--cable-url", cable_url]
1817                    .map(str::to_owned)
1818                    .to_vec(),
1819                60,
1820                true,
1821            )],
1822        ),
1823    );
1824    settings
1825}
1826
1827/// The green ink gate when the Run has a Station to ask (its Cable endpoint). The gate is the
1828/// `ai6` program hosting this handler, or the one `AI6_GREEN_INK_GATE` names.
1829fn gate_of(environment: &BTreeMap<String, String>) -> Option<SettingsDocument> {
1830    let cable_url = environment
1831        .get("AI6_CABLE_MCP_URL")
1832        .filter(|_| has_endpoint(environment, "AI6_CABLE_MCP"))?;
1833    hook_program(environment).map(|program| gate_settings(&program, cable_url))
1834}
1835
1836/// Keeps the working directory's own settings out of the harness unless AI6 allowed them:
1837/// only the user's settings file loads (`--setting-sources user`, so no project or local
1838/// hooks), and only the MCP servers AI6 passes (`--strict-mcp-config`, so no `.mcp.json`).
1839/// AI6's `--settings` and `--mcp-config` apply either way.
1840fn add_project_settings(argv: &mut Vec<String>, allowed: bool, mcp: bool) {
1841    if !allowed {
1842        argv.extend(["--setting-sources".to_owned(), "user".to_owned()]);
1843    }
1844    if !(allowed && mcp) {
1845        argv.push("--strict-mcp-config".to_owned());
1846    }
1847}
1848
1849/// Gives Claude Code its own spend ceiling for this process (print mode only).
1850fn add_budget(argv: &mut Vec<String>, max_cost_micro_usd: Option<u64>) {
1851    if let Some(micro) = max_cost_micro_usd {
1852        argv.extend([
1853            "--max-budget-usd".to_owned(),
1854            format!("{}.{:06}", micro / 1_000_000, micro % 1_000_000),
1855        ]);
1856    }
1857}
1858
1859/// The usage a `result` event reports: `usage` token counts and `total_cost_usd`, both
1860/// running totals for the Claude Code process.
1861fn decode_usage(line: &StreamLine) -> Option<Spend> {
1862    if line.kind_text()? != "result" {
1863        return None;
1864    }
1865    let (counts, cost) = line.spend()?;
1866    let mut spend = Spend::new("");
1867    spend.input = counts.input;
1868    spend.output = counts.output;
1869    spend.cache_read = counts.cache_read;
1870    spend.cache_write = counts.cache_write;
1871    spend.cost_micro_usd = cost.map(micro_usd);
1872    Some(spend)
1873}
1874
1875/// What an event tells of the account's usage: the Claude Code process's running spend on a
1876/// `result`, and the window of a `rate_limit_event`.
1877fn decode_report(line: &StreamLine) -> Option<UsageReport> {
1878    let spend = decode_usage(line);
1879    let buckets = decode_quota(line);
1880    if spend.is_none() && buckets.is_empty() {
1881        return None;
1882    }
1883    let mut report = UsageReport::new();
1884    report.spend = spend;
1885    report.buckets = buckets;
1886    Some(report)
1887}
1888
1889/// Everything `open` needs to start Claude Code.
1890struct Opening<'a> {
1891    config: &'a ClaudeConfig,
1892    terminal: Object<dyn AgentTerminal>,
1893    /// The flags after those the driver always passes, as AI6 builds them.
1894    flags: Vec<String>,
1895    cwd: &'a str,
1896    environment: BTreeMap<String, String>,
1897    session: SessionStart,
1898    /// The Run a resumed launch must report.
1899    expected_run_id: Option<RunId>,
1900    /// For a restricted (answer-only or assistant) Run, what it may call.
1901    restricted: Option<Allowed>,
1902    /// The oldest Claude Code the Run may use, when its tools are taken over by a hook.
1903    minimum_version: Option<String>,
1904    /// The directory of the context file in `flags`, removed when the Run is dropped.
1905    private: Option<tempfile::TempDir>,
1906}
1907
1908/// Starts Claude Code on the Station's terminal through `coqui-acp-claude`, and waits for it to
1909/// answer its `initialize` request.
1910fn open(opening: Opening<'_>) -> Result<ClaudeRun, ProviderError> {
1911    let Opening {
1912        config,
1913        terminal,
1914        flags,
1915        cwd,
1916        environment,
1917        session,
1918        expected_run_id,
1919        restricted,
1920        private,
1921        minimum_version,
1922    } = opening;
1923    let mut launch = ClaudeLaunch::new(cwd);
1924    launch.executable = config.executable.clone().into();
1925    launch.session = session;
1926    // AI6 reads the stream's whole messages, and decides each permission by flags and settings.
1927    launch.partial_messages = false;
1928    launch.permission_prompts = false;
1929    launch.extra_args = flags.into_iter().map(OsString::from).collect();
1930
1931    let link = Arc::new(Link::default());
1932    let shared = Arc::new(Shared::new(restricted, expected_run_id, Arc::clone(&link)));
1933    let mut settings = DriverSettings::new();
1934    settings.max_line = config.json_line_bytes;
1935    settings.tail_lines = usize::try_from(config.tail_lines).unwrap_or(usize::MAX);
1936    settings.tail_line_bytes = usize::try_from(config.tail_line_bytes).unwrap_or(usize::MAX);
1937    settings.exit_wait = Duration::from_millis(config.exit_wait_ms);
1938    settings.close_wait = Duration::from_millis(config.close_wait_ms);
1939    settings.version_wait = Duration::ZERO;
1940    settings.initialize_timeout = Duration::from_millis(config.initialize_wait_ms);
1941    {
1942        let shared = Arc::clone(&shared);
1943        settings.on_line = Some(Arc::new(move |raw| {
1944            let line = JsonObject::<StreamLine>::deserialize(raw)
1945                .map(|object| object.0)
1946                .unwrap_or_default();
1947            shared.line(
1948                &line,
1949                || coqui_acp_claude::limit_of_line(raw),
1950                || ai6::TokenCapRefusal::deserialize(raw).ok()?.into_text(),
1951            )
1952        }));
1953    }
1954    let mut limits = ai6::station::limits::TerminalOutputLimits::default();
1955    limits.json_line_bytes = ai6::Limit::at(config.json_line_bytes);
1956    limits.csi_bytes = ai6::Limit::at(config.csi_bytes);
1957    let spawner = TerminalSpawn {
1958        terminal,
1959        environment,
1960        limits,
1961        link,
1962    };
1963    let sink = Arc::clone(&shared);
1964    let session = match Session::start(&launch, &spawner, settings, move |event| sink.tell(event)) {
1965        Ok(session) => Some(session),
1966        // It ended, or refused to start, before it answered: the Run reports how, as one that
1967        // ends later does.
1968        Err(ClaudeError::Harness(reason)) => {
1969            shared.ended(&reason);
1970            None
1971        }
1972        Err(ClaudeError::Refused(why)) => {
1973            return Err(refuse(Status::GUATIAO_ERR_UNSUPPORTED, why));
1974        }
1975        Err(other) => {
1976            return Err(refuse(
1977                Status::GUATIAO_ERR_INTERNAL,
1978                polished(&other.to_string()),
1979            ));
1980        }
1981    };
1982    if let (Some(minimum), Some(running)) = (&minimum_version, &session) {
1983        let found = running.version();
1984        if found
1985            .as_deref()
1986            .is_none_or(|found| older_than(found, minimum))
1987        {
1988            running.close();
1989            return Err(refuse(
1990                Status::GUATIAO_ERR_UNSUPPORTED,
1991                format!(
1992                    "Claude Code {} cannot take over its tools: its hook must refuse a call when it fails, \n                     which needs {minimum} or later",
1993                    found.as_deref().unwrap_or("of an unknown version"),
1994                ),
1995            ));
1996        }
1997    }
1998    Ok(ClaudeRun {
1999        session,
2000        shared,
2001        _private: private,
2002    })
2003}
2004
2005/// Whether the Claude Code version `found` (`2.1.326`, as it reports itself) is older than `minimum`. A version that
2006/// is not dotted numbers counts as older: nothing is known of its hooks.
2007fn older_than(found: &str, minimum: &str) -> bool {
2008    fn numbers(version: &str) -> Option<Vec<u64>> {
2009        let words = version.split_whitespace().next()?;
2010        let mut parts = words
2011            .split('.')
2012            .map(|part| part.parse::<u64>().ok())
2013            .collect::<Option<Vec<_>>>()?;
2014        parts.resize(parts.len().max(3), 0);
2015        Some(parts)
2016    }
2017    match (numbers(found), numbers(minimum)) {
2018        (Some(found), Some(minimum)) => found < minimum,
2019        _ => true,
2020    }
2021}
2022
2023/// An exit reason in the words of a Run: how the driver words it, with a negative exit code also
2024/// as Windows names it.
2025fn polished(reason: &str) -> String {
2026    let mut text = reason
2027        .replace("before completing the session", "before completing the Run")
2028        .replace("closed its output", "closed its terminal");
2029    const CODE: &str = "exited with code ";
2030    if let Some(at) = text.find(CODE) {
2031        let start = at + CODE.len();
2032        let digits = text[start..]
2033            .char_indices()
2034            .find(|(index, c)| !(c.is_ascii_digit() || (*index == 0 && *c == '-')))
2035            .map_or(text.len(), |(index, _)| start + index);
2036        if let Ok(code) = text[start..digits].parse::<i64>() {
2037            text.replace_range(start..digits, &exit_code_text(code));
2038        }
2039    }
2040    text
2041}
2042
2043/// What a Run's reader thread and its caller share.
2044struct Shared {
2045    events: Mutex<VecDeque<AgentEvent>>,
2046    arrived: Condvar,
2047    /// The provider ID, once Claude has reported it.
2048    run_id: Mutex<Option<RunId>>,
2049    /// The session a resumed launch must report, until a clear the Station asked for gives the
2050    /// Run another.
2051    expected_run_id: Mutex<Option<RunId>>,
2052    /// Set when the Station asked for a clear, until Claude Code's `conversation_reset` answers it.
2053    clear_asked: AtomicBool,
2054    /// Why the Run ended on a line Claude wrote, for the caller of `next_event` to be told once.
2055    refused: Mutex<Option<ProviderError>>,
2056    /// For a restricted (answer-only or assistant) Run, what it may call.
2057    restricted: Option<Allowed>,
2058    /// Set once a restricted Run called a tool it may not, and was ended: nothing it
2059    /// wrote after that is read.
2060    tripped: AtomicBool,
2061    /// Set once the end of Claude Code was reported as a `failed` event, or needs none.
2062    ended_reported: AtomicBool,
2063    link: Arc<Link>,
2064}
2065
2066impl Shared {
2067    fn new(restricted: Option<Allowed>, expected_run_id: Option<RunId>, link: Arc<Link>) -> Self {
2068        Self {
2069            events: Mutex::new(VecDeque::new()),
2070            arrived: Condvar::new(),
2071            run_id: Mutex::new(None),
2072            expected_run_id: Mutex::new(expected_run_id),
2073            clear_asked: AtomicBool::new(false),
2074            refused: Mutex::new(None),
2075            restricted,
2076            tripped: AtomicBool::new(false),
2077            ended_reported: AtomicBool::new(false),
2078            link,
2079        }
2080    }
2081
2082    fn push(&self, event: AgentEvent) {
2083        if let Ok(mut events) = self.events.lock() {
2084            events.push_back(event);
2085            self.arrived.notify_all();
2086        }
2087    }
2088
2089    /// The `failed` event that ends a restricted Run whose `seen` event calls a tool outside
2090    /// its servers (`mcp__<server>__<tool>`) and the built-in tools its mode offers, after
2091    /// closing it; `None` when it calls none. The flags it was started with are meant to make
2092    /// this impossible; this backs them up. Which paths, commands and hosts a built-in tool may
2093    /// reach is the permission rules' and the sandbox's to enforce.
2094    fn tripped(&self, seen: &AgentEvent, line: &StreamLine) -> Option<AgentEvent> {
2095        let allowed = self.restricted.as_ref()?;
2096        let mut forbidden = seen
2097            .tools
2098            .iter()
2099            .filter(|tool| {
2100                !(allowed
2101                    .servers
2102                    .iter()
2103                    .any(|server| tool.starts_with(&format!("mcp__{server}__")))
2104                    || allowed.builtins.iter().any(|builtin| builtin == *tool))
2105            })
2106            .cloned()
2107            .collect::<Vec<_>>();
2108        for block in unexpected_blocks(line) {
2109            if !forbidden.contains(&block) {
2110                forbidden.push(block);
2111            }
2112        }
2113        if forbidden.is_empty() {
2114            return None;
2115        }
2116        let reason = format!(
2117            "the restricted Claude Code Run called {}, which it may not use; the Run \
2118             was ended",
2119            forbidden.join(", ")
2120        );
2121        eprintln!("ai6: {reason}");
2122        self.link.kill();
2123        self.tripped.store(true, Ordering::Release);
2124        self.ended_reported.store(true, Ordering::Release);
2125        Some(event("failed", Some(reason)))
2126    }
2127
2128    /// Takes one line Claude Code wrote, before the driver reads it; `false` ends Claude Code.
2129    fn line(
2130        &self,
2131        line: &StreamLine,
2132        limit: impl FnOnce() -> Option<LimitHit>,
2133        refusal: impl FnOnce() -> Option<String>,
2134    ) -> bool {
2135        if self.tripped.load(Ordering::Acquire) {
2136            return false;
2137        }
2138        if let Some(id) = line.session_id.text() {
2139            let run_id = match RunId::try_from(id.to_string()) {
2140                Ok(run_id) => run_id,
2141                Err(error) => return self.refuse(refuse(Status::GUATIAO_ERR_BAD_VALUE, error)),
2142            };
2143            let different = self
2144                .expected_run_id
2145                .lock()
2146                .map(|expected| {
2147                    expected
2148                        .as_ref()
2149                        .is_some_and(|expected| expected != &run_id)
2150                })
2151                .unwrap_or(false);
2152            // Kept even when it is the wrong one: `run_id` is how the Station learns that.
2153            if let Ok(mut known) = self.run_id.lock() {
2154                *known = Some(run_id);
2155            }
2156            if different {
2157                return self.refuse(refuse(
2158                    Status::GUATIAO_ERR_BAD_VALUE,
2159                    "Claude resumed a different Run than requested",
2160                ));
2161            }
2162        }
2163        let kind = line.kind_text();
2164        // The clear the Station asked for makes a new session: the next id is the Run's.
2165        if kind == Some("conversation_reset")
2166            && self.clear_asked.swap(false, Ordering::AcqRel)
2167            && let Ok(mut expected) = self.expected_run_id.lock()
2168        {
2169            *expected = None;
2170        }
2171        if kind == Some("control_response") {
2172            control_answered(line);
2173        }
2174        if let Some(changed) = session_event(line) {
2175            self.push(changed);
2176            return true;
2177        }
2178        if matches!(kind, Some("user" | "control_response")) {
2179            return true;
2180        }
2181        let text = self
2182            .link
2183            .last
2184            .lock()
2185            .map(|last| last.clone())
2186            .unwrap_or_default();
2187        if let Some(event) = decode_event(line, text, limit, refusal) {
2188            if let Some(ended) = self.tripped(&event, line) {
2189                self.push(ended);
2190                return false;
2191            }
2192            if let Some(denied) = decode_denials(line) {
2193                self.push(denied);
2194            }
2195            self.push(event);
2196        }
2197        true
2198    }
2199
2200    /// Ends the Run on a line it should not have written; the caller of `next_event` is told why.
2201    fn refuse(&self, error: ProviderError) -> bool {
2202        if let Ok(mut refused) = self.refused.lock() {
2203            refused.get_or_insert(error);
2204        }
2205        self.ended_reported.store(true, Ordering::Release);
2206        // Waking the caller is how it learns.
2207        if let Ok(_events) = self.events.lock() {
2208            self.arrived.notify_all();
2209        }
2210        false
2211    }
2212
2213    /// Takes what the driver tells of Claude Code.
2214    fn tell(&self, told: ClaudeEvent) -> bool {
2215        match told {
2216            ClaudeEvent::Output(text) => self.push(AgentEvent {
2217                kind: "output".to_owned(),
2218                text: Some(text),
2219                data: None,
2220                limit: None,
2221                tools: Vec::new(),
2222                report: None,
2223            }),
2224            ClaudeEvent::Exited(reason) => self.ended(&reason),
2225            _ => {}
2226        }
2227        true
2228    }
2229
2230    /// The end of Claude Code ends the Run once, with the reason.
2231    fn ended(&self, reason: &str) {
2232        if !self.ended_reported.swap(true, Ordering::AcqRel) {
2233            let reason = polished(reason);
2234            eprintln!("ai6: {reason}");
2235            self.push(event("failed", Some(reason)));
2236        }
2237    }
2238}
2239
2240/// A started Claude Code, as one of AI6's Runs.
2241struct ClaudeRun {
2242    /// `None` for a Claude Code that ended before it was started: its Run only reports that.
2243    session: Option<Session>,
2244    shared: Arc<Shared>,
2245    /// Holds the Run's private directory until the Run is dropped.
2246    _private: Option<tempfile::TempDir>,
2247}
2248
2249impl ClaudeRun {
2250    fn command(&self, command: &SessionCommand) -> Result<(), ProviderError> {
2251        // A resumed Run holds the session it was asked for; a clear gives it another, which is
2252        // then the one it holds.
2253        if *command == SessionCommand::Clear {
2254            self.shared.clear_asked.store(true, Ordering::Release);
2255        }
2256        match &self.session {
2257            Some(session) => session
2258                .prompt(&[Content::Text(command_text(command))])
2259                .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error)),
2260            None => Ok(()),
2261        }
2262    }
2263
2264    fn send(&self, text: &str) -> Result<(), ProviderError> {
2265        match &self.session {
2266            Some(session) => session
2267                .prompt(&contents(text))
2268                .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error)),
2269            None => Ok(()),
2270        }
2271    }
2272}
2273
2274/// The user message that asks Claude Code for `command`: its own slash command, which stream-json
2275/// input runs as a turn of its own (`/compact` ends in a `compact_boundary`, `/clear` in a
2276/// `conversation_reset`, each followed by a `result`).
2277fn command_text(command: &SessionCommand) -> String {
2278    match command {
2279        SessionCommand::Compact { focus } => {
2280            let focus = focus
2281                .as_deref()
2282                .map(|focus| focus.split_whitespace().collect::<Vec<_>>().join(" "))
2283                .filter(|focus| !focus.is_empty());
2284            match focus {
2285                Some(focus) => format!("/compact {focus}"),
2286                None => "/compact".to_owned(),
2287            }
2288        }
2289        SessionCommand::Clear => "/clear".to_owned(),
2290    }
2291}
2292
2293/// What a line of Claude Code's says of a conversation changing, as the event that reports
2294/// it: `system/compact_boundary` (with the tokens before and after), a `system/status` that
2295/// reports a compaction failed, and `conversation_reset`. Any other line is no change.
2296fn session_event(line: &StreamLine) -> Option<AgentEvent> {
2297    let kind = line.kind_text()?;
2298    let subtype = line.subtype.text();
2299    match (kind, subtype) {
2300        ("system", Some("compact_boundary")) => {
2301            let meta = line.compaction();
2302            Some(
2303                SessionChange {
2304                    trigger: meta.trigger.text().map(str::to_owned),
2305                    tokens_before: meta.pre_tokens.copied(),
2306                    tokens_after: meta.post_tokens.copied(),
2307                    session_id: None,
2308                }
2309                .event(ai6::COMPACTED_EVENT, None),
2310            )
2311        }
2312        ("system", Some("status")) if line.compact_result.text() == Some("failed") => {
2313            let why = line
2314                .compact_error
2315                .text()
2316                .unwrap_or("Claude Code did not compact the conversation");
2317            Some(SessionChange::default().event(ai6::COMPACT_FAILED_EVENT, Some(why.to_owned())))
2318        }
2319        ("conversation_reset", _) => Some(
2320            SessionChange {
2321                trigger: line.trigger.text().map(str::to_owned),
2322                ..SessionChange::default()
2323            }
2324            .event(ai6::CLEARED_EVENT, None),
2325        ),
2326        _ => None,
2327    }
2328}
2329
2330/// A message in AI6's content form as the driver's blocks: the images it carries, then its text.
2331fn contents(text: &str) -> Vec<Content> {
2332    match ai6::MessageContent::decode(text) {
2333        Some(content) => content
2334            .images
2335            .iter()
2336            .map(|image| Content::Image {
2337                mime_type: image.media_type.clone(),
2338                data: image.data.clone(),
2339            })
2340            .chain([Content::Text(content.text)])
2341            .collect(),
2342        None => vec![Content::Text(text.to_owned())],
2343    }
2344}
2345
2346/// Logs a `control_response` that reports an error; a success needs nothing. Claude Code
2347/// 2.1.310 answers an interrupt with `success` (`{"still_queued":[]}`) even when no turn is
2348/// running, and a request it does not support with `error` and its reason.
2349fn control_answered(line: &StreamLine) {
2350    if let Some(error) = line.control_refusal() {
2351        eprintln!("ai6: Claude Code refused a control request: {error}");
2352    }
2353}
2354
2355impl ai6::AgentSession for ClaudeRun {
2356    fn session_id(&self) -> Result<Option<String>, ProviderError> {
2357        Ok(lock(&self.shared.run_id)?.clone().map(String::from))
2358    }
2359
2360    fn send_message(&self, message: AgentMessage) -> Result<(), ProviderError> {
2361        match SessionCommand::parse(&message.text)
2362            .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?
2363        {
2364            Some(command) => self.command(&command),
2365            None => self.send(&message.text),
2366        }
2367    }
2368
2369    fn next_event(&self, timeout_ms: i64) -> Result<Option<AgentEvent>, ProviderError> {
2370        let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
2371        let mut events = lock(&self.shared.events)?;
2372        loop {
2373            if let Some(event) = events.pop_front() {
2374                return Ok(Some(event));
2375            }
2376            if let Some(error) = lock(&self.shared.refused)?.take() {
2377                return Err(error);
2378            }
2379            let remaining = deadline.saturating_duration_since(Instant::now());
2380            if remaining.is_zero() {
2381                return Ok(None);
2382            }
2383            events = self
2384                .shared
2385                .arrived
2386                .wait_timeout(events, remaining)
2387                .map_err(|_| refuse(Status::GUATIAO_ERR_INTERNAL, "run lock was poisoned"))?
2388                .0;
2389        }
2390    }
2391
2392    /// Stops the running turn with stream-json's `interrupt` control request, in the Agent
2393    /// SDK's shape; the `control_response` Claude answers with is read and dropped.
2394    fn interrupt(&self) -> Result<(), ProviderError> {
2395        match &self.session {
2396            Some(session) => session
2397                .interrupt()
2398                .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error)),
2399            None => Ok(()),
2400        }
2401    }
2402
2403    /// Ends Claude Code. The caller may remove the working directory next, which it holds until
2404    /// it has exited, so this waits for that.
2405    fn close(&self) -> Result<(), ProviderError> {
2406        // The exit this causes is no failure, and the Station's log does not say it is one.
2407        self.shared.ended_reported.store(true, Ordering::Release);
2408        if let Some(session) = &self.session {
2409            session.close();
2410        }
2411        Ok(())
2412    }
2413}
2414
2415/// A user message in stream-json's shape: its text, after the images a message in AI6's
2416/// content form carries, each as a base64 `image` block.
2417/// A user message as the driver writes it, for the tests that hold its shape.
2418#[cfg(test)]
2419fn user_input(text: &str) -> Value {
2420    let blocks = coqui_acp_claude::user_blocks(&contents(text)).unwrap();
2421    json!({"type": "user", "message": {"role": "user", "content": blocks}})
2422}
2423
2424fn event(kind: &str, text: Option<String>) -> AgentEvent {
2425    AgentEvent {
2426        kind: kind.to_string(),
2427        text,
2428        data: None,
2429        limit: None,
2430        tools: Vec::new(),
2431        report: None,
2432    }
2433}
2434
2435/// Recognises Claude Code's refusal to continue until a quota resets: the driver's reading of the line
2436/// ([`coqui_acp_claude::limit_of_line`]), with the wait the words state and the one limit that follows the
2437/// work and not the account.
2438fn stated_limit(mut limit: LimitHit) -> (LimitHit, Option<String>) {
2439    let text = limit.text.clone();
2440    // A wait the words state (`retry after 90 seconds`) is the refusal's own.
2441    limit.retry_after = text
2442        .as_deref()
2443        .and_then(|words| {
2444            infer_limit(
2445                words,
2446                &["429", "usage limit", "limit reached", "hit your limit"],
2447            )
2448        })
2449        .and_then(|stated| stated.retry_after);
2450    (limit, text)
2451}
2452
2453#[cfg(test)]
2454fn decode_limit(value: &Value) -> Option<(LimitHit, Option<String>)> {
2455    coqui_acp_claude::limit_of_line(value).map(stated_limit)
2456}
2457
2458/// The quota a `rate_limit_event` reports, whatever its status: the window
2459/// (`rateLimitType`), the status, `resetsAt`, and `utilization` as thousandths when it is a
2460/// fraction between 0 and 1.
2461fn decode_quota(line: &StreamLine) -> Vec<Bucket> {
2462    if line.kind_text() != Some("rate_limit_event") {
2463        return Vec::new();
2464    }
2465    let Some(info) = line.rate_limit() else {
2466        return Vec::new();
2467    };
2468    let mut bucket = Bucket::new(info.window.text().unwrap_or("unknown"));
2469    if let Some(used) = info
2470        .utilization
2471        .copied()
2472        .filter(|fraction| (0.0..=1.0).contains(fraction))
2473    {
2474        bucket.limit = Some(1000);
2475        bucket.used = Some((used * 1000.0).round() as u64);
2476    }
2477    bucket.refill = Refill::FixedWindow {
2478        length: None,
2479        resets_at: info.resets_at.copied().map(unix_seconds),
2480    };
2481    bucket.status = match info.status.text() {
2482        Some("allowed") => BucketStatus::Ok,
2483        Some("allowed_warning") => BucketStatus::Warning,
2484        Some("rejected") => BucketStatus::Exhausted,
2485        _ => BucketStatus::Unknown,
2486    };
2487    vec![bucket]
2488}
2489
2490/// A Unix timestamp that may be in seconds or milliseconds.
2491fn unix_seconds(value: i64) -> i64 {
2492    if value > 100_000_000_000 {
2493        value / 1000
2494    } else {
2495        value
2496    }
2497}
2498
2499fn decode_event(
2500    line: &StreamLine,
2501    bytes: Vec<u8>,
2502    limit: impl FnOnce() -> Option<LimitHit>,
2503    refusal: impl FnOnce() -> Option<String>,
2504) -> Option<AgentEvent> {
2505    let event_type = line.kind_text().unwrap_or("event");
2506    if event_type == "user" {
2507        return None;
2508    }
2509    if let Some((limit, text)) = limit().map(stated_limit) {
2510        return Some(AgentEvent {
2511            kind: LIMIT_EVENT.to_owned(),
2512            text,
2513            data: Some(bytes),
2514            limit: Some(limit),
2515            tools: Vec::new(),
2516            report: decode_report(line),
2517        });
2518    }
2519    // Claude Code retries a gateway's refusal for hours (`api_retry`); a token-cap refusal is the
2520    // same every time, so the turn ends with the gateway's own words.
2521    if event_type == "system"
2522        && line.subtype.text() == Some("api_retry")
2523        && let Some(words) = refusal()
2524    {
2525        return Some(AgentEvent {
2526            data: Some(bytes),
2527            ..event("failed", Some(words))
2528        });
2529    }
2530    let tools = decode_tools(line);
2531    let error_result = event_type == "result" && result_is_error(line);
2532    let kind = match event_type {
2533        "result" if error_result => "failed",
2534        "result" => "completed",
2535        "error" => "failed",
2536        "assistant" if !tools.is_empty() => "tool",
2537        "assistant" | "stream_event" => "text",
2538        other => other,
2539    };
2540    let text = line
2541        .text()
2542        .map(str::to_string)
2543        .or_else(|| error_result.then(|| result_errors(line)).flatten());
2544    Some(AgentEvent {
2545        kind: kind.to_string(),
2546        text,
2547        data: Some(bytes),
2548        limit: None,
2549        tools,
2550        report: decode_report(line),
2551    })
2552}
2553
2554/// [`decode_event`] of a line that is read here.
2555#[cfg(test)]
2556fn decoded(value: &Value, bytes: Vec<u8>) -> Option<AgentEvent> {
2557    decode_event(
2558        &read_line(value),
2559        bytes,
2560        || coqui_acp_claude::limit_of_line(value),
2561        || ai6::TokenCapRefusal::deserialize(value).ok()?.into_text(),
2562    )
2563}
2564
2565/// What a line holds of the members this handler reads; a line that is no object holds none.
2566#[cfg(test)]
2567fn read_line(value: &Value) -> StreamLine {
2568    if value.is_object() {
2569        StreamLine::deserialize(value).unwrap_or_default()
2570    } else {
2571        StreamLine::default()
2572    }
2573}
2574
2575/// The event for the calls a `result` lists under `permission_denials`, a turn that otherwise
2576/// reads as a success: its text names each tool once, in the order first refused, and its data
2577/// lists every call as `{"tool", "target"}`, the target being the one field of the call's input
2578/// that says what it reached (a path, a command, an address or a pattern). The rest of the input
2579/// stays out, since it may hold anything the model wrote; the reader cuts and screens the target.
2580fn decode_denials(line: &StreamLine) -> Option<AgentEvent> {
2581    if line.kind_text() != Some("result") {
2582        return None;
2583    }
2584    let calls = line.denied_calls()?;
2585    let mut tools: Vec<&str> = Vec::new();
2586    for call in &calls {
2587        if !tools.contains(&call.tool) {
2588            tools.push(call.tool);
2589        }
2590    }
2591    let mut denied = (!tools.is_empty()).then(|| event(DENIED_EVENT, Some(tools.join(", "))))?;
2592    denied.data = serde_json::to_vec(&calls).ok();
2593    Some(denied)
2594}
2595
2596/// Whether a `result` reports that the turn did not do its work: `is_error`, which Claude Code
2597/// 2.1.316 sets with `subtype: success` when no login reached a model, or an `error_*` subtype.
2598fn result_is_error(line: &StreamLine) -> bool {
2599    line.is_error.copied() == Some(true)
2600        || line
2601            .subtype
2602            .text()
2603            .is_some_and(|subtype| subtype.starts_with("error"))
2604}
2605
2606/// The `errors` of a `result` with no `result` text, one per line.
2607fn result_errors(line: &StreamLine) -> Option<String> {
2608    let errors = line.error_texts();
2609    (!errors.is_empty()).then(|| errors.join("\n"))
2610}
2611
2612/// The tools an `assistant` message calls, one per tool-call content block: a `tool_use`
2613/// block (a tool Claude Code runs) by its `name`; any other `*_tool_use` block, which the
2614/// Messages API runs itself (`server_tool_use` for the advisor, web search or code execution,
2615/// `mcp_tool_use` for its MCP connector), as `TYPE:NAME`, which no `mcp__` rule matches.
2616fn decode_tools(line: &StreamLine) -> Vec<String> {
2617    if line.kind_text() != Some("assistant") {
2618        return Vec::new();
2619    }
2620    line.block_kinds()
2621        .into_iter()
2622        .filter_map(|(kind, name)| {
2623            let kind = kind?;
2624            let name = name.unwrap_or("");
2625            match kind {
2626                "tool_use" => Some(name.to_owned()),
2627                kind if kind.ends_with("_tool_use") => Some(format!("{kind}:{name}")),
2628                _ => None,
2629            }
2630        })
2631        .collect()
2632}
2633
2634/// The content block types an `assistant` message of a restricted Run may hold: prose,
2635/// reasoning, and a call of a tool Claude Code runs (checked by name).
2636const EXPECTED_BLOCKS: [&str; 4] = ["text", "thinking", "redacted_thinking", "tool_use"];
2637
2638/// Every content block of an `assistant` message whose type is not [`EXPECTED_BLOCKS`], as
2639/// `TYPE` or `TYPE:NAME`: a call the Messages API runs itself (`server_tool_use`,
2640/// `mcp_tool_use`), its result (`web_search_tool_result`, `mcp_tool_result`), a block with no
2641/// type, or one of a type Claude Code adds later.
2642fn unexpected_blocks(line: &StreamLine) -> Vec<String> {
2643    if line.kind_text() != Some("assistant") {
2644        return Vec::new();
2645    }
2646    line.block_kinds()
2647        .into_iter()
2648        .filter_map(|(kind, name)| {
2649            let kind = kind.unwrap_or("");
2650            if EXPECTED_BLOCKS.contains(&kind) {
2651                return None;
2652            }
2653            let kind = if kind.is_empty() { "untyped" } else { kind };
2654            Some(match name {
2655                Some(name) => format!("{kind}:{name}"),
2656                None => kind.to_owned(),
2657            })
2658        })
2659        .collect()
2660}
2661
2662fn lock<T>(mutex: &Mutex<T>) -> Result<std::sync::MutexGuard<'_, T>, ProviderError> {
2663    mutex
2664        .lock()
2665        .map_err(|_| refuse(Status::GUATIAO_ERR_INTERNAL, "run lock was poisoned"))
2666}
2667
2668#[cfg(test)]
2669fn internal(error: impl std::fmt::Display) -> ProviderError {
2670    refuse(Status::GUATIAO_ERR_INTERNAL, error)
2671}
2672
2673fn refuse(status: Status, error: impl std::fmt::Display) -> ProviderError {
2674    ProviderError::new(status, &error.to_string())
2675}
2676
2677#[cfg(test)]
2678mod tests {
2679    #[test]
2680    fn a_harness_the_station_closed_is_not_reported_as_having_exited() {
2681        let shared = Arc::new(Shared::new(None, None, Arc::new(Link::default())));
2682        let run = ClaudeRun {
2683            session: None,
2684            shared: Arc::clone(&shared),
2685            _private: None,
2686        };
2687        run.close().unwrap();
2688        shared.ended("Claude Code exited with code 1 before completing the session");
2689        assert!(
2690            run.next_event(0).unwrap().is_none(),
2691            "the exit the close caused is no failed event"
2692        );
2693        // One that ends by itself still is reported.
2694        let alone = Arc::new(Shared::new(None, None, Arc::new(Link::default())));
2695        let run = ClaudeRun {
2696            session: None,
2697            shared: Arc::clone(&alone),
2698            _private: None,
2699        };
2700        alone.ended("Claude Code exited with code 1 before completing the session");
2701        assert_eq!(run.next_event(0).unwrap().unwrap().kind, "failed");
2702    }
2703
2704    use super::*;
2705    use ai6::LimitKind;
2706    use ai6::directorates::q::terminal::{
2707        ExitInfo, READ_TIMED_OUT, STREAM_COLS, Spec, TerminalRun,
2708    };
2709    use ai6::guatiao::{FromValue, ToValue};
2710    use std::collections::VecDeque;
2711
2712    #[test]
2713    fn a_runs_transcript_is_found_under_its_configuration_directory() {
2714        let config = tempfile::tempdir().unwrap();
2715        let project = config.path().join("projects").join("-work-repo");
2716        std::fs::create_dir_all(&project).unwrap();
2717        std::fs::write(project.join("abc-123.jsonl"), "{}\n").unwrap();
2718        let query = |run: &str| RunRecordQuery {
2719            run_id: run.to_owned(),
2720            working_directory: "/work/repo".to_owned(),
2721            environment: BTreeMap::from([(
2722                "CLAUDE_CONFIG_DIR".to_owned(),
2723                config.path().to_string_lossy().into_owned(),
2724            )]),
2725        };
2726        let found = claude_record(&query("abc-123")).unwrap();
2727        assert_eq!(
2728            std::path::PathBuf::from(found.path),
2729            project.join("abc-123.jsonl")
2730        );
2731        assert_eq!(found.format, RECORD_FORMAT);
2732        assert!(claude_record(&query("other")).is_none());
2733        assert!(claude_record(&query("../abc-123")).is_none());
2734    }
2735
2736    /// Claude Code 2.1.316's answer to `initialize`, cut to what the listing reads, with the
2737    /// `account` it also carries: that is never read.
2738    fn initialize_answer() -> Value {
2739        json!({
2740            "type": "control_response",
2741            "response": {
2742                "subtype": "success",
2743                "request_id": "ai6-models",
2744                "response": {
2745                    "account": {"email": "someone@example.invalid"},
2746                    "models": [
2747                        {"value": "default", "resolvedModel": "claude-opus-5-5",
2748                         "displayName": "Default (recommended)",
2749                         "description": "Use the default model", "supportsEffort": true},
2750                        {"value": "claude-haiku-5-5", "resolvedModel": "claude-haiku-5-5",
2751                         "displayName": "Haiku"},
2752                        {"value": "opus", "displayName": "Opus", "supportsEffort": true,
2753                         "supportedEffortLevels": ["low", "high"]},
2754                        {"displayName": "no value: not a model"}
2755                    ]
2756                }
2757            }
2758        })
2759    }
2760
2761    #[test]
2762    fn the_models_claude_code_lists_are_read_from_its_initialize_answer() {
2763        let answer = models_of(&InitializeAnswer::deserialize(initialize_answer()).unwrap());
2764        let models = answer.value().expect("the models are known");
2765        let ids: Vec<_> = models.iter().map(|model| model.id.as_str()).collect();
2766        assert_eq!(ids, ["default", "claude-haiku-5-5", "opus"]);
2767        assert_eq!(models[0].name.as_deref(), Some("Default (recommended)"));
2768        assert_eq!(
2769            models[0].description.as_deref(),
2770            Some("Use the default model (resolves to claude-opus-5-5)")
2771        );
2772        assert_eq!(models[1].description, None, "an id that resolves to itself");
2773        assert!(
2774            !format!("{answer:?}").contains("someone@example"),
2775            "the account is never read"
2776        );
2777    }
2778
2779    #[test]
2780    fn a_model_lists_the_efforts_it_takes_and_none_where_it_takes_none() {
2781        let answer = models_of(&InitializeAnswer::deserialize(initialize_answer()).unwrap());
2782        let models = answer.value().unwrap();
2783        assert_eq!(
2784            models[0].efforts, EFFORTS,
2785            "it says it takes effort and names no levels: the command line's own"
2786        );
2787        assert!(models[1].efforts.is_empty(), "it does not take effort");
2788        assert_eq!(models[2].efforts, ["low", "high"], "the levels it names");
2789    }
2790
2791    #[test]
2792    fn an_answer_without_models_or_a_refusal_is_unknown_never_empty() {
2793        for answer in [
2794            json!({"type": "control_response", "response": {"subtype": "error", "request_id": "ai6-models"}}),
2795            json!({"type": "control_response", "response": {"subtype": "success", "response": {"commands": []}}}),
2796        ] {
2797            let models = models_of(&InitializeAnswer::deserialize(answer).unwrap());
2798            assert!(
2799                matches!(&models, Answer::Unknown { reason } if !reason.is_empty()),
2800                "{models:?}"
2801            );
2802        }
2803    }
2804
2805    #[test]
2806    fn what_the_command_line_takes_is_known_and_what_claude_code_has_no_such_thing_as_is_declared()
2807    {
2808        let options = start_options_of(Answer::unknown("it did not answer"));
2809        assert!(
2810            matches!(&options.models, Answer::Unknown { reason } if reason == "it did not answer")
2811        );
2812        let efforts: Vec<_> = options
2813            .efforts
2814            .value()
2815            .unwrap()
2816            .iter()
2817            .map(|choice| choice.id.as_str())
2818            .collect();
2819        assert_eq!(efforts, ["low", "medium", "high", "xhigh", "max"]);
2820        let modes: Vec<_> = options
2821            .modes
2822            .value()
2823            .unwrap()
2824            .iter()
2825            .map(|choice| choice.id.as_str())
2826            .collect();
2827        assert_eq!(modes, ["manual", "accept_edits", "auto", "plan", "bypass"]);
2828        assert_eq!(options.config, Answer::NotSupported);
2829        assert_eq!(options.sessions, Answer::NotSupported);
2830    }
2831
2832    #[test]
2833    fn a_claude_code_that_cannot_run_has_unknown_models_and_the_rest_as_declared() {
2834        let config = ClaudeConfig {
2835            executable: "ai6-no-such-claude".to_owned(),
2836            ..ClaudeConfig::default()
2837        };
2838        let options = ClaudeHandler::try_from(config)
2839            .unwrap()
2840            .start_options(BTreeMap::new())
2841            .unwrap();
2842        assert!(
2843            matches!(options.models, Answer::Unknown { .. }),
2844            "{options:?}"
2845        );
2846        assert!(options.efforts.is_known() && options.modes.is_known());
2847        assert_eq!(options.sessions, Answer::NotSupported);
2848    }
2849
2850    /// Against the real Claude Code on this machine, with no login and no network: the harness
2851    /// answers `initialize` before any turn. Run with `AI6_TEST_LIVE_HARNESSES=1`.
2852    #[test]
2853    #[ignore = "needs Claude Code installed; set AI6_TEST_LIVE_HARNESSES=1 and run with --ignored"]
2854    fn live_claude_code_lists_models_with_no_login_and_no_turn() {
2855        assert!(
2856            std::env::var_os("AI6_TEST_LIVE_HARNESSES").is_some(),
2857            "set AI6_TEST_LIVE_HARNESSES=1"
2858        );
2859        let home = tempfile::tempdir().unwrap();
2860        let path = std::env::var("PATH").unwrap_or_default();
2861        let environment = BTreeMap::from([
2862            ("PATH".to_owned(), path),
2863            (
2864                "SYSTEMROOT".to_owned(),
2865                std::env::var("SYSTEMROOT").unwrap_or_default(),
2866            ),
2867            ("HOME".to_owned(), home.path().display().to_string()),
2868            ("USERPROFILE".to_owned(), home.path().display().to_string()),
2869            ("APPDATA".to_owned(), home.path().display().to_string()),
2870            ("LOCALAPPDATA".to_owned(), home.path().display().to_string()),
2871            (
2872                "CLAUDE_CONFIG_DIR".to_owned(),
2873                home.path().join(".claude").display().to_string(),
2874            ),
2875            ("ANTHROPIC_API_KEY".to_owned(), "dummy-not-a-key".to_owned()),
2876            (
2877                "ANTHROPIC_BASE_URL".to_owned(),
2878                "http://127.0.0.1:9".to_owned(),
2879            ),
2880        ]);
2881        let handler = ClaudeHandler::try_from(ClaudeConfig::default()).unwrap();
2882        let options = handler.start_options(environment).unwrap();
2883        let models = options
2884            .models
2885            .value()
2886            .unwrap_or_else(|| panic!("{options:?}"));
2887        assert!(models.iter().any(|model| model.id == "opus"), "{options:?}");
2888    }
2889    use std::io::{BufRead, BufReader, Read, Write};
2890    use std::process::{Child, ChildStdin, Command, Stdio};
2891    use std::sync::Arc;
2892    use std::sync::mpsc::{self, Receiver};
2893    use std::thread;
2894    use std::time::{Duration, Instant};
2895
2896    #[derive(Clone)]
2897    struct ProcessTerminal {
2898        specs: Arc<Mutex<Vec<Spec>>>,
2899        /// The text of the `--append-system-prompt-file` each spawn named, read as it spawned:
2900        /// the Run removes the file when it ends.
2901        contexts: Arc<Mutex<Vec<Option<String>>>>,
2902        /// Keeps the output open after the child exits, as ConPTY does.
2903        keep_open: bool,
2904    }
2905
2906    impl ProcessTerminal {
2907        fn new() -> Self {
2908            Self {
2909                specs: Arc::new(Mutex::new(Vec::new())),
2910                contexts: Arc::new(Mutex::new(Vec::new())),
2911                keep_open: false,
2912            }
2913        }
2914
2915        fn kept_open() -> Self {
2916            Self {
2917                keep_open: true,
2918                ..Self::new()
2919            }
2920        }
2921    }
2922
2923    /// A line the fake child writes that the fixture hands over although it is not JSON: the
2924    /// harness's own diagnostics.
2925    const FAKE_TEXT: &str = "fake-claude: ";
2926
2927    impl AgentTerminal for ProcessTerminal {
2928        fn spawn_private(
2929            &self,
2930            value: &ai6::guatiao::Value,
2931        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
2932            self.spawn(value)
2933        }
2934
2935        fn spawn(
2936            &self,
2937            value: &ai6::guatiao::Value,
2938        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
2939            let spec = Spec::from_value(value).map_err(internal)?;
2940            self.specs.lock().unwrap().push(spec.clone());
2941            let file = spec
2942                .argv
2943                .iter()
2944                .position(|argument| argument == "--append-system-prompt-file")
2945                .map(|at| std::fs::read_to_string(&spec.argv[at + 1]).unwrap());
2946            self.contexts.lock().unwrap().push(file);
2947
2948            let mut child = Command::new(std::env::current_exe().map_err(internal)?)
2949                .args(["--exact", "tests::fake_claude_child", "--nocapture"])
2950                .env("AI6_FAKE_CLAUDE_CHILD", "1")
2951                .envs(spec.env.unwrap_or_default())
2952                .stdin(Stdio::piped())
2953                .stdout(Stdio::piped())
2954                .stderr(Stdio::null())
2955                .spawn()
2956                .map_err(internal)?;
2957            let stdin = child.stdin.take().ok_or_else(|| {
2958                refuse(
2959                    Status::GUATIAO_ERR_INTERNAL,
2960                    "fake Claude stdin is unavailable",
2961                )
2962            })?;
2963            let stdout = child.stdout.take().ok_or_else(|| {
2964                refuse(
2965                    Status::GUATIAO_ERR_INTERNAL,
2966                    "fake Claude stdout is unavailable",
2967                )
2968            })?;
2969            let (sender, receiver) = mpsc::channel();
2970            let held_open = self.keep_open.then(|| sender.clone());
2971            thread::spawn(move || forward_json_lines(stdout, sender));
2972
2973            Ok(ProcessTerminalRun {
2974                child: Mutex::new(child),
2975                stdin: Mutex::new(stdin),
2976                receiver: Mutex::new(receiver),
2977                pending: Mutex::new(VecDeque::new()),
2978                _held_open: held_open,
2979            }
2980            .into_object())
2981        }
2982    }
2983
2984    fn forward_json_lines(mut stdout: impl Read, sender: mpsc::Sender<Vec<u8>>) {
2985        let mut reader = BufReader::new(&mut stdout);
2986        let mut line = Vec::new();
2987        loop {
2988            line.clear();
2989            match reader.read_until(b'\n', &mut line) {
2990                Ok(0) | Err(_) => return,
2991                Ok(_)
2992                    if serde_json::from_slice::<Value>(&line).is_ok()
2993                        || line.starts_with(FAKE_TEXT.as_bytes()) =>
2994                {
2995                    if sender.send(line.clone()).is_err() {
2996                        return;
2997                    }
2998                }
2999                Ok(_) => {}
3000            }
3001        }
3002    }
3003
3004    struct ProcessTerminalRun {
3005        child: Mutex<Child>,
3006        stdin: Mutex<ChildStdin>,
3007        receiver: Mutex<Receiver<Vec<u8>>>,
3008        pending: Mutex<VecDeque<u8>>,
3009        _held_open: Option<mpsc::Sender<Vec<u8>>>,
3010    }
3011
3012    impl TerminalRun for ProcessTerminalRun {
3013        fn pid(&self) -> i64 {
3014            i64::from(self.child.lock().unwrap().id())
3015        }
3016
3017        fn read(&self, dst: &mut [u8], timeout_ms: i64) -> Result<i64, ProviderError> {
3018            let mut pending = self.pending.lock().unwrap();
3019            if pending.is_empty() {
3020                match self
3021                    .receiver
3022                    .lock()
3023                    .unwrap()
3024                    .recv_timeout(Duration::from_millis(timeout_ms.max(0) as u64))
3025                {
3026                    Ok(bytes) => pending.extend(bytes),
3027                    Err(mpsc::RecvTimeoutError::Timeout) => return Ok(READ_TIMED_OUT),
3028                    Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(0),
3029                }
3030            }
3031            let count = dst.len().min(pending.len());
3032            for byte in &mut dst[..count] {
3033                *byte = pending
3034                    .pop_front()
3035                    .expect("count is bounded by pending bytes");
3036            }
3037            Ok(count as i64)
3038        }
3039
3040        fn write(&self, data: &[u8]) -> Result<(), ProviderError> {
3041            self.stdin.lock().unwrap().write_all(data).map_err(internal)
3042        }
3043
3044        fn resize(&self, _rows: i64, _cols: i64) -> Result<(), ProviderError> {
3045            Ok(())
3046        }
3047
3048        fn kill(&self) -> Result<(), ProviderError> {
3049            let mut child = self.child.lock().unwrap();
3050            match child.kill() {
3051                Ok(()) => child.wait().map(|_| ()).map_err(internal),
3052                Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => Ok(()),
3053                Err(error) => Err(internal(error)),
3054            }
3055        }
3056
3057        fn exit_status(&self, timeout_ms: i64) -> Result<ai6::guatiao::Value, ProviderError> {
3058            let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
3059            loop {
3060                if let Some(status) = self.child.lock().unwrap().try_wait().map_err(internal)? {
3061                    return ExitInfo {
3062                        running: false,
3063                        code: status.code().map(i64::from),
3064                        signal: None,
3065                    }
3066                    .to_value()
3067                    .map_err(internal);
3068                }
3069                if Instant::now() >= deadline {
3070                    return ExitInfo {
3071                        running: true,
3072                        ..ExitInfo::default()
3073                    }
3074                    .to_value()
3075                    .map_err(internal);
3076                }
3077                thread::sleep(Duration::from_millis(10));
3078            }
3079        }
3080    }
3081
3082    #[test]
3083    fn fake_claude_child() {
3084        if std::env::var_os("AI6_FAKE_CLAUDE_CHILD").is_none() {
3085            return;
3086        }
3087        let stdout = std::io::stdout();
3088        let mut stdout = stdout.lock();
3089        // Claude Code reads its first input before it writes anything (stream-json input); one
3090        // that cannot go on then says why and exits.
3091        if let Ok(code) = std::env::var("CLAUDE_FIXTURE_EXIT") {
3092            let mut first = String::new();
3093            std::io::stdin().lock().read_line(&mut first).unwrap();
3094            writeln!(stdout, "{FAKE_TEXT}Error: the stored login has expired").unwrap();
3095            stdout.flush().unwrap();
3096            std::process::exit(code.parse().unwrap());
3097        }
3098        let run_id = std::env::var("CLAUDE_FIXTURE_RUN_ID").unwrap();
3099        let mut initialized = false;
3100        for line in std::io::stdin().lock().lines() {
3101            let message: Value = serde_json::from_str(&line.unwrap()).unwrap();
3102            if message["type"] == "control_request" {
3103                if message.pointer("/request/subtype") == Some(&json!("initialize")) {
3104                    let answer = json!({"type": "control_response", "response": {
3105                        "subtype": "success", "request_id": message["request_id"],
3106                        "response": {}}});
3107                    writeln!(stdout, "{answer}").unwrap();
3108                    stdout.flush().unwrap();
3109                }
3110                continue;
3111            }
3112            if !std::mem::replace(&mut initialized, true) {
3113                writeln!(
3114                    stdout,
3115                    "{}",
3116                    json!({"type":"system","subtype":"init","session_id":run_id})
3117                )
3118                .unwrap();
3119            }
3120            let Some(text) = message
3121                .pointer("/message/content/0/text")
3122                .and_then(Value::as_str)
3123            else {
3124                continue;
3125            };
3126            writeln!(
3127                stdout,
3128                "{}",
3129                json!({"type":"assistant","session_id":run_id,"message":{"content":[{"type":"text","text":text}]}})
3130            )
3131            .unwrap();
3132            writeln!(
3133                stdout,
3134                "{}",
3135                json!({"type":"result","session_id":run_id,"result":text})
3136            )
3137            .unwrap();
3138            stdout.flush().unwrap();
3139        }
3140    }
3141
3142    fn read_to_completion(run: &Object<dyn AgentSession>) -> Vec<AgentEvent> {
3143        let deadline = Instant::now() + Duration::from_secs(60);
3144        let mut events = Vec::new();
3145        while Instant::now() < deadline {
3146            let remaining = deadline.saturating_duration_since(Instant::now());
3147            if let Some(event) = run
3148                .next_event(remaining.as_millis().min(i64::MAX as u128) as i64)
3149                .unwrap()
3150            {
3151                let completed = event.kind == "completed";
3152                events.push(event);
3153                if completed {
3154                    return events;
3155                }
3156            }
3157        }
3158        panic!("fake Claude did not complete the Run")
3159    }
3160
3161    #[test]
3162    fn process_run_restarts_and_resumes_with_the_same_provider_id() {
3163        let terminal = ProcessTerminal::new();
3164        let run_id = RunId::try_new("claude-process-session-42").unwrap();
3165        let environment =
3166            BTreeMap::from([("CLAUDE_FIXTURE_RUN_ID".to_owned(), run_id.to_string())]);
3167        let handler = ClaudeHandler::try_from(ClaudeConfig {
3168            executable: "claude-process-fixture".to_owned(),
3169            ..ClaudeConfig::default()
3170        })
3171        .unwrap();
3172
3173        let started = handler
3174            .start(
3175                AgentStart {
3176                    mission_id: "mission-process-42".parse().unwrap(),
3177                    agent_id: "007".to_owned(),
3178                    prompt: "first process turn".to_owned(),
3179                    initial_context: vec!["context before the prompt".to_owned()],
3180                    working_directory: std::env::current_dir()
3181                        .unwrap()
3182                        .to_string_lossy()
3183                        .into_owned(),
3184                    clearance: "field".to_owned(),
3185                    environment: environment.clone(),
3186                    model: Some("sonnet".to_owned()),
3187                    effort: Some("high".to_owned()),
3188                    max_cost_micro_usd: None,
3189                    project_settings: false,
3190                    project_mcp: false,
3191                    answer_only: false,
3192                    assistant: None,
3193                    overlays: Default::default(),
3194                    loadout: Default::default(),
3195                    ledger: None,
3196                },
3197                terminal.clone().into_object(),
3198            )
3199            .unwrap();
3200        let first_events = read_to_completion(&started);
3201        assert_eq!(started.session_id().unwrap(), Some(run_id.to_string()));
3202        assert!(first_events.iter().any(|event| {
3203            event.kind == "completed" && event.text.as_deref() == Some("first process turn")
3204        }));
3205        started.close().unwrap();
3206
3207        let resumed = handler
3208            .resume(
3209                AgentResume {
3210                    clearance: "field".to_owned(),
3211                    mission_id: "mission-process-42".parse().unwrap(),
3212                    run_id: run_id.clone(),
3213                    message: Some("resumed process turn".to_owned()),
3214                    working_directory: std::env::current_dir()
3215                        .unwrap()
3216                        .to_string_lossy()
3217                        .into_owned(),
3218                    environment,
3219                    model: Some("sonnet".to_owned()),
3220                    effort: Some("high".to_owned()),
3221                    max_cost_micro_usd: None,
3222                    project_settings: false,
3223                    project_mcp: false,
3224                    answer_only: false,
3225                    assistant: None,
3226                    initial_context: Vec::new(),
3227                    overlays: Default::default(),
3228                    loadout: Default::default(),
3229                },
3230                terminal.clone().into_object(),
3231            )
3232            .unwrap();
3233        let resumed_events = read_to_completion(&resumed);
3234        assert_eq!(resumed.session_id().unwrap(), Some(run_id.to_string()));
3235        assert!(resumed_events.iter().any(|event| {
3236            event.kind == "completed" && event.text.as_deref() == Some("resumed process turn")
3237        }));
3238        resumed.close().unwrap();
3239
3240        let specs = terminal.specs.lock().unwrap();
3241        assert_eq!(specs.len(), 2);
3242        assert!(
3243            specs[0]
3244                .argv
3245                .iter()
3246                .all(|arg| !arg.starts_with("--append-system-prompt=")),
3247            "the context goes through a file"
3248        );
3249        assert_eq!(
3250            terminal.contexts.lock().unwrap()[0].as_deref(),
3251            Some("context before the prompt")
3252        );
3253        assert!(
3254            specs[1]
3255                .argv
3256                .iter()
3257                .any(|argument| *argument == format!("--resume={run_id}"))
3258        );
3259    }
3260
3261    /// A model, effort or context starting with `-` stays the value of its own option.
3262    #[test]
3263    fn launch_option_values_are_never_read_as_options() {
3264        let mut argv = Vec::new();
3265        add_launch_options(
3266            &mut argv,
3267            Some("--dangerously-skip-permissions"),
3268            Some("-p"),
3269        );
3270        assert_eq!(
3271            argv,
3272            ["--model=--dangerously-skip-permissions", "--effort=-p"]
3273        );
3274    }
3275
3276    /// A standing context of 40 KB, as a charge's logbook makes one, stays out of the command
3277    /// line (Windows refuses one over 32,767 characters, os error 206): the argument names a file
3278    /// that holds all of it, nobody but the owner may read it, and it is gone with the Run.
3279    #[test]
3280    fn a_large_context_reaches_claude_through_a_private_file_not_the_command_line() {
3281        let big = "- 1700000000 failed: the turn did not end\n".repeat(1000);
3282        assert!(big.len() > 40_000);
3283        let mut argv = Vec::new();
3284        let private = add_context(&mut argv, &["standing".to_owned(), big.clone()], None)
3285            .unwrap()
3286            .expect("a context makes a file");
3287        let length: usize = argv.iter().map(|argument| argument.len() + 1).sum();
3288        assert!(length < 1024, "{length} characters: {argv:?}");
3289        assert_eq!(argv[0], "--append-system-prompt-file");
3290        let path = std::path::PathBuf::from(&argv[1]);
3291        assert!(path.starts_with(private.path()));
3292        assert_eq!(
3293            std::fs::read_to_string(&path).unwrap(),
3294            format!("standing\n\n{big}")
3295        );
3296        #[cfg(unix)]
3297        {
3298            use std::os::unix::fs::PermissionsExt;
3299            let mode = |path: &std::path::Path| {
3300                std::fs::metadata(path).unwrap().permissions().mode() & 0o777
3301            };
3302            assert_eq!(mode(&path), 0o600);
3303            assert_eq!(mode(private.path()), 0o700);
3304        }
3305        drop(private);
3306        assert!(!path.exists(), "removed with the Run");
3307        let mut none = Vec::new();
3308        assert!(add_context(&mut none, &[], None).unwrap().is_none());
3309        assert!(none.is_empty());
3310    }
3311
3312    /// Her default network is `denied`: no web tool is offered, and the harness says it can be
3313    /// kept to AI6's tools.
3314    #[test]
3315    fn her_default_network_offers_no_web_tool() {
3316        let mode = AssistantMode::moneypenny();
3317        assert_eq!(mode.network.policy, "denied");
3318        let tools = offered_tools(&mode);
3319        assert!(
3320            !tools.contains(&"WebFetch") && !tools.contains(&"WebSearch"),
3321            "{tools:?}"
3322        );
3323        let handler = ClaudeHandler::try_from(ClaudeConfig::default()).unwrap();
3324        assert_eq!(handler.assistant_network().unwrap(), None);
3325    }
3326
3327    /// An assistant's harness makes no connection but the model's and its MCP servers': the
3328    /// nonessential-traffic switch is set, an operator's own value for it wins, and a Run that
3329    /// is not an assistant keeps Claude Code's default.
3330    #[test]
3331    fn an_assistants_harness_turns_off_nonessential_traffic() {
3332        let mode = AssistantMode::moneypenny();
3333        let plain = BTreeMap::new();
3334        let set = harness_environment(&plain, true, Some(&mode));
3335        assert_eq!(
3336            set.get(DISABLE_NONESSENTIAL_TRAFFIC_ENV)
3337                .map(String::as_str),
3338            Some("1")
3339        );
3340        let mut own = BTreeMap::new();
3341        own.insert(DISABLE_NONESSENTIAL_TRAFFIC_ENV.to_owned(), String::new());
3342        assert_eq!(
3343            harness_environment(&own, true, Some(&mode))
3344                .get(DISABLE_NONESSENTIAL_TRAFFIC_ENV)
3345                .map(String::as_str),
3346            Some("")
3347        );
3348        assert_eq!(
3349            harness_environment(&plain, false, None).get(DISABLE_NONESSENTIAL_TRAFFIC_ENV),
3350            None
3351        );
3352        assert_eq!(
3353            harness_environment(&plain, true, None).get(DISABLE_NONESSENTIAL_TRAFFIC_ENV),
3354            None
3355        );
3356    }
3357
3358    /// The Run's file holds the context and the assistant mode's file, in that order, and the
3359    /// command line names one file only.
3360    #[test]
3361    fn the_assistants_context_file_joins_the_standing_context_in_one_file() {
3362        let directory = tempfile::tempdir().unwrap();
3363        let theirs = directory.path().join("assistant.md");
3364        std::fs::write(&theirs, "her notes").unwrap();
3365        let mode = AssistantMode {
3366            context_file: Some(theirs.to_string_lossy().into_owned()),
3367            ..AssistantMode::moneypenny()
3368        };
3369        let mut argv = Vec::new();
3370        let private = add_context(&mut argv, &["standing".to_owned()], Some(&mode))
3371            .unwrap()
3372            .unwrap();
3373        assert_eq!(argv.len(), 2, "{argv:?}");
3374        assert_eq!(
3375            std::fs::read_to_string(&argv[1]).unwrap(),
3376            "standing\n\nher notes"
3377        );
3378        drop(private);
3379        let missing = AssistantMode {
3380            context_file: Some(
3381                directory
3382                    .path()
3383                    .join("gone.md")
3384                    .to_string_lossy()
3385                    .into_owned(),
3386            ),
3387            ..AssistantMode::moneypenny()
3388        };
3389        assert!(add_context(&mut Vec::new(), &[], Some(&missing)).is_err());
3390    }
3391
3392    /// A terminal whose Claude Code answers `initialize` as the real one does, with no message
3393    /// written, and then writes `input`, so a stream is read once the driver waits for it.
3394    struct ResumeTerminal {
3395        spec: Arc<Mutex<Option<Spec>>>,
3396        input: Vec<u8>,
3397        writes: Arc<Mutex<Vec<u8>>>,
3398    }
3399
3400    impl AgentTerminal for ResumeTerminal {
3401        fn spawn_private(
3402            &self,
3403            value: &ai6::guatiao::Value,
3404        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3405            self.spawn(value)
3406        }
3407
3408        fn spawn(
3409            &self,
3410            value: &ai6::guatiao::Value,
3411        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3412            *self.spec.lock().unwrap() = Some(Spec::from_value(value).map_err(internal)?);
3413            Ok(
3414                ResumeTerminalRun::new(self.input.clone(), self.writes.clone(), false)
3415                    .into_object(),
3416            )
3417        }
3418    }
3419
3420    /// A terminal whose Claude Code reads `initialize` and never answers it.
3421    struct MuteTerminal;
3422
3423    impl AgentTerminal for MuteTerminal {
3424        fn spawn_private(
3425            &self,
3426            value: &ai6::guatiao::Value,
3427        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3428            self.spawn(value)
3429        }
3430
3431        fn spawn(
3432            &self,
3433            _value: &ai6::guatiao::Value,
3434        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3435            let mut run = ResumeTerminalRun::new(Vec::new(), Arc::default(), false);
3436            run.mute = true;
3437            Ok(run.into_object())
3438        }
3439    }
3440
3441    /// A terminal that answers `initialize` and then closes its output.
3442    struct EofTerminal;
3443
3444    impl AgentTerminal for EofTerminal {
3445        fn spawn_private(
3446            &self,
3447            value: &ai6::guatiao::Value,
3448        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3449            self.spawn(value)
3450        }
3451
3452        fn spawn(
3453            &self,
3454            _value: &ai6::guatiao::Value,
3455        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3456            Ok(ResumeTerminalRun::new(Vec::new(), Arc::default(), true).into_object())
3457        }
3458    }
3459
3460    /// Like [`ResumeTerminal`], with the stream held back until `hold` is cleared.
3461    struct HeldTerminal {
3462        spec: Arc<Mutex<Option<Spec>>>,
3463        input: Vec<u8>,
3464        writes: Arc<Mutex<Vec<u8>>>,
3465        hold: Arc<AtomicBool>,
3466    }
3467
3468    impl AgentTerminal for HeldTerminal {
3469        fn spawn_private(
3470            &self,
3471            value: &ai6::guatiao::Value,
3472        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3473            self.spawn(value)
3474        }
3475
3476        fn spawn(
3477            &self,
3478            value: &ai6::guatiao::Value,
3479        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3480            *self.spec.lock().unwrap() = Some(Spec::from_value(value).map_err(internal)?);
3481            let mut run = ResumeTerminalRun::new(self.input.clone(), self.writes.clone(), false);
3482            run.hold = self.hold.clone();
3483            Ok(run.into_object())
3484        }
3485    }
3486
3487    struct Script {
3488        answers: VecDeque<u8>,
3489        output: VecDeque<u8>,
3490        released: bool,
3491    }
3492
3493    struct ResumeTerminalRun {
3494        script: Mutex<Script>,
3495        arrived: Condvar,
3496        stream: Vec<u8>,
3497        writes: Arc<Mutex<Vec<u8>>>,
3498        eof: bool,
3499        /// While set, the stream is not read: only the answers to what was written.
3500        hold: Arc<AtomicBool>,
3501        /// The version Claude Code's answer to `initialize` reports.
3502        version: Option<String>,
3503        /// Claude Code never answers `initialize`.
3504        mute: bool,
3505    }
3506
3507    impl ResumeTerminalRun {
3508        fn new(stream: Vec<u8>, writes: Arc<Mutex<Vec<u8>>>, eof: bool) -> Self {
3509            Self {
3510                script: Mutex::new(Script {
3511                    answers: VecDeque::new(),
3512                    output: VecDeque::new(),
3513                    released: false,
3514                }),
3515                arrived: Condvar::new(),
3516                stream,
3517                writes,
3518                eof,
3519                hold: Arc::new(AtomicBool::new(false)),
3520                version: None,
3521                mute: false,
3522            }
3523        }
3524    }
3525
3526    impl TerminalRun for ResumeTerminalRun {
3527        fn pid(&self) -> i64 {
3528            7
3529        }
3530
3531        fn read(&self, dst: &mut [u8], timeout_ms: i64) -> Result<i64, ProviderError> {
3532            let mut script = self.script.lock().unwrap();
3533            let held = |script: &Script| {
3534                script.answers.is_empty()
3535                    && (script.output.is_empty() || self.hold.load(Ordering::Acquire))
3536            };
3537            if held(&script) {
3538                // Short waits, so a stream let go of is read at once.
3539                let wait = Duration::from_millis(timeout_ms.clamp(0, 20) as u64);
3540                script = self.arrived.wait_timeout(script, wait).unwrap().0;
3541            }
3542            if held(&script) {
3543                return Ok(if self.eof && script.released && script.output.is_empty() {
3544                    0
3545                } else {
3546                    READ_TIMED_OUT
3547                });
3548            }
3549            let from_answers = !script.answers.is_empty();
3550            let source = if from_answers {
3551                &mut script.answers
3552            } else {
3553                &mut script.output
3554            };
3555            let count = dst.len().min(source.len());
3556            for byte in &mut dst[..count] {
3557                *byte = source.pop_front().unwrap();
3558            }
3559            Ok(count as i64)
3560        }
3561
3562        fn write(&self, data: &[u8]) -> Result<(), ProviderError> {
3563            self.writes.lock().unwrap().extend_from_slice(data);
3564            if self.mute {
3565                return Ok(());
3566            }
3567            for line in data.split(|byte| *byte == b'\n') {
3568                let Ok(message) = serde_json::from_slice::<Value>(line) else {
3569                    continue;
3570                };
3571                if message["type"] != "control_request"
3572                    || message.pointer("/request/subtype") != Some(&json!("initialize"))
3573                {
3574                    continue;
3575                }
3576                let mut script = self.script.lock().unwrap();
3577                let answer = json!({"type": "control_response", "response": {
3578                    "subtype": "success", "request_id": message["request_id"],
3579                    "response": {"claude_code_version": self.version}}});
3580                script.answers.extend(format!("{answer}\n").into_bytes());
3581                if !script.released {
3582                    script.released = true;
3583                    script.output.extend(self.stream.iter().copied());
3584                }
3585                self.arrived.notify_all();
3586            }
3587            Ok(())
3588        }
3589
3590        fn resize(&self, _rows: i64, _cols: i64) -> Result<(), ProviderError> {
3591            Ok(())
3592        }
3593
3594        fn kill(&self) -> Result<(), ProviderError> {
3595            Ok(())
3596        }
3597
3598        fn exit_status(&self, _timeout_ms: i64) -> Result<ai6::guatiao::Value, ProviderError> {
3599            Err(refuse(
3600                Status::GUATIAO_ERR_INTERNAL,
3601                "unused in resume test",
3602            ))
3603        }
3604    }
3605
3606    /// Claude Code, started with the settings of a Run that is not gated, on `terminal`.
3607    fn open_on(terminal: impl AgentTerminal + 'static, allowed: Option<Allowed>) -> ClaudeRun {
3608        let config = ClaudeConfig::default();
3609        open(Opening {
3610            config: &config,
3611            terminal: terminal.into_object(),
3612            flags: Vec::new(),
3613            cwd: "/work",
3614            environment: BTreeMap::new(),
3615            session: SessionStart::Chosen,
3616            expected_run_id: None,
3617            restricted: allowed,
3618            private: None,
3619            minimum_version: None,
3620        })
3621        .unwrap()
3622    }
3623
3624    /// The wait for Claude Code's `initialize` answer is the configured one, not a fixed 30 s: a
3625    /// host whose Claude Code runs several `SessionStart` hooks first needs more, and a test
3626    /// needs less.
3627    #[test]
3628    fn a_claude_code_that_never_answers_initialize_fails_the_start_after_the_configured_wait() {
3629        let config = ClaudeConfig {
3630            initialize_wait_ms: 300,
3631            ..ClaudeConfig::default()
3632        };
3633        let started = Instant::now();
3634        let error = match open(Opening {
3635            config: &config,
3636            terminal: MuteTerminal.into_object(),
3637            flags: Vec::new(),
3638            cwd: "/work",
3639            environment: BTreeMap::new(),
3640            session: SessionStart::Chosen,
3641            expected_run_id: None,
3642            restricted: None,
3643            private: None,
3644            minimum_version: None,
3645        }) {
3646            Ok(_) => panic!("a Claude Code that never answered started"),
3647            Err(error) => error.to_string(),
3648        };
3649        assert!(error.contains("did not answer"), "{error}");
3650        assert!(
3651            error.contains("300ms"),
3652            "the configured wait is named: {error}"
3653        );
3654        assert!(started.elapsed() < Duration::from_secs(10));
3655    }
3656
3657    #[test]
3658    fn a_start_from_a_ledger_that_fails_leaves_no_transcript_behind() {
3659        let config_dir = tempfile::tempdir().unwrap();
3660        let ledger = ai6::StartLedger::from_text(&format!("{}\n", [r#"{"format":"coqui-acp-history","version":1,"id":"5f0f6d6e-3f3c-4f1a-8a52-1c1e6f0b9a77","origin":{"harness":"codex"}}"#,
3661                r#"{"method":"session/prompt","params":{"prompt":[{"type":"text","text":"fix the parser"}]}}"#,
3662                r#"{"method":"history/turn_end","params":{"stopReason":"end_turn"}}"#,
3663            ].join("\n"))).unwrap();
3664        let handler = ClaudeHandler::try_from(ClaudeConfig {
3665            executable: "claude-test".to_owned(),
3666            initialize_wait_ms: 300,
3667            ..ClaudeConfig::default()
3668        })
3669        .unwrap();
3670        let mut request = start_request("continue", None);
3671        request.working_directory = "/work".to_owned();
3672        request.environment.insert(
3673            "CLAUDE_CONFIG_DIR".to_owned(),
3674            config_dir.path().to_string_lossy().into_owned(),
3675        );
3676        request.ledger = Some(ledger);
3677        assert!(handler.start(request, MuteTerminal.into_object()).is_err());
3678        let mut left = Vec::new();
3679        for project in std::fs::read_dir(config_dir.path().join("projects"))
3680            .into_iter()
3681            .flatten()
3682            .flatten()
3683        {
3684            left.extend(std::fs::read_dir(project.path()).unwrap().flatten());
3685        }
3686        assert!(left.is_empty(), "{left:?}");
3687    }
3688
3689    /// A Run that reads `input` after its start, restricted to what `allowed` names.
3690    fn restricted_run(input: Vec<u8>, allowed: Option<Allowed>) -> ClaudeRun {
3691        open_on(
3692            ResumeTerminal {
3693                spec: Arc::new(Mutex::new(None)),
3694                input,
3695                writes: Arc::new(Mutex::new(Vec::new())),
3696            },
3697            allowed,
3698        )
3699    }
3700
3701    /// A terminal whose Claude Code reports `version` and writes what it is sent to `writes`.
3702    struct VersionedTerminal {
3703        version: Option<&'static str>,
3704        writes: Arc<Mutex<Vec<u8>>>,
3705    }
3706
3707    impl AgentTerminal for VersionedTerminal {
3708        fn spawn_private(
3709            &self,
3710            value: &ai6::guatiao::Value,
3711        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3712            self.spawn(value)
3713        }
3714
3715        fn spawn(
3716            &self,
3717            _value: &ai6::guatiao::Value,
3718        ) -> Result<Object<dyn TerminalRun>, ProviderError> {
3719            let mut run = ResumeTerminalRun::new(Vec::new(), self.writes.clone(), false);
3720            run.version = self.version.map(str::to_owned);
3721            Ok(run.into_object())
3722        }
3723    }
3724
3725    fn start_request(prompt: &str, minimum: Option<&str>) -> AgentStart {
3726        let mut environment = BTreeMap::new();
3727        if let Some(minimum) = minimum {
3728            environment.insert(
3729                THEATER_PLUGIN_MIN_VERSION_ENV.to_owned(),
3730                minimum.to_owned(),
3731            );
3732        }
3733        AgentStart {
3734            mission_id: "mission-42".parse().unwrap(),
3735            agent_id: "007".to_owned(),
3736            prompt: prompt.to_owned(),
3737            initial_context: Vec::new(),
3738            working_directory: "/work".to_owned(),
3739            clearance: "field".to_owned(),
3740            environment,
3741            model: None,
3742            effort: None,
3743            max_cost_micro_usd: None,
3744            project_settings: false,
3745            project_mcp: false,
3746            answer_only: false,
3747            assistant: None,
3748            overlays: Default::default(),
3749            loadout: Default::default(),
3750            ledger: None,
3751        }
3752    }
3753
3754    /// A start's outcome and the bytes Claude Code was sent.
3755    type Started = (
3756        Result<Object<dyn ai6::AgentSession>, ProviderError>,
3757        Arc<Mutex<Vec<u8>>>,
3758    );
3759
3760    fn start_on(version: Option<&'static str>, request: AgentStart) -> Started {
3761        let writes = Arc::new(Mutex::new(Vec::new()));
3762        let handler = ClaudeHandler::try_from(ClaudeConfig {
3763            executable: "claude-test".to_owned(),
3764            ..ClaudeConfig::default()
3765        })
3766        .unwrap();
3767        let started = handler.start(
3768            request,
3769            VersionedTerminal {
3770                version,
3771                writes: writes.clone(),
3772            }
3773            .into_object(),
3774        );
3775        (started, writes)
3776    }
3777
3778    /// What Claude Code was sent so far, after giving the driver's writer a moment.
3779    fn written(writes: &Arc<Mutex<Vec<u8>>>) -> String {
3780        std::thread::sleep(Duration::from_millis(300));
3781        String::from_utf8_lossy(&writes.lock().unwrap()).into_owned()
3782    }
3783
3784    #[test]
3785    fn versions_are_compared_by_their_numbers() {
3786        assert!(older_than("2.1.294", "2.1.295"));
3787        assert!(older_than("2.0.999", "2.1.295"));
3788        assert!(older_than("1.9.9", "2.1.295"));
3789        assert!(!older_than("2.1.295", "2.1.295"));
3790        assert!(!older_than("2.1.326 (Claude Code)", "2.1.295"));
3791        assert!(!older_than("2.10.0", "2.9.9"));
3792        assert!(older_than("not a version", "2.1.295"), "unknown is refused");
3793    }
3794
3795    #[test]
3796    fn a_taken_over_run_on_a_claude_code_below_the_hooks_minimum_is_refused() {
3797        let (started, writes) = start_on(Some("2.1.294"), start_request("go", Some("2.1.295")));
3798        let Err(error) = started else {
3799            panic!("an old Claude Code is refused");
3800        };
3801        assert!(error.to_string().contains("2.1.295"), "{error}");
3802        let written = written(&writes);
3803        assert!(
3804            !written.contains("\"type\":\"user\""),
3805            "nothing was sent: {written}"
3806        );
3807        // Its version unknown is as bad: the hook's behaviour on failure is not known.
3808        let (started, _) = start_on(None, start_request("go", Some("2.1.295")));
3809        assert!(started.is_err());
3810        // A new enough one starts, and so does any version when no hook is taking over.
3811        assert!(
3812            start_on(Some("2.1.295"), start_request("go", Some("2.1.295")))
3813                .0
3814                .is_ok()
3815        );
3816        assert!(start_on(Some("1.0.0"), start_request("go", None)).0.is_ok());
3817    }
3818
3819    #[test]
3820    fn an_empty_prompt_sends_nothing_and_a_prompt_is_sent() {
3821        let (started, writes) = start_on(Some("2.1.326"), start_request("", None));
3822        let run = started.unwrap();
3823        assert!(!written(&writes).contains("\"type\":\"user\""));
3824        run.send_message(AgentMessage {
3825            text: "now".to_owned(),
3826        })
3827        .unwrap();
3828        // The positive control: a prompt is seen written, so the silence above means nothing was sent.
3829        let (started, writes) = start_on(Some("2.1.326"), start_request("hello", None));
3830        started.unwrap();
3831        let written = written(&writes);
3832        assert!(
3833            written.contains("\"type\":\"user\"") && written.contains("hello"),
3834            "{written}"
3835        );
3836    }
3837
3838    #[test]
3839    fn resume_uses_the_provider_id_and_stream_json_message() {
3840        let run_id = RunId::try_new("claude-session-42").unwrap();
3841        let spec = Arc::new(Mutex::new(None));
3842        let writes = Arc::new(Mutex::new(Vec::new()));
3843        let hold = Arc::new(AtomicBool::new(true));
3844        let terminal = HeldTerminal {
3845            spec: spec.clone(),
3846            input:
3847                b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\n"
3848                    .to_vec(),
3849            writes: writes.clone(),
3850            hold: hold.clone(),
3851        };
3852        let handler = ClaudeHandler::try_from(ClaudeConfig {
3853            executable: "claude-test".to_owned(),
3854            ..ClaudeConfig::default()
3855        })
3856        .unwrap();
3857        let run = handler
3858            .resume(
3859                AgentResume {
3860                    clearance: "field".to_owned(),
3861                    mission_id: "mission-42".parse().unwrap(),
3862                    run_id: run_id.clone(),
3863                    message: Some("continue the same Run".to_owned()),
3864                    working_directory: "C:\\station\\mission-42".to_owned(),
3865                    environment: BTreeMap::from([("TOKEN".to_owned(), "fresh".to_owned())]),
3866                    model: Some("sonnet".to_owned()),
3867                    effort: Some("high".to_owned()),
3868                    max_cost_micro_usd: None,
3869                    project_settings: false,
3870                    project_mcp: false,
3871                    answer_only: false,
3872                    assistant: None,
3873                    initial_context: Vec::new(),
3874                    overlays: Default::default(),
3875                    loadout: Default::default(),
3876                },
3877                terminal.into_object(),
3878            )
3879            .unwrap();
3880
3881        assert_eq!(
3882            run.session_id().unwrap(),
3883            None,
3884            "unknown until Claude reports it"
3885        );
3886        hold.store(false, Ordering::Release);
3887        let event = run.next_event(2_000).unwrap().unwrap();
3888        assert_eq!(event.kind, "system");
3889        assert_eq!(run.session_id().unwrap(), Some(run_id.to_string()));
3890
3891        let spec = spec.lock().unwrap().clone().unwrap();
3892        assert!(
3893            spec.argv
3894                .iter()
3895                .any(|argument| argument == "--resume=claude-session-42")
3896        );
3897        assert!(spec.argv.iter().any(|arg| arg == "--model=sonnet"));
3898        assert!(spec.argv.iter().any(|arg| arg == "--effort=high"));
3899        assert_eq!(spec.cwd.as_deref(), Some("C:\\station\\mission-42"));
3900        assert_eq!(
3901            spec.env.as_ref().unwrap().get("TOKEN").map(String::as_str),
3902            Some("fresh")
3903        );
3904
3905        let deadline = Instant::now() + Duration::from_secs(5);
3906        while Instant::now() < deadline
3907            && !String::from_utf8_lossy(&writes.lock().unwrap()).contains("\"user\"")
3908        {
3909            std::thread::sleep(Duration::from_millis(20));
3910        }
3911        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
3912        let message = written
3913            .lines()
3914            .map(|line| serde_json::from_str::<Value>(line).unwrap())
3915            .find(|message| message["type"] == "user")
3916            .expect("the message was written");
3917        assert_eq!(message["type"], "user");
3918        assert_eq!(
3919            message["message"]["content"][0]["text"],
3920            "continue the same Run"
3921        );
3922    }
3923
3924    /// Claude Code's stream as ConPTY renders it on Windows: mode and title sequences first, a
3925    /// CRLF after each line, the echoed input, and a line longer than the terminal broken
3926    /// with CRLF and a cursor move.
3927    #[test]
3928    fn a_stream_rendered_by_conpty_reads_as_the_lines_claude_wrote() {
3929        let long = "w".repeat(20_000);
3930        let assistant = format!(
3931            "{{\"type\":\"assistant\",\"message\":{{\"content\":[{{\"type\":\"text\",\"text\":\"{long}\"}}]}}}}"
3932        );
3933        let (head, tail) = assistant.split_at(9_000);
3934        let mut input =
3935            b"\x1b[?9001h\x1b[?1004h\x1b[m\x1b]0;C:\\bin\\claude.exe\x07\x1b[?25h\r\n".to_vec();
3936        input.extend_from_slice(
3937            b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\r\n",
3938        );
3939        input.extend_from_slice(b"{\"type\":\"user\",\"message\":{\"role\":\"user\"}}\r\n");
3940        input.extend_from_slice(head.as_bytes());
3941        input.extend_from_slice(b"\r\n\x1b[23;9000H");
3942        input.extend_from_slice(tail.as_bytes());
3943        input.extend_from_slice(b"\r\n\x1b[?25l{\"type\":\"result\",\"result\":\"done\"}\r\n");
3944        let spec = Arc::new(Mutex::new(None));
3945        let terminal = ResumeTerminal {
3946            spec: spec.clone(),
3947            input,
3948            writes: Arc::new(Mutex::new(Vec::new())),
3949        };
3950        let handler = ClaudeHandler::try_from(ClaudeConfig {
3951            executable: "claude-test".to_owned(),
3952            ..ClaudeConfig::default()
3953        })
3954        .unwrap();
3955        let run = handler
3956            .resume(
3957                AgentResume {
3958                    clearance: "field".to_owned(),
3959                    mission_id: "mission-42".parse().unwrap(),
3960                    run_id: RunId::try_new("claude-session-42").unwrap(),
3961                    message: None,
3962                    working_directory: "C:\\station\\mission-42".to_owned(),
3963                    environment: BTreeMap::new(),
3964                    model: None,
3965                    effort: None,
3966                    max_cost_micro_usd: None,
3967                    project_settings: false,
3968                    project_mcp: false,
3969                    answer_only: false,
3970                    assistant: None,
3971                    initial_context: Vec::new(),
3972                    overlays: Default::default(),
3973                    loadout: Default::default(),
3974                },
3975                terminal.into_object(),
3976            )
3977            .unwrap();
3978        let kinds_and_texts = std::iter::from_fn(|| run.next_event(400).unwrap())
3979            .map(|event| (event.kind, event.text))
3980            .collect::<Vec<_>>();
3981        assert_eq!(
3982            kinds_and_texts,
3983            [
3984                ("system".to_owned(), None),
3985                ("text".to_owned(), Some(long)),
3986                ("completed".to_owned(), Some("done".to_owned())),
3987            ]
3988        );
3989        assert_eq!(spec.lock().unwrap().as_ref().unwrap().cols, STREAM_COLS);
3990    }
3991
3992    /// An interrupt is one stream-json control request; Claude's answers to it, the idle
3993    /// `success` Claude Code 2.1.310 sends and an `error`, are consumed, never events.
3994    #[test]
3995    fn interrupt_writes_a_control_request_and_consumes_its_response() {
3996        let mut input =
3997            b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\n"
3998                .to_vec();
3999        input.extend_from_slice(
4000            b"{\"type\":\"control_response\",\"response\":{\"subtype\":\"success\",\
4001              \"request_id\":\"ai6-interrupt-1\",\"response\":{\"still_queued\":[]}}}\n",
4002        );
4003        input.extend_from_slice(
4004            b"{\"type\":\"control_response\",\"response\":{\"subtype\":\"error\",\
4005              \"request_id\":\"ai6-interrupt-2\",\"error\":\"no turn to interrupt\"}}\n",
4006        );
4007        input.extend_from_slice(b"{\"type\":\"result\",\"result\":\"stopped\"}\n");
4008        let writes = Arc::new(Mutex::new(Vec::new()));
4009        let terminal = ResumeTerminal {
4010            spec: Arc::new(Mutex::new(None)),
4011            input,
4012            writes: writes.clone(),
4013        };
4014        let handler = ClaudeHandler::try_from(ClaudeConfig {
4015            executable: "claude-test".to_owned(),
4016            ..ClaudeConfig::default()
4017        })
4018        .unwrap();
4019        let run = handler
4020            .resume(
4021                AgentResume {
4022                    clearance: "field".to_owned(),
4023                    mission_id: "mission-42".parse().unwrap(),
4024                    run_id: RunId::try_new("claude-session-42").unwrap(),
4025                    message: None,
4026                    working_directory: "C:\\station\\mission-42".to_owned(),
4027                    environment: BTreeMap::new(),
4028                    model: None,
4029                    effort: None,
4030                    max_cost_micro_usd: None,
4031                    project_settings: false,
4032                    project_mcp: false,
4033                    answer_only: false,
4034                    assistant: None,
4035                    initial_context: Vec::new(),
4036                    overlays: Default::default(),
4037                    loadout: Default::default(),
4038                },
4039                terminal.into_object(),
4040            )
4041            .unwrap();
4042
4043        run.interrupt().unwrap();
4044        run.interrupt().unwrap();
4045
4046        // The driver writes on a thread of its own.
4047        let deadline = Instant::now() + Duration::from_secs(5);
4048        while Instant::now() < deadline
4049            && String::from_utf8_lossy(&writes.lock().unwrap())
4050                .matches("\"interrupt\"")
4051                .count()
4052                < 2
4053        {
4054            std::thread::sleep(Duration::from_millis(20));
4055        }
4056        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4057        assert!(!written.contains('\u{3}'), "no ^C byte reaches the stream");
4058        // The driver numbers its own requests: the shape is the contract, the id is its own.
4059        let mut requests = written
4060            .lines()
4061            .map(|line| serde_json::from_str::<Value>(line).unwrap())
4062            .filter(|request| request.pointer("/request/subtype") == Some(&json!("interrupt")))
4063            .collect::<Vec<_>>();
4064        assert!(requests.iter().all(|request| {
4065            request["request_id"]
4066                .as_str()
4067                .is_some_and(|id| !id.is_empty())
4068        }));
4069        for request in &mut requests {
4070            request.as_object_mut().unwrap().remove("request_id");
4071        }
4072        let interrupt = json!({"type": "control_request", "request": { "subtype": "interrupt" }});
4073        assert_eq!(requests, [interrupt.clone(), interrupt]);
4074        assert!(written.ends_with('\n'));
4075
4076        let kinds_and_texts = std::iter::from_fn(|| run.next_event(400).unwrap())
4077            .map(|event| (event.kind, event.text))
4078            .collect::<Vec<_>>();
4079        assert_eq!(
4080            kinds_and_texts,
4081            [
4082                ("system".to_owned(), None),
4083                ("completed".to_owned(), Some("stopped".to_owned())),
4084            ]
4085        );
4086    }
4087
4088    /// A resumed Run on a terminal whose Claude Code writes `stream`; the writes are kept.
4089    fn resumed_on(stream: &str) -> (Object<dyn ai6::AgentSession>, Arc<Mutex<Vec<u8>>>) {
4090        let writes = Arc::new(Mutex::new(Vec::new()));
4091        let terminal = ResumeTerminal {
4092            spec: Arc::new(Mutex::new(None)),
4093            input: stream.as_bytes().to_vec(),
4094            writes: writes.clone(),
4095        };
4096        let handler = ClaudeHandler::try_from(ClaudeConfig {
4097            executable: "claude-test".to_owned(),
4098            ..ClaudeConfig::default()
4099        })
4100        .unwrap();
4101        let run = handler
4102            .resume(
4103                AgentResume {
4104                    clearance: "field".to_owned(),
4105                    mission_id: "mission-42".parse().unwrap(),
4106                    run_id: RunId::try_new("claude-session-42").unwrap(),
4107                    message: None,
4108                    working_directory: "C:\\station\\mission-42".to_owned(),
4109                    environment: BTreeMap::new(),
4110                    model: None,
4111                    effort: None,
4112                    max_cost_micro_usd: None,
4113                    project_settings: false,
4114                    project_mcp: false,
4115                    answer_only: false,
4116                    assistant: None,
4117                    initial_context: Vec::new(),
4118                    overlays: Default::default(),
4119                    loadout: Default::default(),
4120                },
4121                terminal.into_object(),
4122            )
4123            .unwrap();
4124        (run, writes)
4125    }
4126
4127    /// What the driver wrote as user messages, by text.
4128    fn written_texts(writes: &Arc<Mutex<Vec<u8>>>) -> Vec<String> {
4129        let deadline = Instant::now() + Duration::from_secs(5);
4130        loop {
4131            let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4132            let texts = written
4133                .lines()
4134                .filter_map(|line| serde_json::from_str::<Value>(line).ok())
4135                .filter(|value| value["type"] == "user")
4136                .filter_map(|value| {
4137                    value
4138                        .pointer("/message/content/0/text")
4139                        .and_then(Value::as_str)
4140                        .map(str::to_owned)
4141                })
4142                .collect::<Vec<_>>();
4143            if !texts.is_empty() || Instant::now() > deadline {
4144                return texts;
4145            }
4146            std::thread::sleep(Duration::from_millis(20));
4147        }
4148    }
4149
4150    /// `/compact` is a user turn in stream-json input. Claude Code 2.1.326 answers it with
4151    /// `status: compacting`, a `compact_boundary` that counts the tokens before and after, and a
4152    /// `result`; the lines here are those it wrote, cut to what the handler reads.
4153    #[test]
4154    fn a_compaction_is_a_slash_command_and_its_boundary_counts_the_tokens() {
4155        let stream = concat!(
4156            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\n",
4157            "{\"type\":\"system\",\"subtype\":\"status\",\"status\":\"compacting\",\"session_id\":\"claude-session-42\"}\n",
4158            "{\"type\":\"system\",\"subtype\":\"status\",\"status\":null,\"compact_result\":\"success\",\"session_id\":\"claude-session-42\"}\n",
4159            "{\"type\":\"system\",\"subtype\":\"compact_boundary\",\"session_id\":\"claude-session-42\",\"compact_metadata\":{\"trigger\":\"manual\",\"pre_tokens\":23879,\"post_tokens\":2830,\"cumulative_dropped_tokens\":21049}}\n",
4160            "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"num_turns\":0,\"session_id\":\"claude-session-42\"}\n",
4161        );
4162        let (run, writes) = resumed_on(stream);
4163        run.send_message(AgentMessage {
4164            text: SessionCommand::Compact {
4165                focus: Some("keep the\nfruit words".to_owned()),
4166            }
4167            .encode(),
4168        })
4169        .unwrap();
4170        assert_eq!(
4171            written_texts(&writes),
4172            ["/compact keep the fruit words".to_owned()]
4173        );
4174        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4175        let kinds = events.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>();
4176        assert_eq!(
4177            kinds,
4178            ["system", "system", "system", "compacted", "completed"]
4179        );
4180        let change = SessionChange::of(&events[3]).unwrap();
4181        assert_eq!(change.trigger.as_deref(), Some("manual"));
4182        assert_eq!(
4183            (change.tokens_before, change.tokens_after),
4184            (Some(23879), Some(2830))
4185        );
4186    }
4187
4188    /// A compaction Claude Code could not make is a `compact_result: failed` status, and its
4189    /// `result` is still a success: the event is what tells the Station nothing changed.
4190    #[test]
4191    fn a_failed_compaction_is_reported_and_the_turn_still_ends() {
4192        let stream = concat!(
4193            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\n",
4194            "{\"type\":\"system\",\"subtype\":\"status\",\"status\":null,\"compact_result\":\"failed\",\"compact_error\":\"Not enough messages to compact.\"}\n",
4195            "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"num_turns\":0}\n",
4196        );
4197        let (run, _writes) = resumed_on(stream);
4198        run.send_message(AgentMessage {
4199            text: SessionCommand::Compact { focus: None }.encode(),
4200        })
4201        .unwrap();
4202        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4203        let failed = events
4204            .iter()
4205            .find(|event| event.kind == ai6::COMPACT_FAILED_EVENT)
4206            .expect("the failure is an event");
4207        assert_eq!(
4208            failed.text.as_deref(),
4209            Some("Not enough messages to compact.")
4210        );
4211        assert_eq!(events.last().unwrap().kind, "completed");
4212    }
4213
4214    /// `/clear` keeps the process and gives the conversation a new session id, which `session_id`
4215    /// then answers. The line order is Claude Code 2.1.326's.
4216    #[test]
4217    fn a_clear_keeps_the_run_and_takes_the_new_session_id() {
4218        let stream = concat!(
4219            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\n",
4220            "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"session_id\":\"claude-session-42\"}\n",
4221            "{\"type\":\"conversation_reset\",\"new_conversation_id\":\"conv-9\",\"trigger\":\"clear\",\"session_id\":\"claude-session-42\"}\n",
4222            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-43\"}\n",
4223            "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"num_turns\":0,\"session_id\":\"claude-session-43\"}\n",
4224        );
4225        let writes = Arc::new(Mutex::new(Vec::new()));
4226        let terminal = ResumeTerminal {
4227            spec: Arc::new(Mutex::new(None)),
4228            input: stream.as_bytes().to_vec(),
4229            writes: writes.clone(),
4230        };
4231        let handler = ClaudeHandler::try_from(ClaudeConfig {
4232            executable: "claude-test".to_owned(),
4233            ..ClaudeConfig::default()
4234        })
4235        .unwrap();
4236        let run = handler
4237            .start(
4238                AgentStart {
4239                    mission_id: "mission-42".parse().unwrap(),
4240                    agent_id: "007".to_owned(),
4241                    prompt: "first".to_owned(),
4242                    initial_context: Vec::new(),
4243                    working_directory: "C:\\station\\mission-42".to_owned(),
4244                    clearance: "field".to_owned(),
4245                    environment: BTreeMap::new(),
4246                    model: None,
4247                    effort: None,
4248                    max_cost_micro_usd: None,
4249                    project_settings: false,
4250                    project_mcp: false,
4251                    answer_only: false,
4252                    assistant: None,
4253                    overlays: Default::default(),
4254                    loadout: Default::default(),
4255                    ledger: None,
4256                },
4257                terminal.into_object(),
4258            )
4259            .unwrap();
4260        run.send_message(AgentMessage {
4261            text: SessionCommand::Clear.encode(),
4262        })
4263        .unwrap();
4264        assert!(written_texts(&writes).contains(&"first".to_owned()));
4265        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4266        let kinds = events.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>();
4267        assert_eq!(
4268            kinds,
4269            ["system", "completed", "cleared", "system", "completed"]
4270        );
4271        assert_eq!(
4272            SessionChange::of(&events[2]).unwrap().trigger.as_deref(),
4273            Some("clear")
4274        );
4275        assert_eq!(
4276            run.session_id().unwrap().as_deref(),
4277            Some("claude-session-43")
4278        );
4279    }
4280
4281    /// A resumed Run clears too: the new session id, which Claude Code reports after the reset the
4282    /// Station asked for, is the one the Run holds from then on, and no line of it is refused.
4283    #[test]
4284    fn a_resumed_run_clears_and_takes_the_new_session_id() {
4285        let stream = concat!(
4286            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-42\"}\n",
4287            "{\"type\":\"conversation_reset\",\"new_conversation_id\":\"conv-9\",\"trigger\":\"clear\",\"session_id\":\"claude-session-42\"}\n",
4288            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-43\"}\n",
4289            "{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"num_turns\":0,\"session_id\":\"claude-session-43\"}\n",
4290        );
4291        let (run, writes) = resumed_on(stream);
4292        run.send_message(AgentMessage {
4293            text: SessionCommand::Clear.encode(),
4294        })
4295        .unwrap();
4296        assert_eq!(written_texts(&writes), ["/clear".to_owned()]);
4297        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
4298        let kinds = events.iter().map(|e| e.kind.as_str()).collect::<Vec<_>>();
4299        assert_eq!(
4300            kinds,
4301            ["system", "cleared", "system", "completed"],
4302            "{events:?}"
4303        );
4304        assert_eq!(
4305            run.session_id().unwrap().as_deref(),
4306            Some("claude-session-43")
4307        );
4308    }
4309
4310    /// A session id that differs with no clear asked for is still the wrong Run.
4311    #[test]
4312    fn another_session_without_a_clear_is_still_refused() {
4313        let stream =
4314            "{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"claude-session-99\"}\n";
4315        let (run, _writes) = resumed_on(stream);
4316        let error = loop {
4317            match run.next_event(400) {
4318                Err(error) => break error,
4319                Ok(Some(_)) => {}
4320                Ok(None) => panic!("the wrong Run was not refused"),
4321            }
4322        };
4323        assert!(error.to_string().contains("different Run"), "{error}");
4324    }
4325
4326    #[test]
4327    fn a_command_form_that_is_not_a_command_is_refused_not_sent() {
4328        let (run, writes) = resumed_on("");
4329        let refused = run
4330            .send_message(AgentMessage {
4331                text: format!("{}{{\"command\":\"reboot\"}}", ai6::SESSION_COMMAND_PREFIX),
4332            })
4333            .unwrap_err();
4334        assert!(refused.to_string().contains("session command"), "{refused}");
4335        assert!(written_texts_now(&writes).is_empty());
4336    }
4337
4338    fn written_texts_now(writes: &Arc<Mutex<Vec<u8>>>) -> Vec<String> {
4339        let written = String::from_utf8(writes.lock().unwrap().clone()).unwrap();
4340        written
4341            .lines()
4342            .filter(|line| line.contains("\"user\""))
4343            .map(str::to_owned)
4344            .collect()
4345    }
4346
4347    #[test]
4348    fn the_handler_says_it_compacts_and_clears() {
4349        let handler = ClaudeHandler::try_from(ClaudeConfig::default()).unwrap();
4350        let commands = handler.session_commands().unwrap();
4351        assert!(commands.compact && commands.clear);
4352    }
4353
4354    #[test]
4355    fn a_restricted_run_that_calls_a_tool_is_ended() {
4356        let call = |tool: &str| {
4357            format!(
4358                "{{\"type\":\"assistant\",\"message\":{{\"content\":[{{\"type\":\"tool_use\",\
4359                 \"name\":\"{tool}\"}}]}}}}\n"
4360            )
4361        };
4362        for (answer_only, assistant, tool, ends) in [
4363            (true, None, "Bash", true),
4364            (true, None, "mcp__moneypenny__board", true),
4365            (
4366                false,
4367                Some(AssistantMode::moneypenny()),
4368                "mcp__moneypenny__board",
4369                false,
4370            ),
4371            (
4372                false,
4373                Some(AssistantMode::moneypenny()),
4374                "mcp__other__read",
4375                true,
4376            ),
4377            (false, None, "Bash", false),
4378        ] {
4379            let mut input =
4380                b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"s-1\"}\n".to_vec();
4381            input.extend_from_slice(call(tool).as_bytes());
4382            input.extend_from_slice(b"{\"type\":\"result\",\"result\":\"done\"}\n");
4383            let handler = ClaudeHandler::try_from(ClaudeConfig {
4384                executable: "claude-test".to_owned(),
4385                ..ClaudeConfig::default()
4386            })
4387            .unwrap();
4388            let run = handler
4389                .resume(
4390                    AgentResume {
4391                        clearance: "desk".to_owned(),
4392                        mission_id: "mission-42".parse().unwrap(),
4393                        run_id: RunId::try_new("s-1").unwrap(),
4394                        message: None,
4395                        working_directory: "C:\\station\\mission-42".to_owned(),
4396                        environment: assistant_environment(),
4397                        model: None,
4398                        effort: None,
4399                        max_cost_micro_usd: None,
4400                        project_settings: false,
4401                        project_mcp: false,
4402                        answer_only,
4403                        assistant,
4404                        initial_context: Vec::new(),
4405                        overlays: Default::default(),
4406                        loadout: Default::default(),
4407                    },
4408                    ResumeTerminal {
4409                        spec: Arc::new(Mutex::new(None)),
4410                        input,
4411                        writes: Arc::new(Mutex::new(Vec::new())),
4412                    }
4413                    .into_object(),
4414                )
4415                .unwrap();
4416            let kinds = std::iter::from_fn(|| run.next_event(400).unwrap())
4417                .map(|event| (event.kind, event.text))
4418                .collect::<Vec<_>>();
4419            if ends {
4420                assert_eq!(kinds.len(), 2, "{tool}: {kinds:?}");
4421                assert_eq!(kinds[1].0, "failed");
4422                let reason = kinds[1].1.as_deref().unwrap();
4423                assert!(reason.contains(tool), "{reason}");
4424            } else {
4425                assert_eq!(
4426                    kinds.last().map(|(kind, _)| kind.as_str()),
4427                    Some("completed"),
4428                    "{tool}: {kinds:?}"
4429                );
4430            }
4431        }
4432    }
4433
4434    #[test]
4435    fn resume_rejects_a_different_run_reported_by_claude() {
4436        let terminal = ResumeTerminal {
4437            spec: Arc::new(Mutex::new(None)),
4438            input: b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"different-run\"}\n"
4439                .to_vec(),
4440            writes: Arc::new(Mutex::new(Vec::new())),
4441        };
4442        let handler = ClaudeHandler::try_from(ClaudeConfig {
4443            executable: "claude-test".to_owned(),
4444            ..ClaudeConfig::default()
4445        })
4446        .unwrap();
4447        let run = handler
4448            .resume(
4449                AgentResume {
4450                    clearance: "field".to_owned(),
4451                    mission_id: "mission-42".parse().unwrap(),
4452                    run_id: RunId::try_new("claude-session-42").unwrap(),
4453                    message: None,
4454                    working_directory: "C:\\station\\mission-42".to_owned(),
4455                    environment: BTreeMap::new(),
4456                    model: None,
4457                    effort: None,
4458                    max_cost_micro_usd: None,
4459                    project_settings: false,
4460                    project_mcp: false,
4461                    answer_only: false,
4462                    assistant: None,
4463                    initial_context: Vec::new(),
4464                    overlays: Default::default(),
4465                    loadout: Default::default(),
4466                },
4467                terminal.into_object(),
4468            )
4469            .unwrap();
4470        let error = match run.next_event(400) {
4471            Ok(event) => panic!("a different provider ID was read as {event:?}"),
4472            Err(error) => error.to_string(),
4473        };
4474        assert!(error.contains("different Run"), "{error}");
4475        assert_eq!(run.session_id().unwrap().as_deref(), Some("different-run"));
4476    }
4477
4478    /// Claude Code with stream-json input writes nothing until it has read a message, so a
4479    /// resume that waited for its output before sending one would never see any.
4480    #[test]
4481    fn resume_sends_its_message_at_once_to_a_harness_silent_until_it_reads_input() {
4482        let terminal = ProcessTerminal::new();
4483        let handler = ClaudeHandler::try_from(ClaudeConfig {
4484            executable: "claude-silent-fixture".to_owned(),
4485            ..ClaudeConfig::default()
4486        })
4487        .unwrap();
4488        let resumed = handler
4489            .resume(
4490                AgentResume {
4491                    clearance: "field".to_owned(),
4492                    mission_id: "mission-silent".parse().unwrap(),
4493                    run_id: RunId::try_new("claude-silent-run").unwrap(),
4494                    message: Some("are you there?".to_owned()),
4495                    working_directory: std::env::current_dir()
4496                        .unwrap()
4497                        .to_string_lossy()
4498                        .into_owned(),
4499                    environment: BTreeMap::from([(
4500                        "CLAUDE_FIXTURE_RUN_ID".to_owned(),
4501                        "claude-silent-run".to_owned(),
4502                    )]),
4503                    model: None,
4504                    effort: None,
4505                    max_cost_micro_usd: None,
4506                    project_settings: false,
4507                    project_mcp: false,
4508                    answer_only: false,
4509                    assistant: None,
4510                    initial_context: Vec::new(),
4511                    overlays: Default::default(),
4512                    loadout: Default::default(),
4513                },
4514                terminal.into_object(),
4515            )
4516            .unwrap();
4517        // Completing at all shows it sent the message before waiting for output.
4518        let events = read_to_completion(&resumed);
4519        assert!(events.iter().any(|event| {
4520            event.kind == "completed" && event.text.as_deref() == Some("are you there?")
4521        }));
4522        assert_eq!(
4523            resumed.session_id().unwrap().as_deref(),
4524            Some("claude-silent-run")
4525        );
4526        resumed.close().unwrap();
4527    }
4528
4529    #[test]
4530    fn a_message_with_images_reaches_claude_as_image_blocks_before_its_text() {
4531        let message = ai6::MessageContent {
4532            text: "What is wrong here?".to_owned(),
4533            images: vec![ai6::MessageImage {
4534                media_type: "image/png".to_owned(),
4535                data: "iVBORw0KGgo=".to_owned(),
4536            }],
4537        }
4538        .encode();
4539        assert_eq!(
4540            user_input(&message),
4541            serde_json::json!({
4542                "type": "user",
4543                "message": {
4544                    "role": "user",
4545                    "content": [
4546                        {"type": "image", "source": {"type": "base64",
4547                            "media_type": "image/png", "data": "iVBORw0KGgo="}},
4548                        {"type": "text", "text": "What is wrong here?"}
4549                    ]
4550                }
4551            })
4552        );
4553        assert_eq!(
4554            ClaudeHandler::try_from(ClaudeConfig::default())
4555                .unwrap()
4556                .image_input()
4557                .unwrap(),
4558            None
4559        );
4560    }
4561
4562    #[test]
4563    fn input_fixture_keeps_the_provider_stream_json_message_shape() {
4564        let encoded = user_input("continue the Mission");
4565        assert_eq!(
4566            encoded,
4567            serde_json::json!({
4568                "type": "user",
4569                "message": {
4570                    "role": "user",
4571                    "content": [{ "type": "text", "text": "continue the Mission" }]
4572                }
4573            })
4574        );
4575    }
4576
4577    #[test]
4578    fn result_fixture_maps_to_a_completed_event() {
4579        let value = serde_json::json!({
4580            "type": "result",
4581            "session_id": "claude-session-7",
4582            "result": "Mission work finished"
4583        });
4584        let event = decoded(&value, br#"{"type":"result"}"#.to_vec()).unwrap();
4585        assert_eq!(event.kind, "completed");
4586        assert_eq!(event.text.as_deref(), Some("Mission work finished"));
4587        assert_eq!(value["session_id"], "claude-session-7");
4588    }
4589
4590    #[test]
4591    fn a_rejected_rate_limit_event_becomes_a_limit_with_its_reset_time() {
4592        let value = json!({
4593            "type": "rate_limit_event",
4594            "session_id": "claude-session-7",
4595            "rate_limit_info": {
4596                "status": "rejected",
4597                "resetsAt": 1_790_000_000,
4598                "rateLimitType": "five_hour"
4599            }
4600        });
4601        let event = decoded(&value, b"{}".to_vec()).unwrap();
4602        assert_eq!(event.kind, LIMIT_EVENT);
4603        let limit = event.limit.expect("a limit");
4604        assert_eq!(limit.resets_at, Some(1_790_000_000));
4605        assert_eq!(limit.bucket.as_deref(), Some("five_hour"));
4606        assert_eq!(limit.kind, Some(LimitKind::UsageQuota));
4607        assert_eq!(limit.continuable, Some(true));
4608        assert!(limit.can_continue());
4609    }
4610
4611    #[test]
4612    fn a_limit_carries_the_kind_claude_code_names_or_its_words_say() {
4613        let overage = json!({
4614            "type": "rate_limit_event",
4615            "rate_limit_info": { "status": "rejected", "rateLimitType": "overage" }
4616        });
4617        let limit = decoded(&overage, b"{}".to_vec()).unwrap().limit.unwrap();
4618        assert_eq!(limit.kind, Some(LimitKind::Credit));
4619        assert_eq!(limit.continuable, Some(true));
4620
4621        let result = |text: &str, status: Option<i64>| {
4622            let mut value = json!({ "type": "result", "is_error": true, "result": text });
4623            if let Some(status) = status {
4624                value["api_error_status"] = json!(status);
4625            }
4626            decoded(&value, b"{}".to_vec()).unwrap().limit.unwrap()
4627        };
4628        let quota = result("Claude AI usage limit reached|1790000000", None);
4629        assert_eq!(quota.kind, Some(LimitKind::UsageQuota));
4630        assert_eq!(quota.continuable, Some(true));
4631        assert_eq!(quota.resets_at, Some(1_790_000_000));
4632        let rate = result("API Error: Request rejected (429)", Some(429));
4633        assert_eq!(rate.kind, Some(LimitKind::RateLimit));
4634        assert!(rate.can_continue());
4635        let window = result(
4636            "API Error: 429 prompt is too long for the context window",
4637            Some(429),
4638        );
4639        assert_eq!(window.kind, Some(LimitKind::ContextWindow));
4640        assert_eq!(window.continuable, Some(false));
4641        assert!(!window.can_continue());
4642    }
4643
4644    #[test]
4645    fn every_rate_limit_event_reports_its_window_as_quota() {
4646        let rejected = json!({
4647            "type": "rate_limit_event",
4648            "session_id": "claude-session-7",
4649            "rate_limit_info": {
4650                "status": "rejected",
4651                "resetsAt": 1_790_000_000,
4652                "rateLimitType": "five_hour"
4653            }
4654        });
4655        let rejected = quota_of(&rejected);
4656        assert_eq!(rejected[0].id, "five_hour");
4657        assert_eq!(UsageReport::fraction_permille(&rejected[0]), None);
4658        assert_eq!(rejected[0].status, BucketStatus::Exhausted);
4659        assert_eq!(
4660            rejected[0].refill,
4661            Refill::FixedWindow {
4662                length: None,
4663                resets_at: Some(1_790_000_000)
4664            }
4665        );
4666        let warning = json!({
4667            "type": "rate_limit_event",
4668            "rate_limit_info": { "status": "allowed_warning", "resetsAt": 1_790_000_000 }
4669        });
4670        let quota = quota_of(&warning);
4671        assert_eq!(quota[0].id, "unknown");
4672        assert_eq!(quota[0].status, BucketStatus::Warning);
4673        // `utilization` is in the SDK's published SDKRateLimitInfo type; only a fraction is
4674        // taken, since its scale is not documented there.
4675        let measured = json!({
4676            "type": "rate_limit_event",
4677            "rate_limit_info": {
4678                "status": "allowed",
4679                "rateLimitType": "seven_day",
4680                "utilization": 0.25
4681            }
4682        });
4683        assert_eq!(
4684            UsageReport::fraction_permille(&quota_of(&measured)[0]),
4685            Some(250)
4686        );
4687        let percent = json!({
4688            "type": "rate_limit_event",
4689            "rate_limit_info": { "status": "allowed", "utilization": 25 }
4690        });
4691        assert_eq!(UsageReport::fraction_permille(&quota_of(&percent)[0]), None);
4692        let result = json!({ "type": "result", "result": "done" });
4693        assert!(quota_of(&result).is_empty());
4694    }
4695
4696    fn quota_of(value: &Value) -> Vec<Bucket> {
4697        decoded(value, b"{}".to_vec())
4698            .unwrap()
4699            .report
4700            .map(|report| report.buckets)
4701            .unwrap_or_default()
4702    }
4703
4704    fn spend_of(value: &Value) -> Option<Spend> {
4705        decoded(value, b"{}".to_vec())?.report?.spend
4706    }
4707
4708    #[test]
4709    fn an_allowed_rate_limit_event_is_not_a_limit() {
4710        let value = json!({
4711            "type": "rate_limit_event",
4712            "rate_limit_info": { "status": "allowed_warning", "resetsAt": 1_790_000_000 }
4713        });
4714        let event = decoded(&value, b"{}".to_vec()).unwrap();
4715        assert_eq!(event.kind, "rate_limit_event");
4716        assert_eq!(event.limit, None);
4717    }
4718
4719    #[test]
4720    fn a_usage_limit_result_carries_the_reset_time_after_the_pipe() {
4721        for (reset, expected) in [
4722            ("1790000000", 1_790_000_000),
4723            ("1790000000000", 1_790_000_000),
4724        ] {
4725            let value = json!({
4726                "type": "result",
4727                "is_error": true,
4728                "result": format!("Claude AI usage limit reached|{reset}")
4729            });
4730            let event = decoded(&value, b"{}".to_vec()).unwrap();
4731            assert_eq!(
4732                event.kind, LIMIT_EVENT,
4733                "not completed: the Run did not finish"
4734            );
4735            assert_eq!(event.limit.unwrap().resets_at, Some(expected));
4736            assert!(event.text.unwrap().contains("usage limit reached"));
4737        }
4738    }
4739
4740    #[test]
4741    fn a_limit_without_a_parsable_reset_time_still_parks_the_run() {
4742        let value = json!({
4743            "type": "result",
4744            "is_error": true,
4745            "result": "5-hour limit reached \u{2219} resets 3pm"
4746        });
4747        let limit = decoded(&value, b"{}".to_vec()).unwrap().limit.unwrap();
4748        assert_eq!(limit.resets_at, None);
4749        assert_eq!(limit.bucket.as_deref(), Some("five_hour"));
4750    }
4751
4752    /// As Claude Code 2.1.316 reports a 429 from a LiteLLM gateway, past its retries.
4753    #[test]
4754    fn a_gateway_refusing_for_quota_is_a_limit_with_no_reset_time() {
4755        let (limit, text) = decode_limit(&serde_json::json!({
4756            "type": "result",
4757            "subtype": "success",
4758            "is_error": true,
4759            "api_error_status": 429,
4760            "terminal_reason": "api_error",
4761            "result": "API Error: Request rejected (429) · litellm.RateLimitError: GeminiException \
4762                       - quota exceeded. Received Model Group=gemini-free",
4763        }))
4764        .expect("a limit");
4765        assert_eq!(limit.resets_at, None);
4766        assert_eq!(limit.retry_after, None);
4767        assert!(text.unwrap().contains("Request rejected (429)"));
4768        assert!(
4769            decode_limit(&serde_json::json!({
4770                "type": "result",
4771                "is_error": true,
4772                "api_error_status": 500,
4773                "result": "API Error: 500 upstream",
4774            }))
4775            .is_none(),
4776            "another status is no limit"
4777        );
4778    }
4779
4780    /// Claude Code reports each retry of a gateway's refusal as `system`/`api_retry`; a token-cap
4781    /// refusal ends the turn at the first one, and a transient error is left to its retries.
4782    #[test]
4783    fn a_token_cap_refusal_in_a_retry_fails_the_turn_once_with_the_gateways_words() {
4784        let words = "400 Request rejected: Current cap is 300000 tokens";
4785        let capped = json!({
4786            "type": "system",
4787            "subtype": "api_retry",
4788            "attempt": 10,
4789            "max_retries": 300,
4790            "error_status": 400,
4791            "error": words,
4792        });
4793        let event = decoded(&capped, b"{}".to_vec()).unwrap();
4794        assert_eq!(event.kind, "failed");
4795        assert_eq!(event.text.as_deref(), Some(words));
4796
4797        let transient = json!({
4798            "type": "system",
4799            "subtype": "api_retry",
4800            "attempt": 1,
4801            "max_retries": 300,
4802            "error_status": 529,
4803            "error": "overloaded",
4804        });
4805        assert_eq!(decoded(&transient, b"{}".to_vec()).unwrap().kind, "system");
4806    }
4807
4808    #[test]
4809    fn an_ordinary_error_result_is_not_mistaken_for_a_limit() {
4810        let value = json!({
4811            "type": "result",
4812            "is_error": true,
4813            "result": "Tool call failed"
4814        });
4815        let event = decoded(&value, b"{}".to_vec()).unwrap();
4816        assert_eq!(event.kind, "failed");
4817        assert_eq!(event.text.as_deref(), Some("Tool call failed"));
4818        assert_eq!(event.limit, None);
4819    }
4820
4821    /// As Claude Code 2.1.316 writes them. One that never logged in reaches no model and still
4822    /// says `success`; an interrupted turn has no `result` at all, only `errors`.
4823    #[test]
4824    fn a_result_reporting_an_error_does_not_complete_the_turn() {
4825        let not_logged_in = json!({
4826            "type": "result",
4827            "subtype": "success",
4828            "is_error": true,
4829            "result": "Not logged in \u{b7} Please run /login",
4830            "stop_reason": "stop_sequence",
4831            "terminal_reason": "api_error",
4832            "session_id": "c75d9e6e-f5fe-45d2-b05d-f2c88f0d132b",
4833            "total_cost_usd": 0,
4834        });
4835        let event = decoded(&not_logged_in, b"{}".to_vec()).unwrap();
4836        assert_eq!(event.kind, "failed");
4837        assert_eq!(
4838            event.text.as_deref(),
4839            Some("Not logged in \u{b7} Please run /login")
4840        );
4841
4842        let interrupted = json!({
4843            "type": "result",
4844            "subtype": "error_during_execution",
4845            "is_error": true,
4846            "result": null,
4847            "errors": ["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=null"],
4848            "terminal_reason": "aborted_streaming",
4849            "stop_reason": null,
4850            "session_id": "b46e80da-b2eb-4336-b717-a18df95b965b",
4851        });
4852        let event = decoded(&interrupted, b"{}".to_vec()).unwrap();
4853        assert_eq!(event.kind, "failed");
4854        assert!(event.text.unwrap().contains("ede_diagnostic"));
4855
4856        let done =
4857            json!({"type": "result", "subtype": "success", "is_error": false, "result": "ok"});
4858        assert_eq!(decoded(&done, b"{}".to_vec()).unwrap().kind, "completed");
4859    }
4860
4861    /// A harness that exits while its terminal keeps the output open (ConPTY) ends the Run
4862    /// with one `failed` event naming its exit code and quoting what it wrote last.
4863    #[test]
4864    fn a_harness_that_exits_early_fails_the_run_with_its_status_and_last_output() {
4865        let terminal = ProcessTerminal::kept_open();
4866        let handler = ClaudeHandler::try_from(ClaudeConfig {
4867            executable: "claude-exit-fixture".to_owned(),
4868            ..ClaudeConfig::default()
4869        })
4870        .unwrap();
4871        let run = handler
4872            .start(
4873                AgentStart {
4874                    mission_id: "mission-exit".parse().unwrap(),
4875                    agent_id: "007".to_owned(),
4876                    prompt: "hello".to_owned(),
4877                    initial_context: Vec::new(),
4878                    working_directory: std::env::current_dir()
4879                        .unwrap()
4880                        .to_string_lossy()
4881                        .into_owned(),
4882                    clearance: "field".to_owned(),
4883                    environment: BTreeMap::from([(
4884                        "CLAUDE_FIXTURE_EXIT".to_owned(),
4885                        "3".to_owned(),
4886                    )]),
4887                    model: None,
4888                    effort: None,
4889                    max_cost_micro_usd: None,
4890                    project_settings: false,
4891                    project_mcp: false,
4892                    answer_only: false,
4893                    assistant: None,
4894                    overlays: Default::default(),
4895                    loadout: Default::default(),
4896                    ledger: None,
4897                },
4898                terminal.into_object(),
4899            )
4900            .unwrap();
4901        let deadline = Instant::now() + Duration::from_secs(10);
4902        let failed = loop {
4903            assert!(Instant::now() < deadline, "the exit was never noticed");
4904            if let Some(event) = run.next_event(100).unwrap()
4905                && event.kind == "failed"
4906            {
4907                break event;
4908            }
4909        };
4910        let reason = failed.text.unwrap();
4911        assert!(reason.contains("exited with code 3"), "{reason}");
4912        assert!(
4913            reason.contains("Error: the stored login has expired"),
4914            "{reason}"
4915        );
4916        assert_eq!(run.next_event(100).unwrap(), None, "reported once");
4917        run.close().unwrap();
4918    }
4919
4920    #[test]
4921    fn terminal_eof_emits_one_failed_event_instead_of_polling_forever() {
4922        let run = open_on(EofTerminal, None);
4923
4924        let event = run.next_event(2_000).unwrap().unwrap();
4925        assert_eq!(event.kind, "failed");
4926        assert_eq!(run.next_event(100).unwrap(), None);
4927    }
4928
4929    #[test]
4930    fn cable_mcp_config_uses_environment_placeholders_for_auth() {
4931        let environment = BTreeMap::from([
4932            (
4933                "AI6_CABLE_MCP_URL".to_owned(),
4934                "http://127.0.0.1:43210/mcp".to_owned(),
4935            ),
4936            (
4937                "AI6_CABLE_MCP_TOKEN".to_owned(),
4938                "run-secret-token".to_owned(),
4939            ),
4940        ]);
4941        let mut argv = vec!["claude".to_owned()];
4942
4943        add_mcp(&mut argv, &environment);
4944
4945        let position = |flag: &str| argv.iter().position(|argument| argument == flag).unwrap();
4946        let config = &argv[position("--mcp-config") + 1];
4947        assert!(config.contains("${AI6_CABLE_MCP_URL}"));
4948        assert!(config.contains("${AI6_CABLE_MCP_TOKEN}"));
4949        assert!(!config.contains("run-secret-token"));
4950    }
4951
4952    #[test]
4953    fn the_theater_tools_get_the_clients_timeout_the_station_names() {
4954        let mut environment = BTreeMap::from([
4955            ("AI6_THEATER_MCP_URL".to_owned(), "http://b/mcp".to_owned()),
4956            ("AI6_THEATER_MCP_TOKEN".to_owned(), "b".to_owned()),
4957            (
4958                "AI6_THEATER_MCP_TIMEOUT_MS".to_owned(),
4959                "3630000".to_owned(),
4960            ),
4961        ]);
4962        let harness = harness_environment(&environment, false, None);
4963        assert_eq!(harness["MCP_TOOL_TIMEOUT"], "3630000");
4964        environment.insert("MCP_TOOL_TIMEOUT".to_owned(), "5000".to_owned());
4965        assert_eq!(
4966            harness_environment(&environment, false, None)["MCP_TOOL_TIMEOUT"],
4967            "5000",
4968            "the Agent's own setting stands"
4969        );
4970    }
4971
4972    #[test]
4973    fn no_theater_tools_leave_the_clients_timeout_alone() {
4974        let cables = BTreeMap::from([
4975            ("AI6_CABLE_MCP_URL".to_owned(), "http://a/mcp".to_owned()),
4976            ("AI6_CABLE_MCP_TOKEN".to_owned(), "a".to_owned()),
4977        ]);
4978        assert!(!harness_environment(&cables, false, None).contains_key("MCP_TOOL_TIMEOUT"));
4979        let stray = BTreeMap::from([("AI6_THEATER_MCP_TIMEOUT_MS".to_owned(), "1".to_owned())]);
4980        assert!(!harness_environment(&stray, false, None).contains_key("MCP_TOOL_TIMEOUT"));
4981    }
4982
4983    #[test]
4984    fn a_run_with_both_servers_allows_exactly_their_tools() {
4985        let environment = BTreeMap::from([
4986            ("AI6_CABLE_MCP_URL".to_owned(), "http://a/mcp".to_owned()),
4987            ("AI6_CABLE_MCP_TOKEN".to_owned(), "a".to_owned()),
4988            ("AI6_THEATER_MCP_URL".to_owned(), "http://b/mcp".to_owned()),
4989            ("AI6_THEATER_MCP_TOKEN".to_owned(), "b".to_owned()),
4990        ]);
4991        let mut argv = vec!["claude".to_owned()];
4992        add_field_tools(&mut argv, &environment, &ClaudeSettings::default(), true);
4993        let allowed = argv
4994            .iter()
4995            .position(|argument| argument == "--allowedTools")
4996            .unwrap();
4997        // Under dontAsk a tool no rule allows is denied, and an MCP tool is no exception. No
4998        // other server is named, so another server's tools stay denied.
4999        let rules: Vec<&str> = argv[allowed + 1].split(',').collect();
5000        assert_eq!(&rules[..2], ["mcp__ai6-cables", "mcp__ai6-theater"]);
5001        assert_eq!(
5002            rules
5003                .iter()
5004                .filter(|rule| rule.starts_with("mcp__"))
5005                .count(),
5006            2
5007        );
5008        assert_eq!(
5009            argv.iter()
5010                .filter(|argument| *argument == "--allowedTools")
5011                .count(),
5012            1
5013        );
5014    }
5015
5016    #[test]
5017    fn a_run_without_ai6_servers_allows_no_server() {
5018        let mut argv = vec!["claude".to_owned()];
5019        add_mcp(&mut argv, &BTreeMap::new());
5020        assert_eq!(argv, ["claude"]);
5021        add_field_tools(
5022            &mut argv,
5023            &BTreeMap::new(),
5024            &ClaudeSettings::default(),
5025            true,
5026        );
5027        assert!(!argv.iter().any(|argument| argument.contains("mcp__")));
5028    }
5029
5030    #[test]
5031    fn a_trial_denies_web_tools_whatever_the_agent_allows() {
5032        let environment = BTreeMap::from([(TRIAL_MAX_TURNS_ENV.to_owned(), "2".to_owned())]);
5033        let settings = ClaudeSettings {
5034            allowed_tools: vec![
5035                "WebFetch".to_owned(),
5036                "WebSearch(domain:example.test)".to_owned(),
5037            ],
5038            denied_tools: Vec::new(),
5039        };
5040        let mut argv = vec!["claude".to_owned()];
5041        add_field_tools(&mut argv, &environment, &settings, true);
5042        let after = |flag: &str| {
5043            let at = argv.iter().position(|argument| argument == flag).unwrap();
5044            argv[at + 1]
5045                .split(',')
5046                .map(str::to_owned)
5047                .collect::<Vec<_>>()
5048        };
5049        for tool in TRIAL_DENIED {
5050            assert!(after("--disallowedTools").iter().any(|name| name == tool));
5051            assert!(!after("--tools").iter().any(|name| name == tool));
5052        }
5053        assert!(
5054            !after("--allowedTools")
5055                .iter()
5056                .any(|rule| rule.starts_with("Web"))
5057        );
5058        let harness = harness_environment(&environment, false, None);
5059        assert_eq!(
5060            harness.get(DISABLE_WEB_FETCH_ENV).map(String::as_str),
5061            Some("1")
5062        );
5063        let plain = harness_environment(&BTreeMap::new(), false, None);
5064        assert_eq!(plain.get(DISABLE_WEB_FETCH_ENV), None);
5065    }
5066
5067    #[test]
5068    fn remote_hands_turns_off_claudes_own_tools_and_adds_the_theater_server() {
5069        let environment = BTreeMap::from([
5070            (
5071                "AI6_THEATER_MCP_URL".to_owned(),
5072                "http://127.0.0.1:43211/mcp".to_owned(),
5073            ),
5074            (
5075                "AI6_THEATER_MCP_TOKEN".to_owned(),
5076                "theater-secret-token".to_owned(),
5077            ),
5078        ]);
5079        let mut argv = vec!["claude".to_owned()];
5080        let settings = ClaudeSettings {
5081            allowed_tools: vec!["Bash".to_owned(), "Edit(/src/**)".to_owned()],
5082            denied_tools: Vec::new(),
5083        };
5084
5085        add_field_tools(&mut argv, &environment, &settings, true);
5086        add_mcp(&mut argv, &environment);
5087
5088        let position = |flag: &str| argv.iter().position(|argument| argument == flag).unwrap();
5089        let disallowed = &argv[position("--disallowedTools") + 1];
5090        for tool in ["Bash", "Edit", "Write", "Read", "Grep"] {
5091            assert!(disallowed.split(',').any(|name| name == tool), "{tool}");
5092        }
5093        let offered = &argv[position("--tools") + 1];
5094        for tool in OWN_TOOLS {
5095            assert!(!offered.split(',').any(|name| name == tool), "{offered}");
5096        }
5097        // A setting's rule goes on the list, and the deny rule beats it.
5098        let allowed = &argv[position("--allowedTools") + 1];
5099        assert_eq!(
5100            allowed,
5101            "mcp__ai6-theater,TodoWrite,TaskCreate,TaskGet,TaskList,TaskUpdate,Bash,Edit(/src/**)"
5102        );
5103        let config = &argv[position("--mcp-config") + 1];
5104        assert!(config.contains("ai6-theater") && !config.contains("ai6-cables"));
5105        assert!(config.contains("${AI6_THEATER_MCP_TOKEN}"));
5106        assert!(
5107            !argv
5108                .iter()
5109                .any(|argument| argument.contains("theater-secret-token"))
5110        );
5111        // A variadic flag is closed by the next flag, so no value runs on into another.
5112        assert!(position("--tools") < position("--permission-mode"));
5113        assert!(position("--disallowedTools") < position("--allowedTools"));
5114        assert!(position("--allowedTools") < position("--mcp-config"));
5115    }
5116
5117    #[test]
5118    fn a_taken_over_run_keeps_its_shell_for_the_hook_and_loads_the_stations_plugin() {
5119        let environment = BTreeMap::from([
5120            ("AI6_THEATER_MCP_URL".to_owned(), "http://b/mcp".to_owned()),
5121            ("AI6_THEATER_MCP_TOKEN".to_owned(), "b".to_owned()),
5122            (
5123                "AI6_THEATER_PLUGIN_DIR".to_owned(),
5124                "/run/ai6/plugin".to_owned(),
5125            ),
5126        ]);
5127        let mut argv = Vec::new();
5128        add_field_tools(&mut argv, &environment, &ClaudeSettings::default(), true);
5129        add_mcp(&mut argv, &environment);
5130        let (offered, denied, allowed) = field_flags(&argv);
5131        let names = |list: &str| list.split(',').map(str::to_owned).collect::<Vec<_>>();
5132        for shell in ["Bash", "PowerShell"] {
5133            assert!(names(&offered).contains(&shell.to_owned()), "{offered}");
5134            assert!(!names(&denied).contains(&shell.to_owned()), "{denied}");
5135        }
5136        for file in ["Edit", "Write", "NotebookEdit", "Read", "Glob", "Grep"] {
5137            assert!(!names(&offered).contains(&file.to_owned()), "{offered}");
5138            assert!(names(&denied).contains(&file.to_owned()), "{denied}");
5139        }
5140        assert!(names(&allowed).contains(&"Bash".to_owned()), "{allowed}");
5141        assert!(
5142            argv.iter()
5143                .any(|argument| argument == "--plugin-dir=/run/ai6/plugin"),
5144            "{argv:?}"
5145        );
5146        // Without the plugin, the shell stays off: nothing would turn it to the Theater.
5147        let mut argv = Vec::new();
5148        let mut plain = environment.clone();
5149        plain.remove("AI6_THEATER_PLUGIN_DIR");
5150        add_field_tools(&mut argv, &plain, &ClaudeSettings::default(), true);
5151        add_mcp(&mut argv, &plain);
5152        let (offered, denied, _) = field_flags(&argv);
5153        assert!(!names(&offered).contains(&"Bash".to_owned()), "{offered}");
5154        assert!(names(&denied).contains(&"Bash".to_owned()), "{denied}");
5155        assert!(
5156            !argv
5157                .iter()
5158                .any(|argument| argument.starts_with("--plugin-dir"))
5159        );
5160    }
5161
5162    /// What a field Run's tool flags say, as `(offered, denied, allowed)`, after a start.
5163    fn field_flags(argv: &[String]) -> (String, String, String) {
5164        assert_eq!(flag(argv, "--permission-mode").as_deref(), Some("dontAsk"));
5165        (
5166            flag(argv, "--tools").unwrap(),
5167            flag(argv, "--disallowedTools").unwrap(),
5168            flag(argv, "--allowedTools").unwrap(),
5169        )
5170    }
5171
5172    const DEFAULT_OFFERED: &str = "Read,Glob,Grep,Edit,Write,NotebookEdit,Bash,PowerShell,\
5173                                   TodoWrite,TaskCreate,TaskGet,TaskList,TaskUpdate";
5174    const DEFAULT_ALLOWED: &str = "Read,Glob,Grep,Edit(/**),Bash,PowerShell,\
5175                                   TodoWrite,TaskCreate,TaskGet,TaskList,TaskUpdate";
5176
5177    #[test]
5178    fn a_field_run_runs_by_the_explicit_list_on_start_and_resume() {
5179        let mut environment = cable_environment();
5180        environment.insert(
5181            "CLAUDE_FIXTURE_RUN_ID".to_owned(),
5182            "claude-field-run".to_owned(),
5183        );
5184        let terminal = ProcessTerminal::new();
5185        let handler = ClaudeHandler::try_from(ClaudeConfig {
5186            executable: "claude-field-fixture".to_owned(),
5187            ..ClaudeConfig::default()
5188        })
5189        .unwrap();
5190        let working_directory = std::env::current_dir()
5191            .unwrap()
5192            .to_string_lossy()
5193            .into_owned();
5194        let started = handler
5195            .start(
5196                AgentStart {
5197                    mission_id: "mission-field".parse().unwrap(),
5198                    agent_id: "007".to_owned(),
5199                    prompt: "work".to_owned(),
5200                    initial_context: Vec::new(),
5201                    working_directory: working_directory.clone(),
5202                    clearance: "field".to_owned(),
5203                    environment: environment.clone(),
5204                    model: None,
5205                    effort: None,
5206                    max_cost_micro_usd: None,
5207                    project_settings: false,
5208                    project_mcp: false,
5209                    answer_only: false,
5210                    assistant: None,
5211                    overlays: Default::default(),
5212                    loadout: Default::default(),
5213                    ledger: None,
5214                },
5215                terminal.clone().into_object(),
5216            )
5217            .unwrap();
5218        read_to_completion(&started);
5219        started.close().unwrap();
5220        let resumed = handler
5221            .resume(
5222                AgentResume {
5223                    clearance: "field".to_owned(),
5224                    mission_id: "mission-field".parse().unwrap(),
5225                    run_id: RunId::try_new("claude-field-run").unwrap(),
5226                    message: None,
5227                    working_directory,
5228                    environment,
5229                    model: None,
5230                    effort: None,
5231                    max_cost_micro_usd: None,
5232                    project_settings: false,
5233                    project_mcp: false,
5234                    answer_only: false,
5235                    assistant: None,
5236                    initial_context: Vec::new(),
5237                    overlays: Default::default(),
5238                    loadout: Default::default(),
5239                },
5240                terminal.clone().into_object(),
5241            )
5242            .unwrap();
5243        resumed.close().unwrap();
5244        let specs = terminal.specs.lock().unwrap();
5245        for spec in specs.iter() {
5246            let (offered, denied, allowed) = field_flags(&spec.argv);
5247            assert_eq!(offered, DEFAULT_OFFERED);
5248            assert_eq!(denied, "WebFetch,WebSearch,Agent");
5249            assert_eq!(allowed, format!("mcp__ai6-cables,{DEFAULT_ALLOWED}"));
5250            // A gated Run keeps the same list: the gate decides each command.
5251            let settings = settings_of(&spec.argv).expect("the gate");
5252            let hook = &settings["hooks"]["PreToolUse"][0];
5253            assert_eq!(hook["matcher"], "Bash|PowerShell");
5254        }
5255        assert_eq!(specs.len(), 2);
5256    }
5257
5258    #[test]
5259    fn a_field_run_without_a_station_keeps_the_list_and_has_no_gate() {
5260        let mut argv = Vec::new();
5261        add_settings(
5262            &mut argv,
5263            &BTreeMap::new(),
5264            "wd",
5265            Mode {
5266                project_settings: false,
5267                project_mcp: false,
5268                answer_only: false,
5269                commands: true,
5270                reads_only: false,
5271            },
5272            &ClaudeSettings::default(),
5273            None,
5274            &RunOverlays::default(),
5275        )
5276        .unwrap();
5277        let (offered, _, allowed) = field_flags(&argv);
5278        assert_eq!(offered, DEFAULT_OFFERED);
5279        assert_eq!(allowed, DEFAULT_ALLOWED);
5280        assert!(!argv.iter().any(|argument| argument == "--settings"));
5281    }
5282
5283    /// A configuration read from TOML text, as the Station reads a record's settings.
5284    fn read_config(text: &str) -> Result<ClaudeConfig, String> {
5285        let table: toml::Table = toml::from_str(text).map_err(|error| error.to_string())?;
5286        let value = ai6::provider_settings::table_value(&table)?;
5287        ClaudeConfig::from_value(&value).map_err(|error| error.to_string())
5288    }
5289
5290    fn config(text: &str) -> ClaudeConfig {
5291        read_config(text).expect("the settings are valid")
5292    }
5293
5294    #[test]
5295    fn an_agents_settings_change_the_list_and_a_tool_they_add_is_offered() {
5296        let handler = ClaudeHandler::try_from(config(
5297            "allowed_tools = [\"WebFetch(domain:example.com)\", \"Skill\", \"mcp__docs\"]
5298denied_tools = [\"Bash(rm *)\"]
5299",
5300        ))
5301        .unwrap();
5302        let mut argv = Vec::new();
5303        add_field_tools(&mut argv, &BTreeMap::new(), &handler.settings, true);
5304        let (offered, denied, allowed) = field_flags(&argv);
5305        assert_eq!(offered, format!("{DEFAULT_OFFERED},WebFetch,Skill"));
5306        assert_eq!(
5307            denied, "WebSearch,Agent,Bash(rm *)",
5308            "the rule lifts its denial"
5309        );
5310        assert_eq!(
5311            allowed,
5312            format!("{DEFAULT_ALLOWED},WebFetch(domain:example.com),Skill,mcp__docs")
5313        );
5314        assert_eq!(
5315            handler.weakenings().unwrap(),
5316            [
5317                "allowed_tools adds WebFetch(domain:example.com) to what its field Runs may call",
5318                "allowed_tools adds Skill to what its field Runs may call",
5319                "allowed_tools adds mcp__docs to what its field Runs may call",
5320            ]
5321        );
5322    }
5323
5324    #[test]
5325    fn only_a_rule_beyond_the_default_list_weakens_a_run() {
5326        let weakenings = |text: &str| {
5327            ClaudeHandler::try_from(config(text))
5328                .unwrap()
5329                .weakenings()
5330                .unwrap()
5331        };
5332        assert!(weakenings("").is_empty());
5333        assert!(weakenings("denied_tools = [\"Bash\", \"Read\"]").is_empty());
5334        assert!(weakenings("allowed_tools = [\"Read\", \"Edit(/**)\"]").is_empty());
5335        assert!(
5336            weakenings("allowed_tools = [\"WebFetch\"]\ndenied_tools = [\"WebFetch\"]").is_empty(),
5337            "a deny rule beats the allow rule"
5338        );
5339        assert_eq!(
5340            weakenings("allowed_tools = [\"Write\"]").len(),
5341            1,
5342            "a bare Write reaches outside the working directory"
5343        );
5344    }
5345
5346    const DESK_OFFERED: &str = "Read,Glob,Grep,Edit,Write,NotebookEdit,\
5347                                TodoWrite,TaskCreate,TaskGet,TaskList,TaskUpdate";
5348    const DESK_ALLOWED: &str = "Read,Glob,Grep,Edit(/**),\
5349                                TodoWrite,TaskCreate,TaskGet,TaskList,TaskUpdate";
5350
5351    /// The tool flags of a start, then a resume, at `clearance` under `text`.
5352    fn flags_at(clearance: &str, text: &str) -> Vec<(String, String, String)> {
5353        let mut environment = cable_environment();
5354        environment.insert(
5355            "CLAUDE_FIXTURE_RUN_ID".to_owned(),
5356            "claude-clearance-run".to_owned(),
5357        );
5358        let terminal = ProcessTerminal::new();
5359        let handler = ClaudeHandler::try_from(ClaudeConfig {
5360            executable: "claude-field-fixture".to_owned(),
5361            ..config(text)
5362        })
5363        .unwrap();
5364        let working_directory = std::env::current_dir()
5365            .unwrap()
5366            .to_string_lossy()
5367            .into_owned();
5368        let started = handler
5369            .start(
5370                AgentStart {
5371                    mission_id: "mission-clearance".parse().unwrap(),
5372                    agent_id: "007".to_owned(),
5373                    prompt: "work".to_owned(),
5374                    initial_context: Vec::new(),
5375                    working_directory: working_directory.clone(),
5376                    clearance: clearance.to_owned(),
5377                    environment: environment.clone(),
5378                    model: None,
5379                    effort: None,
5380                    max_cost_micro_usd: None,
5381                    project_settings: false,
5382                    project_mcp: false,
5383                    answer_only: false,
5384                    assistant: None,
5385                    overlays: Default::default(),
5386                    loadout: Default::default(),
5387                    ledger: None,
5388                },
5389                terminal.clone().into_object(),
5390            )
5391            .unwrap();
5392        read_to_completion(&started);
5393        started.close().unwrap();
5394        let resumed = handler
5395            .resume(
5396                AgentResume {
5397                    mission_id: "mission-clearance".parse().unwrap(),
5398                    run_id: RunId::try_new("claude-clearance-run").unwrap(),
5399                    message: None,
5400                    working_directory,
5401                    clearance: clearance.to_owned(),
5402                    environment,
5403                    model: None,
5404                    effort: None,
5405                    max_cost_micro_usd: None,
5406                    project_settings: false,
5407                    project_mcp: false,
5408                    answer_only: false,
5409                    assistant: None,
5410                    initial_context: Vec::new(),
5411                    overlays: Default::default(),
5412                    loadout: Default::default(),
5413                },
5414                terminal.clone().into_object(),
5415            )
5416            .unwrap();
5417        resumed.close().unwrap();
5418        let specs = terminal.specs.lock().unwrap();
5419        assert_eq!(specs.len(), 2);
5420        specs.iter().map(|spec| field_flags(&spec.argv)).collect()
5421    }
5422
5423    #[test]
5424    fn a_runs_tools_follow_its_clearance_on_start_and_resume() {
5425        let field = (
5426            DEFAULT_OFFERED.to_owned(),
5427            "WebFetch,WebSearch,Agent".to_owned(),
5428            format!("mcp__ai6-cables,{DEFAULT_ALLOWED}"),
5429        );
5430        let desk = (
5431            DESK_OFFERED.to_owned(),
5432            "WebFetch,WebSearch,Agent,Bash,PowerShell".to_owned(),
5433            format!("mcp__ai6-cables,{DESK_ALLOWED}"),
5434        );
5435        for clearance in ["field", "00"] {
5436            assert_eq!(flags_at(clearance, ""), [field.clone(), field.clone()]);
5437        }
5438        // A value the handler does not know, an empty one included, gets the least it can give.
5439        for clearance in ["desk", "developer", ""] {
5440            assert_eq!(
5441                flags_at(clearance, ""),
5442                [desk.clone(), desk.clone()],
5443                "{clearance:?}"
5444            );
5445        }
5446    }
5447
5448    #[test]
5449    fn a_desk_run_is_given_a_command_tool_only_by_a_rule_reported_as_a_weakening() {
5450        let settings = "allowed_tools = [\"Bash(git status)\"]\n";
5451        let flags = flags_at("desk", settings);
5452        assert_eq!(
5453            flags[0],
5454            (
5455                format!("{DESK_OFFERED},Bash"),
5456                "WebFetch,WebSearch,Agent,PowerShell".to_owned(),
5457                format!("mcp__ai6-cables,{DESK_ALLOWED},Bash(git status)"),
5458            ),
5459            "the tool it names, and no other"
5460        );
5461        assert_eq!(flags[1], flags[0]);
5462        let weakenings = |text: &str| {
5463            ClaudeHandler::try_from(config(text))
5464                .unwrap()
5465                .weakenings()
5466                .unwrap()
5467        };
5468        assert_eq!(
5469            weakenings(settings),
5470            ["allowed_tools adds Bash(git status) to what its desk Runs may call"]
5471        );
5472        assert_eq!(
5473            weakenings("allowed_tools = [\"PowerShell\"]"),
5474            ["allowed_tools adds PowerShell to what its desk Runs may call"]
5475        );
5476        assert_eq!(
5477            weakenings("allowed_tools = [\"mcp__ai6-theater__exec\"]"),
5478            ["allowed_tools adds mcp__ai6-theater__exec to what its desk Runs may call"]
5479        );
5480        assert!(
5481            weakenings("allowed_tools = [\"Bash\"]\ndenied_tools = [\"Bash\"]").is_empty(),
5482            "a deny rule beats the allow rule"
5483        );
5484    }
5485
5486    #[test]
5487    fn a_desk_run_on_a_remote_theater_may_read_it_but_not_run_or_write() {
5488        let environment = BTreeMap::from([
5489            ("AI6_THEATER_MCP_URL".to_owned(), "http://b/mcp".to_owned()),
5490            ("AI6_THEATER_MCP_TOKEN".to_owned(), "b".to_owned()),
5491        ]);
5492        let flags = |commands: bool, settings: &ClaudeSettings| {
5493            let mut argv = Vec::new();
5494            add_field_tools(&mut argv, &environment, settings, commands);
5495            field_flags(&argv)
5496        };
5497        let tasks = "TodoWrite,TaskCreate,TaskGet,TaskList,TaskUpdate";
5498        let own = "Bash,PowerShell,Edit,Write,NotebookEdit,Read,Glob,Grep";
5499        assert_eq!(
5500            flags(false, &ClaudeSettings::default()),
5501            (
5502                tasks.to_owned(),
5503                format!(
5504                    "WebFetch,WebSearch,Agent,mcp__ai6-theater__exec,\
5505                     mcp__ai6-theater__fs_write,mcp__ai6-theater__edit,\
5506                     mcp__ai6-theater__apply_patch,{own}"
5507                ),
5508                format!("mcp__ai6-theater,{tasks}"),
5509            )
5510        );
5511        assert_eq!(
5512            flags(true, &ClaudeSettings::default()).1,
5513            format!("WebFetch,WebSearch,Agent,{own}"),
5514            "field keeps every Theater tool"
5515        );
5516        let consent = ClaudeSettings {
5517            allowed_tools: vec!["mcp__ai6-theater__exec".to_owned(), "Bash".to_owned()],
5518            denied_tools: Vec::new(),
5519        };
5520        let (offered, denied, _) = flags(false, &consent);
5521        assert_eq!(
5522            denied,
5523            format!(
5524                "WebFetch,WebSearch,Agent,mcp__ai6-theater__fs_write,mcp__ai6-theater__edit,\
5525                 mcp__ai6-theater__apply_patch,{own}"
5526            ),
5527            "a rule lifts the Theater tool it names, and never Claude's own shell on the Station"
5528        );
5529        assert_eq!(offered, tasks);
5530    }
5531
5532    #[test]
5533    fn a_run_held_to_its_plan_reads_and_calls_ai6_and_a_resume_at_field_has_its_tools() {
5534        let flags = flags_at(
5535            ai6::READ_CLEARANCE,
5536            "allowed_tools = [\"Bash\", \"Edit(/**)\"]
5537",
5538        );
5539        assert_eq!(flags[0].0, "Read,Glob,Grep", "nothing offered but reading");
5540        assert_eq!(
5541            flags[0].2, "mcp__ai6-cables,Read(/**)",
5542            "reading is rooted at the working directory, and no setting adds to it"
5543        );
5544        for denied in [
5545            "Edit",
5546            "Write",
5547            "NotebookEdit",
5548            "Bash",
5549            "PowerShell",
5550            "TodoWrite",
5551        ] {
5552            assert!(
5553                flags[0].1.split(',').any(|tool| tool == denied),
5554                "{denied} denied by name: {}",
5555                flags[0].1
5556            );
5557        }
5558        assert_eq!(
5559            flags[1], flags[0],
5560            "a resume held to the plan is held the same"
5561        );
5562        let field = flags_at("field", "");
5563        assert_eq!(
5564            field[1].0, DEFAULT_OFFERED,
5565            "a resume at field gets the Mission's tools"
5566        );
5567        assert!(field[1].2.contains("Edit(/**)") && field[1].2.contains("Bash"));
5568    }
5569
5570    #[test]
5571    fn this_handler_can_hold_a_run_to_its_plan() {
5572        let handler = ClaudeHandler::try_from(ClaudeConfig::default()).unwrap();
5573        assert_eq!(handler.read_only_refusal().unwrap(), None);
5574    }
5575
5576    #[test]
5577    fn a_desk_run_without_a_station_has_no_server_and_no_command_tool() {
5578        let mut argv = Vec::new();
5579        add_settings(
5580            &mut argv,
5581            &BTreeMap::new(),
5582            "wd",
5583            Mode {
5584                project_settings: false,
5585                project_mcp: false,
5586                answer_only: false,
5587                commands: false,
5588                reads_only: false,
5589            },
5590            &ClaudeSettings::default(),
5591            None,
5592            &RunOverlays::default(),
5593        )
5594        .unwrap();
5595        let (offered, denied, allowed) = field_flags(&argv);
5596        assert_eq!(offered, DESK_OFFERED);
5597        assert_eq!(denied, "WebFetch,WebSearch,Agent,Bash,PowerShell");
5598        assert_eq!(allowed, DESK_ALLOWED);
5599    }
5600
5601    #[test]
5602    fn answer_only_and_assistant_flags_do_not_depend_on_the_clearance() {
5603        let flags = |commands: bool, answer_only: bool, assistant: Option<&AssistantMode>| {
5604            let mut argv = Vec::new();
5605            add_settings(
5606                &mut argv,
5607                &assistant_environment(),
5608                "wd",
5609                Mode {
5610                    project_settings: false,
5611                    project_mcp: false,
5612                    answer_only,
5613                    commands,
5614                    reads_only: false,
5615                },
5616                &ClaudeSettings::default(),
5617                assistant,
5618                &RunOverlays::default(),
5619            )
5620            .unwrap();
5621            argv
5622        };
5623        assert_eq!(flags(true, true, None), flags(false, true, None));
5624        let mode = AssistantMode::moneypenny();
5625        assert_eq!(
5626            flags(true, false, Some(&mode)),
5627            flags(false, false, Some(&mode))
5628        );
5629    }
5630
5631    #[test]
5632    fn handler_settings_it_cannot_read_are_refused() {
5633        for text in [
5634            "allowed = [\"Bash\"]",
5635            "allowed_tools = \"Bash\"",
5636            "allowed_tools = [\"--dangerously-skip-permissions\"]",
5637            "denied_tools = [\"\"]",
5638        ] {
5639            let refused = read_config(text).and_then(|config| {
5640                ClaudeHandler::try_from(config)
5641                    .map(|_| ())
5642                    .map_err(|e| e.to_string())
5643            });
5644            assert!(refused.is_err(), "{text} was accepted");
5645        }
5646    }
5647
5648    #[test]
5649    fn answer_only_and_assistant_runs_ignore_the_settings() {
5650        let settings = ClaudeSettings {
5651            allowed_tools: vec!["WebFetch".to_owned()],
5652            denied_tools: vec!["Read".to_owned()],
5653        };
5654        let flags =
5655            |answer_only: bool, assistant: Option<&AssistantMode>, settings: &ClaudeSettings| {
5656                let mut argv = Vec::new();
5657                add_settings(
5658                    &mut argv,
5659                    &assistant_environment(),
5660                    "wd",
5661                    Mode {
5662                        project_settings: false,
5663                        project_mcp: false,
5664                        answer_only,
5665                        commands: true,
5666                        reads_only: false,
5667                    },
5668                    settings,
5669                    assistant,
5670                    &RunOverlays::default(),
5671                )
5672                .unwrap();
5673                argv
5674            };
5675        let answer_only = flags(true, None, &settings);
5676        assert_eq!(answer_only, flags(true, None, &ClaudeSettings::default()));
5677        assert!(
5678            !answer_only
5679                .iter()
5680                .any(|argument| argument == "--permission-mode")
5681        );
5682        let (_, _, mode) = script_mode("denied", &[], false);
5683        assert_eq!(
5684            flags(false, Some(&mode), &settings),
5685            flags(false, Some(&mode), &ClaudeSettings::default())
5686        );
5687    }
5688
5689    /// Terminal output holding one `result` line, as a resumed Run reads it.
5690    fn result_run(result: Value) -> Object<dyn AgentSession> {
5691        let mut input = result.to_string().into_bytes();
5692        input.push(b'\n');
5693        let terminal = ResumeTerminal {
5694            spec: Arc::new(Mutex::new(None)),
5695            input,
5696            writes: Arc::new(Mutex::new(Vec::new())),
5697        };
5698        ClaudeHandler::try_from(ClaudeConfig::default())
5699            .unwrap()
5700            .resume(
5701                AgentResume {
5702                    clearance: "field".to_owned(),
5703                    mission_id: "mission-denied".parse().unwrap(),
5704                    run_id: RunId::try_new("claude-run-denied").unwrap(),
5705                    message: None,
5706                    working_directory: "wd".to_owned(),
5707                    environment: BTreeMap::new(),
5708                    model: None,
5709                    effort: None,
5710                    max_cost_micro_usd: None,
5711                    project_settings: false,
5712                    project_mcp: false,
5713                    answer_only: false,
5714                    assistant: None,
5715                    initial_context: Vec::new(),
5716                    overlays: Default::default(),
5717                    loadout: Default::default(),
5718                },
5719                terminal.into_object(),
5720            )
5721            .unwrap()
5722    }
5723
5724    /// The shape Claude Code 2.1.316 writes after a turn whose calls were refused: a success.
5725    #[test]
5726    fn a_denied_call_is_reported_before_the_turn_ends_and_names_only_its_target() {
5727        let run = result_run(json!({
5728            "type": "result",
5729            "subtype": "success",
5730            "is_error": false,
5731            "result": "finished",
5732            "permission_denials": [
5733                {"tool_name": "Write", "tool_use_id": "t1", "tool_input": {"content": "secret", "file_path": "/w/a.txt"}},
5734                {"tool_name": "Bash", "tool_use_id": "t2", "tool_input": {"command": "ls", "description": "secret"}},
5735                {"tool_name": "Write", "tool_use_id": "t3", "tool_input": {"content": "secret"}},
5736            ],
5737        }));
5738        let events = std::iter::from_fn(|| run.next_event(400).unwrap()).collect::<Vec<_>>();
5739        let kinds_and_texts = events
5740            .iter()
5741            .map(|event| (event.kind.as_str(), event.text.as_deref()))
5742            .collect::<Vec<_>>();
5743        assert_eq!(
5744            kinds_and_texts,
5745            [
5746                (DENIED_EVENT, Some("Write, Bash")),
5747                ("completed", Some("finished")),
5748            ]
5749        );
5750        assert!(events[0].tools.is_empty(), "a refused call did not run");
5751        let calls: Value = serde_json::from_slice(events[0].data.as_deref().unwrap()).unwrap();
5752        assert_eq!(
5753            calls,
5754            json!([
5755                {"tool": "Write", "target": "/w/a.txt"},
5756                {"tool": "Bash", "target": "ls"},
5757                {"tool": "Write", "target": null},
5758            ]),
5759            "only the target of each call, never the rest of its input"
5760        );
5761    }
5762
5763    #[test]
5764    fn a_turn_with_nothing_denied_reports_only_its_end() {
5765        for denials in [json!([]), Value::Null] {
5766            let run = result_run(json!({
5767                "type": "result",
5768                "subtype": "success",
5769                "result": "finished",
5770                "permission_denials": denials,
5771            }));
5772            let kinds = std::iter::from_fn(|| run.next_event(400).unwrap())
5773                .map(|event| event.kind)
5774                .collect::<Vec<_>>();
5775            assert_eq!(kinds, ["completed"]);
5776        }
5777    }
5778
5779    fn cable_environment() -> BTreeMap<String, String> {
5780        BTreeMap::from([
5781            (
5782                "AI6_CABLE_MCP_URL".to_owned(),
5783                "http://127.0.0.1:43210/mcp".to_owned(),
5784            ),
5785            ("AI6_CABLE_MCP_TOKEN".to_owned(), "cable-token".to_owned()),
5786        ])
5787    }
5788
5789    /// The hook as the Claude Code hooks reference describes a `PreToolUse` command hook: a
5790    /// regex matcher over tool names, exec form `command` + `args`, `timeout` in seconds.
5791    #[test]
5792    fn a_run_with_a_station_gets_the_green_ink_hook_in_its_settings() {
5793        let mut environment = cable_environment();
5794        environment.insert(GATE_PROGRAM_ENV.to_owned(), "/opt/ai6/bin/ai6".to_owned());
5795        let mut argv = vec!["claude".to_owned()];
5796        add_mission_settings(&mut argv, &environment, &RunOverlays::default());
5797
5798        assert_eq!(argv[1], "--settings");
5799        let settings: Value = serde_json::from_str(&argv[2]).unwrap();
5800        assert_eq!(settings["disableAllHooks"], false);
5801        let entry = &settings["hooks"]["PreToolUse"][0];
5802        let matcher = entry["matcher"].as_str().unwrap();
5803        for tool in ["Bash", "PowerShell"] {
5804            assert!(matcher.split('|').any(|name| name == tool), "{tool}");
5805        }
5806        let hook = &entry["hooks"][0];
5807        assert_eq!(hook["type"], "command");
5808        assert_eq!(hook["command"], "/opt/ai6/bin/ai6");
5809        assert_eq!(
5810            hook["args"],
5811            json!([
5812                "green-ink",
5813                "gate",
5814                "--cable-url",
5815                "http://127.0.0.1:43210/mcp"
5816            ]),
5817            "the endpoint is pinned in the hook itself"
5818        );
5819        assert_eq!(hook["onFailure"], "block");
5820        assert!(hook["timeout"].as_u64().unwrap() >= 30);
5821        assert!(
5822            !argv[2].contains("cable-token"),
5823            "the hook reads the token from its environment"
5824        );
5825
5826        // Unnamed, the gate is the program hosting the handler.
5827        let mut argv = vec!["claude".to_owned()];
5828        add_mission_settings(&mut argv, &cable_environment(), &RunOverlays::default());
5829        let settings: Value = serde_json::from_str(&argv[2]).unwrap();
5830        assert_eq!(
5831            settings["hooks"]["PreToolUse"][0]["hooks"][0]["command"],
5832            std::env::current_exe().unwrap().to_string_lossy().as_ref()
5833        );
5834
5835        // Without a Station to ask there is no gate.
5836        let mut argv = vec!["claude".to_owned()];
5837        add_mission_settings(&mut argv, &BTreeMap::new(), &RunOverlays::default());
5838        assert_eq!(argv, ["claude"]);
5839    }
5840
5841    #[test]
5842    fn start_and_resume_both_pass_the_gate() {
5843        let mut environment = cable_environment();
5844        environment.insert(
5845            "CLAUDE_FIXTURE_RUN_ID".to_owned(),
5846            "claude-gate-run".to_owned(),
5847        );
5848        let terminal = ProcessTerminal::new();
5849        let handler = ClaudeHandler::try_from(ClaudeConfig {
5850            executable: "claude-gate-fixture".to_owned(),
5851            ..ClaudeConfig::default()
5852        })
5853        .unwrap();
5854        let working_directory = std::env::current_dir()
5855            .unwrap()
5856            .to_string_lossy()
5857            .into_owned();
5858        let started = handler
5859            .start(
5860                AgentStart {
5861                    mission_id: "mission-gate".parse().unwrap(),
5862                    agent_id: "007".to_owned(),
5863                    prompt: "push when approved".to_owned(),
5864                    initial_context: Vec::new(),
5865                    working_directory: working_directory.clone(),
5866                    clearance: "field".to_owned(),
5867                    environment: environment.clone(),
5868                    model: None,
5869                    effort: None,
5870                    max_cost_micro_usd: None,
5871                    project_settings: false,
5872                    project_mcp: false,
5873                    answer_only: false,
5874                    assistant: None,
5875                    overlays: Default::default(),
5876                    loadout: Default::default(),
5877                    ledger: None,
5878                },
5879                terminal.clone().into_object(),
5880            )
5881            .unwrap();
5882        read_to_completion(&started);
5883        started.close().unwrap();
5884        let resumed = handler
5885            .resume(
5886                AgentResume {
5887                    clearance: "field".to_owned(),
5888                    mission_id: "mission-gate".parse().unwrap(),
5889                    run_id: RunId::try_new("claude-gate-run").unwrap(),
5890                    message: Some("approved".to_owned()),
5891                    working_directory,
5892                    environment,
5893                    model: None,
5894                    effort: None,
5895                    max_cost_micro_usd: None,
5896                    project_settings: false,
5897                    project_mcp: false,
5898                    answer_only: false,
5899                    assistant: None,
5900                    initial_context: Vec::new(),
5901                    overlays: Default::default(),
5902                    loadout: Default::default(),
5903                },
5904                terminal.clone().into_object(),
5905            )
5906            .unwrap();
5907        read_to_completion(&resumed);
5908        resumed.close().unwrap();
5909        for spec in terminal.specs.lock().unwrap().iter() {
5910            let position = spec
5911                .argv
5912                .iter()
5913                .position(|argument| argument == "--settings")
5914                .expect("the gate is passed");
5915            assert!(spec.argv[position + 1].contains("green-ink"));
5916        }
5917    }
5918
5919    /// `--setting-sources` takes `user`, `project` and `local`; `--strict-mcp-config` keeps only
5920    /// `--mcp-config`'s servers; `--settings` sits above the setting files and is not one of
5921    /// them (Claude Code CLI reference and settings precedence, code.claude.com/docs).
5922    #[test]
5923    fn project_settings_are_shut_out_unless_allowed_and_the_gate_stays_either_way() {
5924        let mut environment = cable_environment();
5925        environment.insert(
5926            "CLAUDE_FIXTURE_RUN_ID".to_owned(),
5927            "claude-settings-run".to_owned(),
5928        );
5929        let terminal = ProcessTerminal::new();
5930        let handler = ClaudeHandler::try_from(ClaudeConfig {
5931            executable: "claude-settings-fixture".to_owned(),
5932            ..ClaudeConfig::default()
5933        })
5934        .unwrap();
5935        let working_directory = std::env::current_dir()
5936            .unwrap()
5937            .to_string_lossy()
5938            .into_owned();
5939        let start = |(project_settings, project_mcp, answer_only)| AgentStart {
5940            mission_id: "mission-settings".parse().unwrap(),
5941            agent_id: "007".to_owned(),
5942            prompt: "work".to_owned(),
5943            initial_context: Vec::new(),
5944            working_directory: working_directory.clone(),
5945            clearance: "field".to_owned(),
5946            environment: environment.clone(),
5947            model: None,
5948            effort: None,
5949            max_cost_micro_usd: None,
5950            project_settings,
5951            project_mcp,
5952            answer_only,
5953            assistant: None,
5954            overlays: Default::default(),
5955            loadout: Default::default(),
5956            ledger: None,
5957        };
5958        for mode in [
5959            (false, false, false),
5960            (true, true, false),
5961            (true, false, false),
5962            (true, true, true),
5963        ] {
5964            let started = handler
5965                .start(start(mode), terminal.clone().into_object())
5966                .unwrap();
5967            read_to_completion(&started);
5968            started.close().unwrap();
5969        }
5970        let resumed = handler
5971            .resume(
5972                AgentResume {
5973                    clearance: "field".to_owned(),
5974                    mission_id: "mission-settings".parse().unwrap(),
5975                    run_id: RunId::try_new("claude-settings-run").unwrap(),
5976                    message: None,
5977                    working_directory: working_directory.clone(),
5978                    environment: environment.clone(),
5979                    model: None,
5980                    effort: None,
5981                    max_cost_micro_usd: None,
5982                    project_settings: false,
5983                    project_mcp: false,
5984                    answer_only: false,
5985                    assistant: None,
5986                    initial_context: Vec::new(),
5987                    overlays: Default::default(),
5988                    loadout: Default::default(),
5989                },
5990                terminal.clone().into_object(),
5991            )
5992            .unwrap();
5993        resumed.close().unwrap();
5994
5995        let specs = terminal.specs.lock().unwrap();
5996        let shut_out = |argv: &[String]| {
5997            argv.windows(2)
5998                .any(|pair| pair[0] == "--setting-sources" && pair[1] == "user")
5999                && argv
6000                    .iter()
6001                    .any(|argument| argument == "--strict-mcp-config")
6002        };
6003        let has = |argv: &[String], flag: &str| argv.iter().any(|argument| argument == flag);
6004        let (ignored, loaded, pinned, answer_only, resumed) = (
6005            &specs[0].argv,
6006            &specs[1].argv,
6007            &specs[2].argv,
6008            &specs[3].argv,
6009            &specs[4].argv,
6010        );
6011        // Answer-only wins over everything else asked for: no tool, no server, no gate.
6012        assert!(shut_out(answer_only), "{answer_only:?}");
6013        assert!(has(answer_only, "--restricted") && has(answer_only, "--tools="));
6014        let position = |flag: &str| answer_only.iter().position(|a| a == flag).unwrap();
6015        assert_eq!(
6016            answer_only[position("--disallowedTools") + 1],
6017            ANSWER_ONLY_DENIED
6018        );
6019        assert_eq!(
6020            answer_only[position("--mcp-config") + 1],
6021            r#"{"mcpServers":{}}"#
6022        );
6023        assert!(!has(answer_only, "--settings"), "no gate: nothing to gate");
6024        assert!(!answer_only.iter().any(|a| a.contains("ai6-cables")));
6025        assert!(shut_out(ignored), "{ignored:?}");
6026        assert!(
6027            !answer_only.iter().any(|a| a.contains("dontAsk")),
6028            "answer-only has no mode"
6029        );
6030        assert!(has(ignored, "--settings") && has(ignored, "--mcp-config"));
6031        assert!(!has(loaded, "--setting-sources") && !has(loaded, "--strict-mcp-config"));
6032        assert!(
6033            has(loaded, "--settings"),
6034            "the gate does not depend on the mode"
6035        );
6036        assert!(
6037            !has(pinned, "--setting-sources") && has(pinned, "--strict-mcp-config"),
6038            "settings without .mcp.json keep only AI6's servers: {pinned:?}"
6039        );
6040        assert!(shut_out(resumed), "{resumed:?}");
6041        let advisor = |index: usize| {
6042            specs[index]
6043                .env
6044                .as_ref()
6045                .unwrap()
6046                .get(DISABLE_ADVISOR_ENV)
6047                .cloned()
6048        };
6049        assert_eq!(
6050            advisor(3).as_deref(),
6051            Some("1"),
6052            "answer-only has no advisor"
6053        );
6054        assert_eq!(advisor(0), None, "an Operation's Run keeps its own");
6055        let instructions = |index: usize| {
6056            specs[index]
6057                .env
6058                .as_ref()
6059                .unwrap()
6060                .get("CLAUDE_CODE_DISABLE_CLAUDE_MDS")
6061                .cloned()
6062        };
6063        assert_eq!(
6064            instructions(3).as_deref(),
6065            Some("1"),
6066            "answer-only loads no CLAUDE.md, the user's own included"
6067        );
6068        assert_eq!(instructions(0), None, "an Operation's Run keeps its own");
6069    }
6070
6071    /// Claude Code 2.1.310 warns that a deny rule naming `MultiEdit` or `LS` matches no known
6072    /// tool.
6073    #[test]
6074    fn deny_lists_name_only_tools_claude_code_knows() {
6075        let lists = [
6076            OWN_TOOLS.join(","),
6077            ANSWER_ONLY_DENIED.to_owned(),
6078            ASSISTANT_DENIED.to_owned(),
6079            FIELD_DENIED.join(","),
6080        ];
6081        for list in lists {
6082            for gone in ["MultiEdit", "LS"] {
6083                assert!(
6084                    !list.split(',').any(|name| name == gone),
6085                    "{gone} in {list}"
6086                );
6087            }
6088        }
6089    }
6090
6091    fn assistant_environment() -> BTreeMap<String, String> {
6092        let mut environment = cable_environment();
6093        environment.insert(
6094            "AI6_MONEYPENNY_MCP_URL".to_owned(),
6095            "https://exports.example/v1/moneypenny/mcp".to_owned(),
6096        );
6097        environment.insert(
6098            "AI6_MONEYPENNY_MCP_TOKEN".to_owned(),
6099            "conversation-token".to_owned(),
6100        );
6101        environment.insert(
6102            "CLAUDE_FIXTURE_RUN_ID".to_owned(),
6103            "claude-assistant-run".to_owned(),
6104        );
6105        environment
6106    }
6107
6108    /// `--tools ""` removes every built-in tool and does not touch MCP tools;
6109    /// `--disallowedTools` with a bare name removes that tool; `--allowedTools` lets a tool run
6110    /// without a prompt; `--strict-mcp-config` keeps only `--mcp-config`'s servers;
6111    /// `--restricted` removes command tools and WebFetch and loads only managed settings and
6112    /// `--settings` (Claude Code CLI reference, code.claude.com/docs/en/cli-reference,
6113    /// read 2026-10-26).
6114    #[test]
6115    fn an_assistant_has_only_its_mcp_servers_and_no_built_in_tool_on_start_and_resume() {
6116        let environment = assistant_environment();
6117        let terminal = ProcessTerminal::new();
6118        let handler = ClaudeHandler::try_from(ClaudeConfig {
6119            executable: "claude-assistant-fixture".to_owned(),
6120            ..ClaudeConfig::default()
6121        })
6122        .unwrap();
6123        let working_directory = std::env::current_dir()
6124            .unwrap()
6125            .to_string_lossy()
6126            .into_owned();
6127        let started = handler
6128            .start(
6129                AgentStart {
6130                    mission_id: "assistant-conversation".parse().unwrap(),
6131                    agent_id: "moneypenny".to_owned(),
6132                    prompt: "Which Stations are busy?".to_owned(),
6133                    initial_context: vec!["You are Moneypenny.".to_owned()],
6134                    working_directory: working_directory.clone(),
6135                    clearance: "desk".to_owned(),
6136                    environment: environment.clone(),
6137                    model: None,
6138                    effort: None,
6139                    max_cost_micro_usd: None,
6140                    project_settings: true,
6141                    project_mcp: true,
6142                    answer_only: false,
6143                    assistant: Some(AssistantMode::moneypenny()),
6144                    overlays: Default::default(),
6145                    loadout: Default::default(),
6146                    ledger: None,
6147                },
6148                terminal.clone().into_object(),
6149            )
6150            .unwrap();
6151        read_to_completion(&started);
6152        started.close().unwrap();
6153        let resumed = handler
6154            .resume(
6155                AgentResume {
6156                    clearance: "desk".to_owned(),
6157                    mission_id: "assistant-conversation".parse().unwrap(),
6158                    run_id: RunId::try_new("claude-assistant-run").unwrap(),
6159                    message: Some("And now?".to_owned()),
6160                    working_directory,
6161                    environment,
6162                    model: None,
6163                    effort: None,
6164                    max_cost_micro_usd: None,
6165                    project_settings: true,
6166                    project_mcp: true,
6167                    answer_only: false,
6168                    assistant: Some(AssistantMode::moneypenny()),
6169                    initial_context: vec!["You are Moneypenny.".to_owned()],
6170                    overlays: Default::default(),
6171                    loadout: Default::default(),
6172                },
6173                terminal.clone().into_object(),
6174            )
6175            .unwrap();
6176        read_to_completion(&resumed);
6177        resumed.close().unwrap();
6178        assert_eq!(
6179            *terminal.contexts.lock().unwrap(),
6180            [
6181                Some("You are Moneypenny.".to_owned()),
6182                Some("You are Moneypenny.".to_owned())
6183            ]
6184        );
6185        let specs = terminal.specs.lock().unwrap();
6186        assert_eq!(specs.len(), 2);
6187        for spec in specs.iter() {
6188            let argv = &spec.argv;
6189            let after = |flag: &str| {
6190                let position = argv.iter().position(|a| a == flag).unwrap_or_else(|| {
6191                    panic!("{flag} missing from {argv:?}");
6192                });
6193                argv[position + 1].clone()
6194            };
6195            assert!(argv.iter().any(|a| a == "--restricted"), "{argv:?}");
6196            assert!(argv.iter().any(|a| a == "--tools="), "{argv:?}");
6197            assert!(argv.iter().any(|a| a == "--strict-mcp-config"), "{argv:?}");
6198            assert_eq!(after("--setting-sources"), "user");
6199            assert_eq!(after("--disallowedTools"), ASSISTANT_DENIED);
6200            assert!(!ASSISTANT_DENIED.contains("mcp__"));
6201            assert_eq!(
6202                spec.env
6203                    .as_ref()
6204                    .unwrap()
6205                    .get(DISABLE_ADVISOR_ENV)
6206                    .map(String::as_str),
6207                Some("1"),
6208                "no server-side advisor"
6209            );
6210            assert_eq!(
6211                spec.env
6212                    .as_ref()
6213                    .unwrap()
6214                    .get(DISABLE_AUTO_MEMORY_ENV)
6215                    .map(String::as_str),
6216                Some("1"),
6217                "no auto memory beside hers"
6218            );
6219            assert!(!argv.iter().any(|a| a == "--permission-mode"), "{argv:?}");
6220            assert_eq!(after("--allowedTools"), "mcp__moneypenny");
6221            let servers: Value = serde_json::from_str(&after("--mcp-config")).unwrap();
6222            assert_eq!(
6223                servers,
6224                json!({"mcpServers": {"moneypenny": {
6225                    "type": "http",
6226                    "url": "${AI6_MONEYPENNY_MCP_URL}",
6227                    "headers": {"Authorization": "Bearer ${AI6_MONEYPENNY_MCP_TOKEN}"}
6228                }}}),
6229                "only Moneypenny's server, the Cable server of the environment left out"
6230            );
6231            assert_eq!(
6232                argv.iter().filter(|a| *a == "--mcp-config").count(),
6233                1,
6234                "{argv:?}"
6235            );
6236            assert!(!argv.iter().any(|a| a == "--settings"), "no gate to pass");
6237            assert!(
6238                argv.iter()
6239                    .all(|a| !a.starts_with("--append-system-prompt=")),
6240                "the instructions go through a file"
6241            );
6242            assert!(
6243                !argv.iter().any(|a| a.contains("conversation-token")),
6244                "the token stays in the environment"
6245            );
6246        }
6247    }
6248
6249    /// Measured with Claude Code 2.1.310 against a loopback stand-in for the API: under these
6250    /// flags Write and Edit under `personal/` ran, and Write to another directory, to the
6251    /// working directory's own `CLAUDE.md`, to `personal/.git/hooks` and to `personal/../x`
6252    /// were denied, as was Read outside the working directory.
6253    #[test]
6254    fn an_assistant_with_files_gets_the_file_tools_under_dont_ask_on_start_and_resume() {
6255        let environment = assistant_environment();
6256        let terminal = ProcessTerminal::new();
6257        let handler = ClaudeHandler::try_from(ClaudeConfig {
6258            executable: "claude-assistant-fixture".to_owned(),
6259            ..ClaudeConfig::default()
6260        })
6261        .unwrap();
6262        let working_directory = std::env::current_dir()
6263            .unwrap()
6264            .to_string_lossy()
6265            .into_owned();
6266        let context_directory = tempfile::tempdir().unwrap();
6267        let context_path = context_directory.path().join("assistant-context.md");
6268        std::fs::write(&context_path, "her notes").unwrap();
6269        let context = context_path.to_string_lossy().into_owned();
6270        let mode = AssistantMode {
6271            files: vec!["personal".to_owned(), "scratch".to_owned()],
6272            context_file: Some(context.clone()),
6273            ..AssistantMode::moneypenny()
6274        };
6275        let started = handler
6276            .start(
6277                AgentStart {
6278                    mission_id: "assistant-conversation".parse().unwrap(),
6279                    agent_id: "moneypenny".to_owned(),
6280                    prompt: "Remember that I like tables.".to_owned(),
6281                    initial_context: Vec::new(),
6282                    working_directory: working_directory.clone(),
6283                    clearance: "desk".to_owned(),
6284                    environment: environment.clone(),
6285                    model: None,
6286                    effort: None,
6287                    max_cost_micro_usd: None,
6288                    project_settings: false,
6289                    project_mcp: false,
6290                    answer_only: false,
6291                    assistant: Some(mode.clone()),
6292                    overlays: Default::default(),
6293                    loadout: Default::default(),
6294                    ledger: None,
6295                },
6296                terminal.clone().into_object(),
6297            )
6298            .unwrap();
6299        read_to_completion(&started);
6300        started.close().unwrap();
6301        let resumed = handler
6302            .resume(
6303                AgentResume {
6304                    clearance: "desk".to_owned(),
6305                    mission_id: "assistant-conversation".parse().unwrap(),
6306                    run_id: RunId::try_new("claude-assistant-run").unwrap(),
6307                    message: Some("And now?".to_owned()),
6308                    working_directory,
6309                    environment,
6310                    model: None,
6311                    effort: None,
6312                    max_cost_micro_usd: None,
6313                    project_settings: false,
6314                    project_mcp: false,
6315                    answer_only: false,
6316                    assistant: Some(mode),
6317                    initial_context: Vec::new(),
6318                    overlays: Default::default(),
6319                    loadout: Default::default(),
6320                },
6321                terminal.clone().into_object(),
6322            )
6323            .unwrap();
6324        read_to_completion(&resumed);
6325        resumed.close().unwrap();
6326        assert_eq!(
6327            *terminal.contexts.lock().unwrap(),
6328            [Some("her notes".to_owned()), Some("her notes".to_owned())]
6329        );
6330        let specs = terminal.specs.lock().unwrap();
6331        assert_eq!(specs.len(), 2);
6332        for spec in specs.iter() {
6333            let argv = &spec.argv;
6334            let after = |flag: &str| {
6335                let position = argv.iter().position(|a| a == flag).unwrap_or_else(|| {
6336                    panic!("{flag} missing from {argv:?}");
6337                });
6338                argv[position + 1].clone()
6339            };
6340            assert!(argv.iter().any(|a| a == "--restricted"), "{argv:?}");
6341            assert!(!argv.iter().any(|a| a == "--tools="), "{argv:?}");
6342            assert_eq!(after("--tools"), "Read,Write,Edit,Glob,Grep");
6343            assert_eq!(after("--permission-mode"), "dontAsk");
6344            let denied = after("--disallowedTools");
6345            for tool in [
6346                "Bash",
6347                "PowerShell",
6348                "WebFetch",
6349                "WebSearch",
6350                "Task",
6351                "Skill",
6352                "Edit(**/.*)",
6353                "Edit(**/.*/**)",
6354            ] {
6355                assert!(denied.split(',').any(|name| name == tool), "{denied}");
6356            }
6357            for tool in ["Read", "Write", "Edit", "Glob", "Grep"] {
6358                assert!(!denied.split(',').any(|name| name == tool), "{denied}");
6359            }
6360            assert_eq!(
6361                after("--allowedTools"),
6362                "mcp__moneypenny,Read,Glob,Grep,Edit(/personal/**),Edit(/scratch/**)"
6363            );
6364            assert_eq!(after("--setting-sources"), "user");
6365            assert_eq!(
6366                argv.iter()
6367                    .filter(|a| *a == "--append-system-prompt-file")
6368                    .count(),
6369                1,
6370                "{argv:?}"
6371            );
6372            assert_eq!(
6373                spec.env
6374                    .as_ref()
6375                    .unwrap()
6376                    .get("CLAUDE_CODE_DISABLE_AUTO_MEMORY")
6377                    .map(String::as_str),
6378                Some("1")
6379            );
6380        }
6381    }
6382
6383    #[test]
6384    fn an_assistant_with_files_may_call_them_and_nothing_else_built_in() {
6385        let mode = AssistantMode {
6386            files: vec!["personal".to_owned()],
6387            ..AssistantMode::moneypenny()
6388        };
6389        for (mode, tool, ends) in [
6390            (mode.clone(), "Write", false),
6391            (mode.clone(), "Read", false),
6392            (mode, "Bash", true),
6393            (AssistantMode::moneypenny(), "Write", true),
6394        ] {
6395            let mut input =
6396                b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"s-1\"}\n".to_vec();
6397            input.extend_from_slice(
6398                format!(
6399                    "{{\"type\":\"assistant\",\"message\":{{\"content\":[{{\"type\":\"tool_use\",\
6400                     \"id\":\"t\",\"name\":\"{tool}\",\"input\":{{}}}}]}}}}\n"
6401                )
6402                .as_bytes(),
6403            );
6404            input.extend_from_slice(b"{\"type\":\"result\",\"result\":\"done\"}\n");
6405            let run = restricted_run(input, restriction(false, Some(&mode)));
6406            let kinds = std::iter::from_fn(|| run.next_event(400).unwrap())
6407                .map(|event| event.kind)
6408                .collect::<Vec<_>>();
6409            assert_eq!(
6410                kinds.contains(&"failed".to_owned()),
6411                ends,
6412                "{tool} with files {:?}: {kinds:?}",
6413                mode.files
6414            );
6415        }
6416    }
6417
6418    #[test]
6419    fn an_assistant_with_cable_grants_gets_the_cable_server_beside_her_own() {
6420        let mut environment = assistant_environment();
6421        let cables = AssistantMode::moneypenny().with_cables();
6422        let mut argv = Vec::new();
6423        assert!(
6424            add_assistant(&mut argv, &environment, "/wd", &cables).is_err(),
6425            "no Cable endpoint in the environment"
6426        );
6427        environment.insert(
6428            "AI6_ASSISTANT_CABLE_MCP_URL".to_owned(),
6429            "http://127.0.0.1:4100/mcp".to_owned(),
6430        );
6431        environment.insert(
6432            "AI6_ASSISTANT_CABLE_MCP_TOKEN".to_owned(),
6433            "cable-token".to_owned(),
6434        );
6435        let mut argv = Vec::new();
6436        add_assistant(&mut argv, &environment, "/wd", &cables).unwrap();
6437        let after = |flag: &str| {
6438            let position = argv.iter().position(|a| a == flag).unwrap();
6439            argv[position + 1].clone()
6440        };
6441        assert_eq!(after("--allowedTools"), "mcp__moneypenny,mcp__cables");
6442        let servers: Value = serde_json::from_str(&after("--mcp-config")).unwrap();
6443        assert_eq!(
6444            servers,
6445            json!({"mcpServers": {
6446                "moneypenny": {
6447                    "type": "http",
6448                    "url": "${AI6_MONEYPENNY_MCP_URL}",
6449                    "headers": {"Authorization": "Bearer ${AI6_MONEYPENNY_MCP_TOKEN}"}
6450                },
6451                "cables": {
6452                    "type": "http",
6453                    "url": "${AI6_ASSISTANT_CABLE_MCP_URL}",
6454                    "headers": {"Authorization": "Bearer ${AI6_ASSISTANT_CABLE_MCP_TOKEN}"}
6455                }
6456            }}),
6457            "a Mission's Cable server of the environment stays out"
6458        );
6459        assert!(!argv.iter().any(|a| a.contains("cable-token")));
6460    }
6461
6462    /// Measured with Claude Code 2.1.311 against a loopback stand-in for the API: under
6463    /// `--restricted` only a `--plugin-dir` plugin's skills loaded, and with
6464    /// `disableSkillShellExecution` a skill's injected command was replaced, not run.
6465    #[test]
6466    fn an_assistant_with_skills_loads_only_its_plugin_directory_and_runs_no_command() {
6467        let environment = assistant_environment();
6468        let dir = std::env::temp_dir()
6469            .join("conversation")
6470            .join(".claude")
6471            .to_string_lossy()
6472            .into_owned();
6473        let skills = AssistantMode {
6474            skills: vec!["report-writer".to_owned(), "charts".to_owned()],
6475            skills_dir: Some(dir.clone()),
6476            ..AssistantMode::moneypenny()
6477        };
6478        let with_files = AssistantMode {
6479            files: vec!["personal".to_owned()],
6480            ..skills.clone()
6481        };
6482        let commands = AssistantMode {
6483            skill_commands: true,
6484            ..skills.clone()
6485        };
6486        for (mode, tools, allowed) in [
6487            (
6488                &skills,
6489                "Skill",
6490                "mcp__moneypenny,Skill(ai6:report-writer),Skill(ai6:charts)",
6491            ),
6492            (
6493                &with_files,
6494                "Read,Write,Edit,Glob,Grep,Skill",
6495                "mcp__moneypenny,Read,Glob,Grep,Edit(/personal/**),Skill(ai6:report-writer),\
6496                 Skill(ai6:charts)",
6497            ),
6498            (
6499                &commands,
6500                "Skill",
6501                "mcp__moneypenny,Skill(ai6:report-writer),Skill(ai6:charts)",
6502            ),
6503        ] {
6504            let mut argv = Vec::new();
6505            add_assistant(&mut argv, &environment, "/wd", mode).unwrap();
6506            let after = |flag: &str| {
6507                let position = argv.iter().position(|a| a == flag);
6508                position.map(|position| argv[position + 1].clone())
6509            };
6510            assert!(argv.iter().any(|a| a == "--restricted"), "{argv:?}");
6511            assert_eq!(after("--tools").as_deref(), Some(tools));
6512            assert_eq!(after("--permission-mode").as_deref(), Some("dontAsk"));
6513            let denied = after("--disallowedTools").unwrap();
6514            assert!(!denied.split(',').any(|tool| tool == "Skill"), "{denied}");
6515            for tool in ["Bash", "WebFetch", "Task", "Agent"] {
6516                assert!(denied.split(',').any(|name| name == tool), "{denied}");
6517            }
6518            assert_eq!(after("--allowedTools").as_deref(), Some(allowed));
6519            assert_eq!(after("--setting-sources").as_deref(), Some("user"));
6520            assert_eq!(after("--plugin-dir").as_deref(), Some(dir.as_str()));
6521            let settings = after("--settings");
6522            if mode.skill_commands {
6523                assert_eq!(settings, None, "{argv:?}");
6524            } else {
6525                assert_eq!(
6526                    serde_json::from_str::<Value>(&settings.unwrap()).unwrap(),
6527                    json!({"disableSkillShellExecution": true})
6528                );
6529            }
6530        }
6531        let mut nowhere = skills.clone();
6532        nowhere.skills_dir = None;
6533        let mut argv = Vec::new();
6534        assert!(add_assistant(&mut argv, &environment, "/wd", &nowhere).is_err());
6535        assert!(argv.is_empty());
6536
6537        // The tripwire lets `Skill` through only for a mode with skills.
6538        for (mode, ends) in [(&skills, false), (&AssistantMode::moneypenny(), true)] {
6539            let mut input =
6540                b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"s-1\"}\n".to_vec();
6541            input.extend_from_slice(
6542                b"{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"tool_use\",\
6543                  \"id\":\"t\",\"name\":\"Skill\",\"input\":{\"skill\":\"ai6:charts\"}}]}}\n",
6544            );
6545            input.extend_from_slice(b"{\"type\":\"result\",\"result\":\"done\"}\n");
6546            let run = restricted_run(input, restriction(false, Some(mode)));
6547            let kinds = std::iter::from_fn(|| run.next_event(400).unwrap())
6548                .map(|event| event.kind)
6549                .collect::<Vec<_>>();
6550            assert_eq!(kinds.contains(&"failed".to_owned()), ends, "{kinds:?}");
6551        }
6552    }
6553
6554    #[test]
6555    fn skills_beside_scripts_share_one_settings_value() {
6556        let environment = assistant_environment();
6557        let mode = AssistantMode {
6558            interpreters: vec!["python3".to_owned()],
6559            files: vec!["personal".to_owned()],
6560            skills: vec!["charts".to_owned()],
6561            skills_dir: Some(
6562                std::env::temp_dir()
6563                    .join("conversation")
6564                    .join(".claude")
6565                    .to_string_lossy()
6566                    .into_owned(),
6567            ),
6568            ..AssistantMode::moneypenny()
6569        };
6570        let mut argv = Vec::new();
6571        add_assistant(&mut argv, &environment, "/wd", &mode).unwrap();
6572        let flags: Vec<usize> = argv
6573            .iter()
6574            .enumerate()
6575            .filter(|(_, a)| *a == "--settings")
6576            .map(|(at, _)| at)
6577            .collect();
6578        assert_eq!(flags.len(), 1, "one --settings: {argv:?}");
6579        let settings: Value = serde_json::from_str(&argv[flags[0] + 1]).unwrap();
6580        assert_eq!(settings["sandbox"]["enabled"], true);
6581        assert_eq!(settings["disableSkillShellExecution"], true);
6582        let tools = &argv[argv.iter().position(|a| a == "--tools").unwrap() + 1];
6583        assert_eq!(tools, "Read,Write,Edit,Glob,Grep,Bash,Skill");
6584    }
6585
6586    #[test]
6587    fn an_assistant_mode_the_handler_cannot_confine_is_refused() {
6588        let environment = assistant_environment();
6589        let mut skills = AssistantMode::moneypenny();
6590        skills.skills.push("pdf".to_owned());
6591        let mut wildcard = AssistantMode::moneypenny();
6592        wildcard.network.allowed_hosts.push("*".to_owned());
6593        let mut path = AssistantMode::moneypenny();
6594        path.interpreters.push("/bin/sh".to_owned());
6595        for mode in [skills, wildcard, path] {
6596            let mut argv = Vec::new();
6597            assert!(add_assistant(&mut argv, &environment, "/wd", &mode).is_err());
6598            assert!(argv.is_empty());
6599        }
6600        let mut argv = Vec::new();
6601        assert!(
6602            add_assistant(
6603                &mut argv,
6604                &BTreeMap::new(),
6605                "/wd",
6606                &AssistantMode::moneypenny()
6607            )
6608            .is_err(),
6609            "no endpoint in the environment"
6610        );
6611    }
6612
6613    /// The working directory, an unreadable directory and the mode of a fixture: `policy` with
6614    /// `hosts`, `python3` when `scripts`, and her workspace's directories.
6615    #[allow(clippy::type_complexity)]
6616    fn script_mode(policy: &str, hosts: &[&str], scripts: bool) -> (String, String, AssistantMode) {
6617        let root = std::env::temp_dir().join("ai6-claude-fixture");
6618        let working_directory = root.join("conversation").to_string_lossy().into_owned();
6619        let home = root.join("home").to_string_lossy().into_owned();
6620        let mode = AssistantMode {
6621            interpreters: if scripts {
6622                vec!["python3".to_owned()]
6623            } else {
6624                Vec::new()
6625            },
6626            network: ai6::AssistantNetwork {
6627                policy: policy.to_owned(),
6628                allowed_hosts: hosts.iter().map(|host| (*host).to_owned()).collect(),
6629                ..Default::default()
6630            },
6631            files: vec!["personal".to_owned(), "scratch".to_owned()],
6632            read_only: vec![
6633                "shared".to_owned(),
6634                "CLAUDE.md".to_owned(),
6635                "AGENTS.md".to_owned(),
6636            ],
6637            ..AssistantMode::moneypenny()
6638        };
6639        (working_directory, home, mode)
6640    }
6641
6642    /// The argv and environment Claude Code is started with for `mode`.
6643    fn started_with(
6644        working_directory: &str,
6645        mode: AssistantMode,
6646    ) -> (Vec<String>, BTreeMap<String, String>) {
6647        let mut environment = assistant_environment();
6648        environment.insert("ANTHROPIC_API_KEY".to_owned(), "model-key".to_owned());
6649        environment.insert("LANG".to_owned(), "C".to_owned());
6650        // The desk gives each conversation its own configuration directory; the handler denies
6651        // reading it and hides the variable from scripts.
6652        environment.insert(
6653            "CLAUDE_CONFIG_DIR".to_owned(),
6654            format!("{working_directory}.config"),
6655        );
6656        let terminal = ProcessTerminal::new();
6657        let handler = ClaudeHandler::try_from(ClaudeConfig {
6658            executable: "claude-assistant-fixture".to_owned(),
6659            ..ClaudeConfig::default()
6660        })
6661        .unwrap();
6662        let started = handler
6663            .start(
6664                AgentStart {
6665                    mission_id: "assistant-conversation".parse().unwrap(),
6666                    agent_id: "moneypenny".to_owned(),
6667                    prompt: "Work it out.".to_owned(),
6668                    initial_context: Vec::new(),
6669                    working_directory: working_directory.to_owned(),
6670                    clearance: "desk".to_owned(),
6671                    environment,
6672                    model: None,
6673                    effort: None,
6674                    max_cost_micro_usd: None,
6675                    project_settings: false,
6676                    project_mcp: false,
6677                    answer_only: false,
6678                    assistant: Some(mode),
6679                    overlays: Default::default(),
6680                    loadout: Default::default(),
6681                    ledger: None,
6682                },
6683                terminal.clone().into_object(),
6684            )
6685            .unwrap();
6686        read_to_completion(&started);
6687        started.close().unwrap();
6688        let spec = terminal.specs.lock().unwrap().remove(0);
6689        (spec.argv, spec.env.unwrap())
6690    }
6691
6692    fn flag(argv: &[String], flag: &str) -> Option<String> {
6693        argv.iter()
6694            .position(|a| a == flag)
6695            .map(|position| argv[position + 1].clone())
6696    }
6697
6698    /// The `--settings` Claude Code is started with, parsed; `None` when none is passed.
6699    fn settings_of(argv: &[String]) -> Option<Value> {
6700        flag(argv, "--settings").map(|settings| serde_json::from_str(&settings).unwrap())
6701    }
6702
6703    /// The string members of a JSON array.
6704    fn strings(value: &Value) -> Vec<String> {
6705        value
6706            .as_array()
6707            .unwrap_or(&Vec::new())
6708            .iter()
6709            .map(|item| item.as_str().unwrap_or_default().to_owned())
6710            .collect()
6711    }
6712
6713    /// Each network policy with and without scripts, as code.claude.com/docs/en/sandboxing,
6714    /// /permissions and /settings-reference describe the flags and keys. Reads are denied
6715    /// everywhere but the working directory and the platform's paths an interpreter needs, and
6716    /// with no deny list nothing is refused, under `open` too.
6717    #[test]
6718    fn scripts_and_the_network_policy_give_exactly_their_tools_rules_and_sandbox() {
6719        let files = "mcp__moneypenny,Read,Glob,Grep,Edit(/personal/**),Edit(/scratch/**)";
6720        let dots = "Edit(**/.*),Edit(**/.*/**)";
6721        // (policy, hosts, scripts, --tools, --disallowedTools, --allowedTools, WebFetch off)
6722        let cases = [
6723            (
6724                "limited",
6725                &["docs.python.org", "*.pypi.org"][..],
6726                true,
6727                "Read,Write,Edit,Glob,Grep,Bash,WebFetch",
6728                format!("PowerShell,NotebookEdit,WebSearch,Task,Agent,TodoWrite,Skill,{dots}"),
6729                format!(
6730                    "{files},Bash(python3 *),WebFetch(domain:docs.python.org),\
6731                     WebFetch(domain:*.pypi.org)"
6732                ),
6733                false,
6734            ),
6735            (
6736                "limited",
6737                &["docs.python.org", "*.pypi.org"][..],
6738                false,
6739                "Read,Write,Edit,Glob,Grep,WebFetch",
6740                format!("Bash,PowerShell,NotebookEdit,WebSearch,Task,Agent,TodoWrite,Skill,{dots}"),
6741                format!("{files},WebFetch(domain:docs.python.org),WebFetch(domain:*.pypi.org)"),
6742                false,
6743            ),
6744            (
6745                "denied",
6746                &[][..],
6747                true,
6748                "Read,Write,Edit,Glob,Grep,Bash",
6749                format!(
6750                    "PowerShell,NotebookEdit,WebFetch,WebSearch,Task,Agent,TodoWrite,Skill,{dots}"
6751                ),
6752                format!("{files},Bash(python3 *)"),
6753                true,
6754            ),
6755            (
6756                "denied",
6757                &[][..],
6758                false,
6759                "Read,Write,Edit,Glob,Grep",
6760                format!(
6761                    "Bash,PowerShell,NotebookEdit,WebFetch,WebSearch,Task,Agent,TodoWrite,Skill,\
6762                     {dots}"
6763                ),
6764                files.to_owned(),
6765                true,
6766            ),
6767            (
6768                "open",
6769                &[][..],
6770                true,
6771                "Read,Write,Edit,Glob,Grep,Bash,WebFetch,WebSearch",
6772                format!("PowerShell,NotebookEdit,Task,Agent,TodoWrite,Skill,{dots}"),
6773                format!("{files},Bash(python3 *),WebFetch(domain:*),WebSearch"),
6774                false,
6775            ),
6776            (
6777                "open",
6778                &[][..],
6779                false,
6780                "Read,Write,Edit,Glob,Grep,WebFetch,WebSearch",
6781                format!("Bash,PowerShell,NotebookEdit,Task,Agent,TodoWrite,Skill,{dots}"),
6782                format!("{files},WebFetch(domain:*),WebSearch"),
6783                false,
6784            ),
6785        ];
6786        for (policy, hosts, scripts, tools, denied, allowed, fetch_off) in cases {
6787            let case = format!("{policy} {hosts:?} scripts={scripts}");
6788            let (working_directory, _home, mode) = script_mode(policy, hosts, scripts);
6789            let (argv, environment) = started_with(&working_directory, mode);
6790            assert_eq!(flag(&argv, "--tools").as_deref(), Some(tools), "{case}");
6791            assert_eq!(flag(&argv, "--permission-mode").as_deref(), Some("dontAsk"));
6792            assert_eq!(flag(&argv, "--disallowedTools"), Some(denied), "{case}");
6793            assert_eq!(flag(&argv, "--allowedTools"), Some(allowed), "{case}");
6794            assert_eq!(
6795                environment.get(DISABLE_WEB_FETCH_ENV).map(String::as_str),
6796                fetch_off.then_some("1"),
6797                "{case}"
6798            );
6799            // `--settings` is present when there is a sandbox (scripts) or a WebFetch gate
6800            // (any policy but `denied`); `denied` with no scripts has neither.
6801            let has_settings = scripts || policy != "denied";
6802            let settings = settings_of(&argv);
6803            assert_eq!(settings.is_some(), has_settings, "{case}");
6804            let Some(settings) = settings else {
6805                continue;
6806            };
6807            let under = |path: &str| {
6808                std::path::Path::new(&working_directory)
6809                    .join(path)
6810                    .to_string_lossy()
6811                    .into_owned()
6812            };
6813            if scripts {
6814                let fs = &settings["sandbox"]["filesystem"];
6815                assert_eq!(settings["sandbox"]["enabled"], json!(true), "{case}");
6816                assert_eq!(
6817                    settings["sandbox"]["failIfUnavailable"],
6818                    json!(true),
6819                    "{case}"
6820                );
6821                let deny_read = strings(&fs["denyRead"]);
6822                assert_eq!(deny_read[0], "/", "reads denied everywhere: {case}");
6823                let station =
6824                    programs::station_paths(std::path::Path::new(&working_directory), &[], &[]);
6825                assert!(!station.is_empty(), "{case}");
6826                for path in station {
6827                    let path = path.to_string_lossy().into_owned();
6828                    assert!(deny_read.contains(&path), "{case}: {path} denied again");
6829                }
6830                let allow_read = strings(&fs["allowRead"]);
6831                assert!(
6832                    allow_read.contains(&working_directory),
6833                    "{case}: {allow_read:?}"
6834                );
6835                for root in script_read_roots(std::env::consts::OS) {
6836                    assert!(allow_read.contains(&(*root).to_owned()), "{case}: {root}");
6837                }
6838                for wide in [
6839                    "/etc",
6840                    "/opt",
6841                    "/dev",
6842                    "/var",
6843                    "/Library",
6844                    "/proc",
6845                    "/private/var/db",
6846                ] {
6847                    assert!(
6848                        !allow_read.iter().any(|dir| dir == wide),
6849                        "{case}: {wide} is not re-opened whole"
6850                    );
6851                }
6852                assert_eq!(
6853                    strings(&fs["allowWrite"]),
6854                    [under("personal"), under("scratch")],
6855                    "{case}"
6856                );
6857                let deny_write = strings(&fs["denyWrite"]);
6858                for path in [
6859                    under("shared"),
6860                    under("CLAUDE.md"),
6861                    under("AGENTS.md"),
6862                    under(".claude"),
6863                    under(".git"),
6864                    under("personal/.git"),
6865                    under("scratch/.git"),
6866                ] {
6867                    assert!(deny_write.contains(&path), "{case}: {path}");
6868                }
6869                let listed: &[&str] = match policy {
6870                    "limited" => hosts,
6871                    "open" => &["*"],
6872                    _ => &[],
6873                };
6874                assert_eq!(
6875                    strings(&settings["sandbox"]["network"]["allowedDomains"]),
6876                    listed,
6877                    "{case}"
6878                );
6879                assert!(
6880                    strings(&settings["sandbox"]["network"]["deniedDomains"]).is_empty(),
6881                    "{case}: no deny list, nothing denied"
6882                );
6883                assert_eq!(
6884                    settings["sandbox"]["network"]["strictAllowlist"],
6885                    json!(true),
6886                    "{case}"
6887                );
6888                let hidden: Vec<String> = settings["sandbox"]["credentials"]["envVars"]
6889                    .as_array()
6890                    .unwrap()
6891                    .iter()
6892                    .map(|entry| entry["name"].as_str().unwrap().to_owned())
6893                    .collect();
6894                for name in [
6895                    "ANTHROPIC_API_KEY",
6896                    "AI6_MONEYPENNY_MCP_TOKEN",
6897                    "CLAUDE_CONFIG_DIR",
6898                ] {
6899                    assert!(hidden.contains(&name.to_owned()), "{case}: {name} hidden");
6900                }
6901                let files: Vec<String> = settings["sandbox"]["credentials"]["files"]
6902                    .as_array()
6903                    .unwrap()
6904                    .iter()
6905                    .map(|entry| entry["path"].as_str().unwrap().to_owned())
6906                    .collect();
6907                assert!(
6908                    files.iter().any(|path| path.ends_with(".config")),
6909                    "{case}: the config dir is a denied file: {files:?}"
6910                );
6911                assert_eq!(
6912                    settings["permissions"]["blockReadsOutsideWorkingDirectories"],
6913                    json!(true),
6914                    "{case}"
6915                );
6916            } else {
6917                assert!(
6918                    settings.get("sandbox").is_none(),
6919                    "no sandbox without scripts: {case}"
6920                );
6921            }
6922            // Every policy but `denied` gates WebFetch; with no deny list it passes none.
6923            let hooks = settings.pointer("/hooks/PreToolUse");
6924            if policy == "denied" {
6925                assert!(hooks.is_none(), "no WebFetch under denied: {case}");
6926            } else {
6927                let args = strings(&hooks.unwrap()[0]["hooks"][0]["args"]);
6928                assert_eq!(&args[..2], ["assistant", "web-gate"], "{case}");
6929                assert!(
6930                    !args.iter().any(|arg| arg == "--deny"),
6931                    "{case}: no deny list"
6932                );
6933                assert_eq!(
6934                    args.iter().any(|arg| arg == "--hosts"),
6935                    policy == "limited",
6936                    "{case}: an allow list only under limited"
6937                );
6938            }
6939            assert!(
6940                !argv
6941                    .iter()
6942                    .any(|a| a.contains("conversation-token") || a.contains("model-key")),
6943                "secrets stay out of the command line: {case}"
6944            );
6945        }
6946    }
6947
6948    /// Without a workspace, scripts and the web still get their tools, and an assistant whose
6949    /// network reaches no host and runs no script keeps `--tools=` with no permission mode.
6950    #[test]
6951    fn scripts_without_a_workspace_and_a_mode_with_nothing_built_in() {
6952        let mode = AssistantMode {
6953            interpreters: vec!["python3".to_owned(), "node".to_owned()],
6954            network: ai6::AssistantNetwork {
6955                policy: "limited".to_owned(),
6956                allowed_hosts: vec!["docs.python.org".to_owned()],
6957                ..Default::default()
6958            },
6959            ..AssistantMode::moneypenny()
6960        };
6961        let (argv, environment) = started_with("/conversation", mode);
6962        assert_eq!(flag(&argv, "--tools").as_deref(), Some("Bash,WebFetch"));
6963        assert_eq!(
6964            flag(&argv, "--allowedTools").as_deref(),
6965            Some("mcp__moneypenny,Bash(python3 *),Bash(node *),WebFetch(domain:docs.python.org)")
6966        );
6967        assert!(
6968            !flag(&argv, "--disallowedTools")
6969                .unwrap()
6970                .contains("Edit(**/.*)")
6971        );
6972        let settings: Value = serde_json::from_str(&flag(&argv, "--settings").unwrap()).unwrap();
6973        // No workspace: nothing writable, but reads are still denied everywhere but the system
6974        // directories, and the WebFetch gate still applies.
6975        assert_eq!(settings["sandbox"]["filesystem"]["allowWrite"], json!([]));
6976        assert_eq!(settings["sandbox"]["filesystem"]["denyRead"][0], json!("/"));
6977        let allow_read = strings(&settings["sandbox"]["filesystem"]["allowRead"]);
6978        for root in script_read_roots(std::env::consts::OS) {
6979            assert!(allow_read.contains(&(*root).to_owned()), "{root}");
6980        }
6981        assert!(
6982            settings.pointer("/hooks/PreToolUse").is_some(),
6983            "the web gate"
6984        );
6985        assert_eq!(environment.get(DISABLE_WEB_FETCH_ENV), None);
6986
6987        let (argv, environment) = started_with("/conversation", AssistantMode::moneypenny());
6988        assert!(argv.iter().any(|a| a == "--tools="), "{argv:?}");
6989        assert_eq!(flag(&argv, "--permission-mode"), None);
6990        assert_eq!(flag(&argv, "--settings"), None);
6991        assert_eq!(
6992            environment.get(DISABLE_WEB_FETCH_ENV).map(String::as_str),
6993            Some("1"),
6994            "limited with no host reaches nothing"
6995        );
6996    }
6997
6998    #[test]
6999    fn managed_settings_are_found_in_each_platforms_system_directory() {
7000        let only = |wanted: &'static str| move |path: &std::path::Path| path.ends_with(wanted);
7001        assert_eq!(
7002            managed_settings_at("linux", only("managed-settings.json")),
7003            Some(std::path::PathBuf::from(
7004                "/etc/claude-code/managed-settings.json"
7005            ))
7006        );
7007        assert_eq!(
7008            managed_settings_at("macos", only("managed-settings.d")),
7009            Some(
7010                std::path::Path::new("/Library/Application Support/ClaudeCode")
7011                    .join("managed-settings.d")
7012            )
7013        );
7014        assert!(managed_settings_at("windows", only("managed-settings.json")).is_some());
7015        assert_eq!(
7016            managed_settings_at("linux", |_: &std::path::Path| false),
7017            None
7018        );
7019        assert_eq!(
7020            managed_settings_at("freebsd", |_: &std::path::Path| true),
7021            None
7022        );
7023    }
7024
7025    /// Reads are denied everywhere but the sandbox's own relay sockets in `/tmp`, and, with a
7026    /// temporary directory of the Run's own, the relay sockets there, by name: the whole
7027    /// directory is not re-opened (that covers the writable `$TMPDIR` read-only and `bwrap`
7028    /// fails to start).
7029    #[test]
7030    fn the_network_relay_sockets_are_the_only_temp_paths_reopened() {
7031        let (working_directory, _, mode) = script_mode("limited", &["docs.python.org"], true);
7032        let mut environment = assistant_environment();
7033        let base = std::env::temp_dir()
7034            .join("conv.t")
7035            .to_string_lossy()
7036            .into_owned();
7037        environment.insert("CLAUDE_CODE_TMPDIR".to_owned(), base.clone());
7038        let settings: Value = serde_json::from_str(
7039            &script_settings(&mode, &working_directory, &environment)
7040                .unwrap()
7041                .to_text(),
7042        )
7043        .unwrap();
7044        let allow_read = strings(&settings["sandbox"]["filesystem"]["allowRead"]);
7045        let under = |name: &str| {
7046            std::path::Path::new(&base)
7047                .join(name)
7048                .to_string_lossy()
7049                .into_owned()
7050        };
7051        assert!(
7052            allow_read.contains(&under("claude-http-*.sock")),
7053            "{allow_read:?}"
7054        );
7055        assert!(
7056            allow_read.contains(&under("srt-mux-*.sock")),
7057            "{allow_read:?}"
7058        );
7059        assert!(
7060            !allow_read.contains(&base),
7061            "not the whole directory: {allow_read:?}"
7062        );
7063        if cfg!(target_os = "linux") {
7064            assert!(allow_read.contains(&"/tmp/claude-http-*.sock".to_owned()));
7065            assert!(!allow_read.contains(&"/tmp".to_owned()), "not all of /tmp");
7066        }
7067    }
7068
7069    /// A deny list reaches the sandbox as the names and single addresses it holds and the
7070    /// WebFetch gate whole; with scripts that reach a host, a network or a range category is
7071    /// refused, since the sandbox's proxy matches names and single addresses only (measured with
7072    /// Claude Code 2.1.310: `127.0.0.0/8` in `deniedDomains` left `127.0.0.2` reachable).
7073    #[test]
7074    fn a_deny_list_reaches_the_sandbox_and_the_gate_and_a_range_with_scripts_is_refused() {
7075        let (working_directory, _, mut mode) = script_mode("open", &[], true);
7076        mode.network.denied = vec![
7077            "metadata".to_owned(),
7078            "intranet.example".to_owned(),
7079            "192.0.2.7".to_owned(),
7080        ];
7081        let (argv, _) = started_with(&working_directory, mode.clone());
7082        let settings = settings_of(&argv).unwrap();
7083        assert_eq!(
7084            strings(&settings["sandbox"]["network"]["deniedDomains"]),
7085            [
7086                "169.254.169.254",
7087                "192.0.2.7",
7088                "[fd00:ec2::254]",
7089                "intranet.example",
7090                "metadata.google.internal",
7091            ]
7092        );
7093        let args = strings(&settings.pointer("/hooks/PreToolUse").unwrap()[0]["hooks"][0]["args"]);
7094        let at = args.iter().position(|arg| arg == "--deny").unwrap();
7095        assert_eq!(args[at + 1], "metadata,intranet.example,192.0.2.7");
7096
7097        for range in ["loopback", "private", "10.0.0.0/8"] {
7098            let mut ranged = mode.clone();
7099            ranged.network.denied = vec![range.to_owned()];
7100            let mut argv = Vec::new();
7101            let error = add_assistant(
7102                &mut argv,
7103                &assistant_environment(),
7104                &working_directory,
7105                &ranged,
7106            )
7107            .unwrap_err();
7108            assert!(
7109                error.to_string().contains("by name and by single address"),
7110                "{range}: {error}"
7111            );
7112            // Without scripts only the gate holds the list, and it resolves names itself.
7113            ranged.interpreters.clear();
7114            let mut argv = Vec::new();
7115            add_assistant(
7116                &mut argv,
7117                &assistant_environment(),
7118                &working_directory,
7119                &ranged,
7120            )
7121            .unwrap();
7122            // A network that reaches nothing cannot reach a range either.
7123            let mut quiet = mode.clone();
7124            quiet.network.policy = "denied".to_owned();
7125            quiet.network.denied = vec![range.to_owned()];
7126            let mut argv = Vec::new();
7127            add_assistant(
7128                &mut argv,
7129                &assistant_environment(),
7130                &working_directory,
7131                &quiet,
7132            )
7133            .unwrap();
7134        }
7135    }
7136
7137    /// A variable `credentials.envVars` cannot name would reach scripts, so the start is
7138    /// refused rather than the variable silently left visible.
7139    #[test]
7140    fn an_environment_variable_the_sandbox_cannot_hide_is_refused() {
7141        let (working_directory, _, mode) = script_mode("limited", &[], true);
7142        let mut environment = assistant_environment();
7143        environment.insert("SECRET-TOKEN".to_owned(), "x".to_owned());
7144        let mut argv = Vec::new();
7145        let error = add_assistant(&mut argv, &environment, &working_directory, &mode).unwrap_err();
7146        assert!(error.to_string().contains("SECRET-TOKEN"), "{error}");
7147        let mut unsandboxed = mode.clone();
7148        unsandboxed.unsandboxed = true;
7149        let mut argv = Vec::new();
7150        add_assistant(&mut argv, &environment, &working_directory, &unsandboxed).unwrap();
7151    }
7152
7153    /// The configuration directory the desk sets is denied to scripts twice over: it is not in
7154    /// `allowRead` (reads are denied everywhere else), and it is a `credentials.files` deny
7155    /// entry, so a stored login and other conversations' transcripts stay unreadable.
7156    #[test]
7157    fn the_config_directory_is_denied_to_scripts() {
7158        let (working_directory, _, mode) = script_mode("denied", &[], true);
7159        let (argv, _) = started_with(&working_directory, mode);
7160        let settings: Value = serde_json::from_str(&flag(&argv, "--settings").unwrap()).unwrap();
7161        let allow_read = strings(&settings["sandbox"]["filesystem"]["allowRead"]);
7162        let config = format!("{working_directory}.config");
7163        assert!(
7164            !allow_read.contains(&config),
7165            "the config dir is not readable: {allow_read:?}"
7166        );
7167        let files: Vec<String> = settings["sandbox"]["credentials"]["files"]
7168            .as_array()
7169            .unwrap()
7170            .iter()
7171            .map(|entry| entry["path"].as_str().unwrap().to_owned())
7172            .collect();
7173        assert!(
7174            files.contains(&config),
7175            "the config dir is a denied file: {files:?}"
7176        );
7177    }
7178
7179    /// With `unsandboxed`, scripts run with the sandbox off; Bash is still allowed only for
7180    /// the interpreters.
7181    #[test]
7182    fn unsandboxed_scripts_turn_the_sandbox_off_and_keep_the_interpreter_rules() {
7183        let (working_directory, _, mut mode) = script_mode("limited", &[], true);
7184        mode.unsandboxed = true;
7185        let (argv, _) = started_with(&working_directory, mode);
7186        let settings: Value = serde_json::from_str(&flag(&argv, "--settings").unwrap()).unwrap();
7187        assert_eq!(
7188            settings,
7189            json!({
7190                "sandbox": { "enabled": false },
7191                "permissions": { "blockReadsOutsideWorkingDirectories": true }
7192            })
7193        );
7194        assert!(
7195            flag(&argv, "--allowedTools")
7196                .unwrap()
7197                .contains("Bash(python3 *)")
7198        );
7199    }
7200
7201    #[test]
7202    fn the_sandbox_is_found_on_macos_and_on_linux_with_bwrap_and_socat() {
7203        let bin = std::env::temp_dir().join(format!("ai6-claude-sandbox-{}", std::process::id()));
7204        std::fs::create_dir_all(&bin).unwrap();
7205        std::fs::write(bin.join("bwrap"), "").unwrap();
7206        let path = Some(std::env::join_paths([&bin]).unwrap());
7207        let missing = script_sandbox_missing("linux", path.clone()).unwrap();
7208        assert!(
7209            missing.contains("socat") && !missing.contains("bwrap and"),
7210            "{missing}"
7211        );
7212        std::fs::write(bin.join("socat"), "").unwrap();
7213        assert_eq!(script_sandbox_missing("linux", path.clone()), None);
7214        assert!(script_sandbox_missing("linux", None).is_some());
7215        assert_eq!(script_sandbox_missing("macos", None), None);
7216        let windows = script_sandbox_missing("windows", path).unwrap();
7217        assert!(windows.contains("native Windows"), "{windows}");
7218        assert!(script_sandbox_missing("freebsd", None).is_some());
7219        std::fs::remove_dir_all(&bin).unwrap();
7220        let handler = ClaudeHandler::try_from(ClaudeConfig {
7221            executable: "claude".to_owned(),
7222            ..ClaudeConfig::default()
7223        })
7224        .unwrap();
7225        let here = handler.assistant_scripts(BTreeMap::new()).unwrap();
7226        if cfg!(windows) {
7227            assert!(here.is_some());
7228        }
7229    }
7230
7231    #[test]
7232    fn an_assistant_may_call_the_built_in_tools_its_mode_offers_and_no_other() {
7233        let (_, _, scripts) = script_mode("limited", &["docs.python.org"], true);
7234        let (_, _, denied) = script_mode("denied", &[], false);
7235        let (_, _, open) = script_mode("open", &[], false);
7236        for (mode, tool, ends) in [
7237            (scripts.clone(), "Bash", false),
7238            (scripts.clone(), "WebFetch", false),
7239            (scripts, "WebSearch", true),
7240            (denied.clone(), "Bash", true),
7241            (denied, "WebFetch", true),
7242            (open.clone(), "WebSearch", false),
7243            (open, "PowerShell", true),
7244        ] {
7245            let mut input =
7246                b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"s-1\"}\n".to_vec();
7247            input.extend_from_slice(
7248                format!(
7249                    "{{\"type\":\"assistant\",\"message\":{{\"content\":[{{\"type\":\"tool_use\",\
7250                     \"id\":\"t\",\"name\":\"{tool}\",\"input\":{{}}}}]}}}}\n"
7251                )
7252                .as_bytes(),
7253            );
7254            input.extend_from_slice(b"{\"type\":\"result\",\"result\":\"done\"}\n");
7255            let run = restricted_run(input, restriction(false, Some(&mode)));
7256            let kinds = std::iter::from_fn(|| run.next_event(400).unwrap())
7257                .map(|event| event.kind)
7258                .collect::<Vec<_>>();
7259            assert_eq!(
7260                kinds.contains(&"failed".to_owned()),
7261                ends,
7262                "{tool} under {:?} with {:?}: {kinds:?}",
7263                mode.network.policy,
7264                mode.interpreters
7265            );
7266        }
7267    }
7268
7269    #[test]
7270    fn without_a_theater_server_claude_keeps_its_own_tools() {
7271        let mut argv = vec!["claude".to_owned()];
7272        add_mcp(&mut argv, &BTreeMap::new());
7273        assert_eq!(argv, ["claude"]);
7274    }
7275
7276    /// The shape Claude Code 2.1 prints for a finished turn. The field names follow its
7277    /// stream-json output; the figures are invented.
7278    fn result_with_usage() -> Value {
7279        json!({
7280            "type": "result",
7281            "subtype": "success",
7282            "is_error": false,
7283            "result": "done",
7284            "session_id": "claude-session-7",
7285            "total_cost_usd": 0.0123456,
7286            "usage": {
7287                "input_tokens": 12,
7288                "output_tokens": 345,
7289                "cache_creation_input_tokens": 6789,
7290                "cache_read_input_tokens": 101112
7291            }
7292        })
7293    }
7294
7295    #[test]
7296    fn a_result_reports_tokens_and_cost_as_running_totals() {
7297        let event = decoded(&result_with_usage(), b"{}".to_vec()).unwrap();
7298        assert_eq!(event.kind, "completed");
7299        let spend = event.report.unwrap().spend.unwrap();
7300        assert_eq!(
7301            (
7302                spend.input,
7303                spend.output,
7304                spend.cache_read,
7305                spend.cache_write,
7306                spend.cost_micro_usd
7307            ),
7308            (12, 345, 101_112, 6_789, Some(12_346))
7309        );
7310    }
7311
7312    #[test]
7313    fn only_a_result_carries_usage_and_a_cost_alone_is_enough() {
7314        let assistant = json!({ "type": "assistant", "usage": { "input_tokens": 5 } });
7315        assert_eq!(spend_of(&assistant), None);
7316        let bare = json!({ "type": "result", "result": "ok" });
7317        assert_eq!(spend_of(&bare), None);
7318        let cost_only = json!({ "type": "result", "total_cost_usd": 1.5 });
7319        let usage = spend_of(&cost_only).unwrap();
7320        assert_eq!((usage.input, usage.cost_micro_usd), (0, Some(1_500_000)));
7321    }
7322
7323    #[test]
7324    fn a_429_that_states_its_wait_carries_it_as_retry_after() {
7325        let (limit, _) = decode_limit(&json!({
7326            "type": "result",
7327            "is_error": true,
7328            "api_error_status": 429,
7329            "result": "API Error: Request rejected (429) - quota exceeded, retry after 90 seconds",
7330        }))
7331        .expect("a limit");
7332        assert_eq!(limit.retry_after, Some(std::time::Duration::from_secs(90)));
7333    }
7334
7335    #[test]
7336    fn an_assistant_message_names_the_tools_it_calls() {
7337        let value = json!({
7338            "type": "assistant",
7339            "message": { "content": [
7340                { "type": "text", "text": "Fetching the page" },
7341                { "type": "tool_use", "id": "toolu_1", "name": "WebFetch", "input": {} },
7342                { "type": "tool_use", "id": "toolu_2", "name": "mcp__ai6-cables__read_cables", "input": {} }
7343            ] }
7344        });
7345        let event = decoded(&value, b"{}".to_vec()).unwrap();
7346        assert_eq!(event.kind, "tool");
7347        assert_eq!(event.text.as_deref(), Some("Fetching the page"));
7348        assert_eq!(event.tools, ["WebFetch", "mcp__ai6-cables__read_cables"]);
7349        let plain = json!({ "type": "assistant", "message": { "content": [{ "type": "text", "text": "hi" }] } });
7350        let event = decoded(&plain, b"{}".to_vec()).unwrap();
7351        assert_eq!((event.kind.as_str(), event.tools.len()), ("text", 0));
7352        // Blocks the Messages API runs itself (platform.claude.com/docs, advisor tool and MCP
7353        // connector): `server_tool_use`, `mcp_tool_use`. Their results are not calls.
7354        let server = json!({
7355            "type": "assistant",
7356            "message": { "content": [
7357                { "type": "server_tool_use", "id": "srvtoolu_1", "name": "advisor", "input": {} },
7358                { "type": "advisor_tool_result", "tool_use_id": "srvtoolu_1", "content": {} },
7359                { "type": "mcp_tool_use", "id": "mcptoolu_1", "name": "echo", "server_name": "x" }
7360            ] }
7361        });
7362        let event = decoded(&server, b"{}".to_vec()).unwrap();
7363        assert_eq!(event.kind, "tool");
7364        assert_eq!(
7365            event.tools,
7366            ["server_tool_use:advisor", "mcp_tool_use:echo"]
7367        );
7368    }
7369
7370    #[test]
7371    fn a_server_side_tool_call_ends_a_restricted_run() {
7372        for (block, named) in [
7373            (
7374                r#"{"type":"server_tool_use","id":"srvtoolu_1","name":"advisor","input":{}}"#,
7375                "server_tool_use:advisor",
7376            ),
7377            (
7378                r#"{"type":"mcp_tool_use","id":"mcptoolu_1","name":"board","server_name":"moneypenny"}"#,
7379                "mcp_tool_use:board",
7380            ),
7381            (
7382                r#"{"type":"web_search_tool_result","tool_use_id":"srvtoolu_1","content":[]}"#,
7383                "web_search_tool_result",
7384            ),
7385            (
7386                r#"{"type":"code_execution_tool_result","tool_use_id":"srvtoolu_2"}"#,
7387                "code_execution_tool_result",
7388            ),
7389            (
7390                r#"{"type":"container_upload","file_id":"f"}"#,
7391                "container_upload",
7392            ),
7393            (r#"{"text":"no type"}"#, "untyped"),
7394        ] {
7395            let mut input =
7396                b"{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"s-1\"}\n".to_vec();
7397            input.extend_from_slice(
7398                format!("{{\"type\":\"assistant\",\"message\":{{\"content\":[{block}]}}}}\n")
7399                    .as_bytes(),
7400            );
7401            input.extend_from_slice(b"{\"type\":\"result\",\"result\":\"done\"}\n");
7402            let run = restricted_run(
7403                input,
7404                restriction(false, Some(&AssistantMode::moneypenny())),
7405            );
7406            let kinds = std::iter::from_fn(|| run.next_event(400).unwrap())
7407                .map(|event| (event.kind, event.text.unwrap_or_default()))
7408                .collect::<Vec<_>>();
7409            assert_eq!(kinds.len(), 2, "{block}: {kinds:?}");
7410            assert_eq!(kinds[1].0, "failed");
7411            assert!(kinds[1].1.contains(named), "{}", kinds[1].1);
7412        }
7413    }
7414
7415    /// Prose, reasoning and an allowed call pass the tripwire.
7416    #[test]
7417    fn expected_blocks_keep_a_restricted_run_going() {
7418        let message = json!({"type": "assistant", "message": {"content": [
7419            {"type": "thinking", "thinking": "hm"},
7420            {"type": "redacted_thinking", "data": "x"},
7421            {"type": "text", "text": "ok"},
7422            {"type": "tool_use", "id": "t", "name": "mcp__moneypenny__board", "input": {}},
7423        ]}});
7424        assert!(unexpected_blocks(&read_line(&message)).is_empty());
7425        let run = restricted_run(
7426            Vec::new(),
7427            restriction(false, Some(&AssistantMode::moneypenny())),
7428        );
7429        let event = decoded(&message, Vec::new()).unwrap();
7430        assert!(run.shared.tripped(&event, &read_line(&message)).is_none());
7431    }
7432
7433    #[test]
7434    fn a_limit_error_result_keeps_its_usage() {
7435        let mut value = result_with_usage();
7436        value["is_error"] = json!(true);
7437        value["result"] = json!("Claude AI usage limit reached|1790000000");
7438        let event = decoded(&value, b"{}".to_vec()).unwrap();
7439        assert_eq!(event.kind, LIMIT_EVENT);
7440        assert_eq!(event.report.unwrap().spend.unwrap().output, 345);
7441    }
7442
7443    #[test]
7444    fn claude_code_learns_its_usage_only_from_a_turn() {
7445        let handler = ClaudeHandler::try_from(ClaudeConfig::default()).unwrap();
7446        let support = handler.usage_support().unwrap();
7447        assert!(support.needs_turn, "a Station never asks it to read one");
7448        assert!(!support.needs_session);
7449        assert!(support.spend);
7450        assert_eq!(support.sources, [UsageSource::Reported]);
7451    }
7452
7453    #[test]
7454    fn a_spend_ceiling_is_passed_as_max_budget_usd() {
7455        let mut argv = vec!["claude".to_owned()];
7456        add_budget(&mut argv, Some(2_500_007));
7457        assert_eq!(argv[1..], ["--max-budget-usd", "2.500007"]);
7458        let mut none = vec!["claude".to_owned()];
7459        add_budget(&mut none, None);
7460        assert_eq!(none.len(), 1);
7461    }
7462
7463    fn overlay_skill(name: &str, native: bool) -> ai6::OverlaySkill {
7464        ai6::OverlaySkill {
7465            name: name.to_owned(),
7466            overlay: "tools".to_owned(),
7467            description: "Does a thing.".to_owned(),
7468            path: format!("/store/tools/skills/{name}"),
7469            native,
7470        }
7471    }
7472
7473    fn mission_argv(overlays: &RunOverlays, commands: bool) -> Vec<String> {
7474        let mut argv = Vec::new();
7475        add_settings(
7476            &mut argv,
7477            &cable_environment(),
7478            "wd",
7479            Mode {
7480                project_settings: false,
7481                project_mcp: false,
7482                answer_only: false,
7483                commands,
7484                reads_only: false,
7485            },
7486            &ClaudeSettings::default(),
7487            None,
7488            overlays,
7489        )
7490        .unwrap();
7491        argv
7492    }
7493
7494    /// Measured with Claude Code 2.1.318 against a loopback stand-in for the API: under these flags
7495    /// the plugin's skills were listed in the request and launched, at `field` and at `desk`.
7496    #[test]
7497    fn a_missions_overlay_skills_load_from_the_plugin_directory_under_its_rules() {
7498        let overlays = RunOverlays {
7499            roots: vec!["/store/tools".to_owned()],
7500            skills: vec![overlay_skill("review", true), overlay_skill("audit", false)],
7501            plugin_dir: Some("/store/plugin".to_owned()),
7502            ..RunOverlays::default()
7503        };
7504        for commands in [true, false] {
7505            let argv = mission_argv(&overlays, commands);
7506            let (offered, _, allowed) = field_flags(&argv);
7507            assert!(offered.split(',').any(|tool| tool == "Skill"), "{offered}");
7508            assert!(allowed.contains("Skill(ai6:review)"), "{allowed}");
7509            assert!(
7510                !allowed.contains("audit"),
7511                "a routed skill is no rule: {allowed}"
7512            );
7513            assert_eq!(
7514                flag(&argv, "--plugin-dir").as_deref(),
7515                Some("/store/plugin")
7516            );
7517            let settings = settings_of(&argv).unwrap();
7518            assert_eq!(settings["disableSkillShellExecution"], json!(true));
7519            assert!(settings["hooks"]["PreToolUse"].is_array(), "the gate stays");
7520        }
7521        // What it does not load itself is named in its context.
7522        let context = overlays.with_routing(&["standing".to_owned()], true);
7523        assert_eq!(context.len(), 2);
7524        assert!(
7525            context[1].contains("/store/tools/skills/audit/SKILL.md"),
7526            "{context:?}"
7527        );
7528        assert!(!context[1].contains("review"), "{context:?}");
7529    }
7530
7531    fn overlay_hook(event: &str, refuse: bool) -> ai6::RunHook {
7532        ai6::RunHook {
7533            overlay: "guard".to_owned(),
7534            event: event.to_owned(),
7535            argv: vec!["sh".to_owned(), "/store/guard/hook.sh".to_owned()],
7536            root: "/store/guard".to_owned(),
7537            state: "/state/guard".to_owned(),
7538            session: "run-1".to_owned(),
7539            select: None,
7540            sets: Vec::new(),
7541            timeout: 7,
7542            refuse,
7543        }
7544    }
7545
7546    /// Each Claude Code event gets one entry running `ai6 overlay-hook` with that event's hooks,
7547    /// beside the green ink gate's, never in place of it.
7548    #[test]
7549    fn a_missions_overlay_hooks_are_claude_code_hooks_beside_the_green_ink_gate() {
7550        let overlays = RunOverlays {
7551            hooks: vec![
7552                overlay_hook("pre-tool", true),
7553                overlay_hook("session-start", false),
7554                overlay_hook("pre-tool", false),
7555                overlay_hook("cd", false),
7556            ],
7557            ..RunOverlays::default()
7558        };
7559        let argv = mission_argv(&overlays, true);
7560        let settings = settings_of(&argv).unwrap();
7561        assert_eq!(settings["disableAllHooks"], json!(false));
7562        let pre_tool = settings["hooks"]["PreToolUse"].as_array().unwrap();
7563        assert_eq!(
7564            pre_tool.len(),
7565            2,
7566            "the gate and the overlays': {pre_tool:?}"
7567        );
7568        assert_eq!(
7569            pre_tool[0]["matcher"], "Bash|PowerShell",
7570            "the gate is first"
7571        );
7572        let entry = &pre_tool[1];
7573        assert_eq!(entry["matcher"], "*");
7574        let command = &entry["hooks"][0];
7575        assert_eq!(command["onFailure"], "block", "a guard fails closed");
7576        assert_eq!(command["timeout"], 7 + 7 + 5);
7577        let args: Vec<&str> = command["args"]
7578            .as_array()
7579            .unwrap()
7580            .iter()
7581            .map(|arg| arg.as_str().unwrap())
7582            .collect();
7583        assert_eq!(
7584            &args[..4],
7585            ["overlay-hook", "--harness", "claude-code", "--hooks"]
7586        );
7587        let hooks: Vec<ai6::RunHook> = serde_json::from_str(args[4]).unwrap();
7588        assert_eq!(hooks.len(), 2);
7589        assert!(hooks.iter().all(|hook| hook.event == "pre-tool"));
7590        let start = &settings["hooks"]["SessionStart"][0]["hooks"][0];
7591        assert!(start.get("onFailure").is_none());
7592        assert!(
7593            settings["hooks"]["SessionStart"][0]
7594                .get("matcher")
7595                .is_none()
7596        );
7597        assert!(
7598            settings["hooks"].get("CwdChanged").is_none(),
7599            "an event Claude Code has no hook for is not invented"
7600        );
7601    }
7602
7603    #[test]
7604    fn a_mission_with_no_overlay_hook_has_only_the_gate() {
7605        let argv = mission_argv(&RunOverlays::default(), true);
7606        let settings = settings_of(&argv).unwrap();
7607        assert_eq!(settings["hooks"]["PreToolUse"].as_array().unwrap().len(), 1);
7608        assert!(settings["hooks"].get("SessionStart").is_none());
7609    }
7610
7611    #[test]
7612    fn a_mission_with_no_overlay_skill_is_offered_no_skill_tool() {
7613        for overlays in [
7614            RunOverlays::default(),
7615            RunOverlays {
7616                roots: vec!["/store/tools".to_owned()],
7617                skills: vec![overlay_skill("audit", false)],
7618                plugin_dir: None,
7619                ..RunOverlays::default()
7620            },
7621        ] {
7622            let argv = mission_argv(&overlays, true);
7623            let (offered, _, allowed) = field_flags(&argv);
7624            assert!(!offered.contains("Skill"), "{offered}");
7625            assert!(!allowed.contains("Skill"), "{allowed}");
7626            assert_eq!(flag(&argv, "--plugin-dir"), None);
7627            assert_eq!(
7628                settings_of(&argv).unwrap()["disableSkillShellExecution"],
7629                Value::Null
7630            );
7631        }
7632    }
7633
7634    /// The flags Claude Code was launched with for a start with `loadout`, or why it was refused.
7635    fn launched_with(
7636        loadout: ai6::RunLoadout,
7637        clearance: &str,
7638        environment: BTreeMap<String, String>,
7639    ) -> Result<Vec<String>, ProviderError> {
7640        let spec = Arc::new(Mutex::new(None));
7641        let handler = ClaudeHandler::try_from(ClaudeConfig {
7642            executable: "claude-test".to_owned(),
7643            ..ClaudeConfig::default()
7644        })
7645        .unwrap();
7646        let mut request = start_request("", None);
7647        request.loadout = loadout;
7648        request.clearance = clearance.to_owned();
7649        request.environment = environment;
7650        handler.start(
7651            request,
7652            HeldTerminal {
7653                spec: spec.clone(),
7654                input: Vec::new(),
7655                writes: Arc::default(),
7656                hold: Arc::new(AtomicBool::new(true)),
7657            }
7658            .into_object(),
7659        )?;
7660        let argv = spec.lock().unwrap().clone().unwrap().argv;
7661        Ok(argv)
7662    }
7663
7664    fn files_server(deny: &[&str]) -> ai6::LoadoutMcp {
7665        ai6::LoadoutMcp {
7666            name: "files".to_owned(),
7667            command: vec!["mcp-files".to_owned(), "$WORKTREE".to_owned()],
7668            deny: deny.iter().map(|tool| (*tool).to_owned()).collect(),
7669        }
7670    }
7671
7672    #[test]
7673    fn a_missions_loadout_server_is_started_allowed_and_kept_from_its_denied_tools() {
7674        let loadout = ai6::RunLoadout {
7675            mcp_servers: vec![files_server(&["delete"])],
7676            ..ai6::RunLoadout::default()
7677        };
7678        let argv = launched_with(loadout, "field", BTreeMap::new()).unwrap();
7679        let config: Value = serde_json::from_str(&flag(&argv, "--mcp-config").unwrap()).unwrap();
7680        assert_eq!(config["mcpServers"]["files"]["command"], "mcp-files");
7681        assert_eq!(config["mcpServers"]["files"]["args"][0], "/work");
7682        let (_, denied, allowed) = field_flags(&argv);
7683        assert!(
7684            allowed.split(',').any(|rule| rule == "mcp__files"),
7685            "{allowed}"
7686        );
7687        assert!(
7688            denied.split(',').any(|rule| rule == "mcp__files__delete"),
7689            "{denied}"
7690        );
7691        // The positive control: with no loadout there is neither.
7692        let argv = launched_with(ai6::RunLoadout::default(), "field", BTreeMap::new()).unwrap();
7693        assert_eq!(flag(&argv, "--mcp-config"), None);
7694    }
7695
7696    #[test]
7697    fn a_loadout_server_on_a_run_that_works_through_a_theater_is_refused_with_the_reason() {
7698        let loadout = ai6::RunLoadout {
7699            mcp_servers: vec![files_server(&[])],
7700            ..ai6::RunLoadout::default()
7701        };
7702        let environment = BTreeMap::from([
7703            (
7704                "AI6_THEATER_MCP_URL".to_owned(),
7705                "http://127.0.0.1:1/mcp".to_owned(),
7706            ),
7707            ("AI6_THEATER_MCP_TOKEN".to_owned(), "t".to_owned()),
7708        ]);
7709        let Err(error) = launched_with(loadout, "field", environment) else {
7710            panic!("the server would start on the Station");
7711        };
7712        assert!(error.to_string().contains("Theater"), "{error}");
7713    }
7714
7715    #[test]
7716    fn a_loadout_handed_to_a_run_that_reads_only_is_refused_not_dropped() {
7717        let loadout = ai6::RunLoadout {
7718            mcp_servers: vec![files_server(&[])],
7719            ..ai6::RunLoadout::default()
7720        };
7721        assert!(launched_with(loadout, ai6::READ_CLEARANCE, BTreeMap::new()).is_err());
7722    }
7723
7724    #[test]
7725    fn start_with_a_codex_ledger_writes_a_claude_transcript_and_resumes_it() {
7726        let config_dir = tempfile::tempdir().unwrap();
7727        let session = "7a1f0d3e-0c11-4a55-9d1e-2f6c4b8a9e10";
7728        let ledger = ai6::StartLedger::from_text(&format!("{}\n", [r#"{"format":"coqui-acp-history","version":1,"id":"5f0f6d6e-3f3c-4f1a-8a52-1c1e6f0b9a77","origin":{"harness":"codex"}}"#,
7729                r#"{"method":"session/prompt","params":{"prompt":[{"type":"text","text":"fix the parser"}]}}"#,
7730                // The tool call as the Station records it: its title, no input or output.
7731                r#"{"method":"session/update","params":{"update":{"sessionUpdate":"tool_call","toolCallId":"ai6-call-1","title":"Read","kind":"other","status":"completed"}}}"#,
7732                r#"{"method":"session/update","params":{"update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"done"}}}}"#,
7733                r#"{"method":"history/turn_end","params":{"stopReason":"end_turn"}}"#,
7734            ].join("\n"))).unwrap()
7735        .with_session(session);
7736        let spec = Arc::new(Mutex::new(None));
7737        let writes = Arc::new(Mutex::new(Vec::new()));
7738        let hold = Arc::new(AtomicBool::new(false));
7739        let terminal = HeldTerminal {
7740            spec: spec.clone(),
7741            input: format!(
7742                "{{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"{session}\"}}\n"
7743            )
7744            .into_bytes(),
7745            writes: writes.clone(),
7746            hold,
7747        };
7748        let handler = ClaudeHandler::try_from(ClaudeConfig {
7749            executable: "claude-test".to_owned(),
7750            ..ClaudeConfig::default()
7751        })
7752        .unwrap();
7753        let mut request = start_request("continue", None);
7754        request.working_directory = "/work".to_owned();
7755        request.environment.insert(
7756            "CLAUDE_CONFIG_DIR".to_owned(),
7757            config_dir.path().to_string_lossy().into_owned(),
7758        );
7759        request.ledger = Some(ledger);
7760        let run = handler.start(request, terminal.into_object()).unwrap();
7761
7762        let spec = spec.lock().unwrap().clone().unwrap();
7763        assert!(
7764            spec.argv
7765                .iter()
7766                .any(|arg| arg == &format!("--resume={session}")),
7767            "{:?}",
7768            spec.argv
7769        );
7770        let event = run.next_event(2_000).unwrap().unwrap();
7771        assert_eq!(event.kind, "system");
7772        assert_eq!(run.session_id().unwrap().as_deref(), Some(session));
7773
7774        let mut transcripts = Vec::new();
7775        for entry in std::fs::read_dir(config_dir.path().join("projects")).unwrap() {
7776            for file in std::fs::read_dir(entry.unwrap().path()).unwrap() {
7777                transcripts.push(file.unwrap().path());
7778            }
7779        }
7780        assert_eq!(transcripts.len(), 1, "{transcripts:?}");
7781        let body = std::fs::read_to_string(&transcripts[0]).unwrap();
7782        assert!(body.contains("fix the parser"), "{body}");
7783        assert!(body.contains("Read"), "the tool call by its title: {body}");
7784    }
7785}