Skip to main content

artifactize_core/llm/claude_agent/
command.rs

1//! How Claude Code is started: its arguments and environment. Claude Code runs with the
2//! user's own login and nothing else of theirs: no settings, hooks, CLAUDE.md, memory,
3//! skills or tools of its own; the only tools are the ones artifactize offers.
4
5use std::{collections::BTreeMap, ffi::OsString};
6
7use serde_json::{Value, json};
8
9use crate::platform::environment;
10
11/// Claude Code's executable, found on `PATH`.
12pub const PROGRAM: &str = "claude";
13/// The MCP server artifactize hosts in this process; Claude Code names its tools
14/// `mcp__artifactize__<tool>`.
15pub const SERVER: &str = "artifactize";
16
17/// What one Claude Code session is started with. A probe sets no model and offers no tools.
18#[derive(Debug, Default)]
19pub struct Launch<'a> {
20    pub model: Option<&'a str>,
21    pub effort: Option<&'a str>,
22    /// Appended to Claude Code's own system prompt.
23    pub system: Option<&'a str>,
24    /// The tools artifactize offers, by their own names.
25    pub tools: Vec<&'a str>,
26    /// The JSON Schema the final answer must match.
27    pub schema: Option<&'a Value>,
28}
29
30impl Launch<'_> {
31    pub fn args(&self) -> Vec<OsString> {
32        let mut args: Vec<String> = [
33            "-p",
34            "--input-format",
35            "stream-json",
36            "--output-format",
37            "stream-json",
38            "--verbose",
39            "--include-partial-messages",
40            // Claude Code's built-in tools are off: only the offered MCP tools are callable.
41            "--tools",
42            "",
43            "--strict-mcp-config",
44            "--permission-mode",
45            "dontAsk",
46            "--setting-sources",
47            "",
48            "--settings",
49            r#"{"disableAllHooks":true}"#,
50            "--no-session-persistence",
51            "--disable-slash-commands",
52            "--no-chrome",
53        ]
54        .map(str::to_owned)
55        .into();
56        if self.model.is_some() {
57            args.extend([
58                "--mcp-config".into(),
59                json!({"mcpServers": {SERVER: {"type": "sdk", "name": SERVER}}}).to_string(),
60            ]);
61        }
62        if !self.tools.is_empty() {
63            let tools: Vec<String> = self.tools.iter().map(|name| tool_name(name)).collect();
64            args.extend(["--allowedTools".into(), tools.join(",")]);
65        }
66        if let Some(model) = self.model {
67            args.extend([
68                "--model".into(),
69                model.into(),
70                "--thinking".into(),
71                "adaptive".into(),
72                "--thinking-display".into(),
73                "summarized".into(),
74            ]);
75        }
76        if let Some(effort) = self.effort {
77            args.extend(["--effort".into(), effort.into()]);
78        }
79        if let Some(system) = self.system {
80            args.extend(["--append-system-prompt".into(), system.into()]);
81        }
82        if let Some(schema) = self.schema {
83            args.extend(["--json-schema".into(), schema.to_string()]);
84        }
85        args.into_iter().map(OsString::from).collect()
86    }
87}
88
89/// The name Claude Code gives an offered tool.
90pub fn tool_name(name: &str) -> String {
91    format!("mcp__{SERVER}__{name}")
92}
93
94/// Removed from the inherited environment: a minimal mode that skips the subscription login,
95/// an effort that would override the declared one, a cap on every tool call, and the marks
96/// of a Claude Code session artifactize itself runs in, which this session is not part of.
97const CLEARED: [&str; 5] = [
98    "CLAUDE_CODE_SIMPLE",
99    "CLAUDE_CODE_EFFORT_LEVEL",
100    "MCP_TOOL_TIMEOUT",
101    "CLAUDECODE",
102    "CLAUDE_CODE_ENTRYPOINT",
103];
104
105/// Set for every session: no CLAUDE.md, auto memory, compaction, away summaries, advisor or
106/// tool search (which would hide the MCP tools); tool results up to 200,000 tokens, as large
107/// as artifactize's own; and none of Claude Code's silent fallbacks, a non-streaming retry
108/// that can leave a tool call unfinished and a switch to another model after a refusal.
109const SET: [(&str, &str); 9] = [
110    ("CLAUDE_CODE_DISABLE_CLAUDE_MDS", "1"),
111    ("CLAUDE_CODE_DISABLE_AUTO_MEMORY", "1"),
112    ("DISABLE_AUTO_COMPACT", "1"),
113    ("CLAUDE_CODE_ENABLE_AWAY_SUMMARY", "0"),
114    ("ENABLE_TOOL_SEARCH", "false"),
115    ("CLAUDE_CODE_DISABLE_ADVISOR_TOOL", "1"),
116    ("MAX_MCP_OUTPUT_TOKENS", "200000"),
117    ("CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK", "1"),
118    ("CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK", "1"),
119];
120
121/// Claude Code's environment: the user's own, as for any command, so every login Claude
122/// Code has (a subscription, an API key, a cloud account) works, with [`CLEARED`] removed
123/// and [`SET`] set.
124pub fn environment(mut inherited: BTreeMap<OsString, OsString>) -> BTreeMap<OsString, OsString> {
125    for name in CLEARED {
126        environment::remove(&mut inherited, name);
127    }
128    for (name, value) in SET {
129        environment::set(&mut inherited, name, value);
130    }
131    inherited
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    fn text(args: &[OsString]) -> Vec<&str> {
139        args.iter().map(|arg| arg.to_str().unwrap()).collect()
140    }
141
142    fn value_of<'a>(args: &'a [&'a str], flag: &str) -> Option<&'a str> {
143        let at = args.iter().position(|arg| *arg == flag)?;
144        args.get(at + 1).copied()
145    }
146
147    #[test]
148    fn a_review_offers_only_its_tools_with_the_declared_model_and_effort() {
149        let schema = json!({"type": "object"});
150        let args = Launch {
151            model: Some("claude-opus-5-5"),
152            effort: Some("high"),
153            system: Some("Review."),
154            tools: vec!["read", "grep"],
155            schema: Some(&schema),
156        }
157        .args();
158        let args = text(&args);
159        assert_eq!(value_of(&args, "--tools"), Some(""));
160        assert_eq!(value_of(&args, "--setting-sources"), Some(""));
161        assert_eq!(value_of(&args, "--permission-mode"), Some("dontAsk"));
162        assert!(args.contains(&"--strict-mcp-config"));
163        assert_eq!(
164            value_of(&args, "--allowedTools"),
165            Some("mcp__artifactize__read,mcp__artifactize__grep")
166        );
167        let servers: Value =
168            serde_json::from_str(value_of(&args, "--mcp-config").unwrap()).unwrap();
169        assert_eq!(
170            servers,
171            json!({"mcpServers": {"artifactize": {"type": "sdk", "name": "artifactize"}}})
172        );
173        assert_eq!(value_of(&args, "--model"), Some("claude-opus-5-5"));
174        assert_eq!(value_of(&args, "--effort"), Some("high"));
175        assert_eq!(value_of(&args, "--thinking"), Some("adaptive"));
176        assert_eq!(value_of(&args, "--thinking-display"), Some("summarized"));
177        assert_eq!(value_of(&args, "--append-system-prompt"), Some("Review."));
178        assert_eq!(
179            value_of(&args, "--json-schema"),
180            Some(r#"{"type":"object"}"#)
181        );
182    }
183
184    #[test]
185    fn a_probe_names_no_model_server_or_tools() {
186        let args = Launch::default().args();
187        let args = text(&args);
188        for flag in ["--model", "--mcp-config", "--allowedTools", "--json-schema"] {
189            assert!(!args.contains(&flag), "{flag}");
190        }
191        assert_eq!(value_of(&args, "--tools"), Some(""));
192    }
193
194    #[test]
195    fn the_environment_keeps_the_login_and_turns_off_the_users_customizations() {
196        let inherited = [
197            ("USER_SETTING", "kept"),
198            ("CLAUDE_CODE_OAUTH_TOKEN", "token"),
199            ("CLAUDE_CODE_SIMPLE", "1"),
200            ("CLAUDE_CODE_EFFORT_LEVEL", "low"),
201            ("CLAUDECODE", "1"),
202            ("ENABLE_TOOL_SEARCH", "true"),
203        ]
204        .into_iter()
205        .map(|(name, value)| (name.into(), value.into()))
206        .collect();
207        let environment = environment(inherited);
208        let get = |name: &str| environment.get(&OsString::from(name)).cloned();
209        assert_eq!(get("USER_SETTING"), Some("kept".into()));
210        assert_eq!(get("CLAUDE_CODE_OAUTH_TOKEN"), Some("token".into()));
211        for cleared in [
212            "CLAUDE_CODE_SIMPLE",
213            "CLAUDE_CODE_EFFORT_LEVEL",
214            "CLAUDECODE",
215        ] {
216            assert_eq!(get(cleared), None, "{cleared}");
217        }
218        assert_eq!(get("ENABLE_TOOL_SEARCH"), Some("false".into()));
219        assert_eq!(get("CLAUDE_CODE_DISABLE_CLAUDE_MDS"), Some("1".into()));
220        assert_eq!(
221            get("CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK"),
222            Some("1".into())
223        );
224    }
225}