,
@@ -13135,6 +13139,28 @@ pub enum OptionsUpdateEnvValueMode {
Unknown,
}
+/// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set.
+///
+///
+///
+/// **Experimental.** This type is part of an experimental wire-protocol surface
+/// and may change or be removed in future SDK or CLI releases.
+///
+///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum OptionsUpdateToolFilterPrecedence {
+ /// If availableTools is set, it is the only constraint that applies (excludedTools is ignored). Preserves CLI / pre-existing client behavior. Default.
+ #[serde(rename = "available")]
+ Available,
+ /// A tool is enabled if and only if it matches the allowlist (or the allowlist is unset) AND it does not match the denylist. Makes 'all except X' expressible by combining the two lists.
+ #[serde(rename = "excluded")]
+ Excluded,
+ /// Unknown variant for forward compatibility.
+ #[default]
+ #[serde(other)]
+ Unknown,
+}
+
/// Approve this single request only
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum PermissionDecisionApproveOnceKind {
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
index cad6ee629..98d0a30e0 100644
--- a/rust/src/lib.rs
+++ b/rust/src/lib.rs
@@ -38,6 +38,12 @@ mod wire;
/// Auto-generated protocol types from Copilot JSON Schemas.
pub mod generated;
+/// Client-level mode ([`ClientMode`]) and the [`ToolSet`] builder for
+/// source-qualified tool filter patterns.
+pub mod mode;
+
+pub use mode::{BUILTIN_TOOLS_ISOLATED, ClientMode, ToolSet};
+
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Stdio;
@@ -423,9 +429,24 @@ pub struct ClientOptions {
/// redirect the extraction (e.g. to a session-scoped temp directory in
/// CI runners) without changing the global cache layout.
///
+ /// Override the directory where the bundled CLI binary is extracted on
+ /// first use.
+ ///
+ /// When `None` (the default), the SDK extracts the embedded CLI to
+ /// `/github-copilot-sdk-{version}/copilot[.exe]`,
+ /// where the cache dir is [`dirs::cache_dir()`] —
+ /// `%LOCALAPPDATA%` on Windows, `~/Library/Caches/` on macOS,
+ /// `$XDG_CACHE_HOME` (or `~/.cache/`) on Linux. Use this knob to
+ /// redirect the extraction (e.g. to a session-scoped temp directory in
+ /// CI runners) without changing the global cache layout.
+ ///
/// Ignored when the SDK was built without a bundled CLI (i.e. with
/// `default-features = false` to disable the `bundled-cli` feature).
pub bundled_cli_extract_dir: Option,
+ /// SDK-level mode controlling whether sessions get CLI-style defaults
+ /// (the default) or are stripped to a minimal/safe baseline. See
+ /// [`ClientMode`] for the contract and trade-offs.
+ pub mode: ClientMode,
}
impl std::fmt::Debug for ClientOptions {
@@ -668,6 +689,7 @@ impl Default for ClientOptions {
base_directory: None,
enable_remote_sessions: false,
bundled_cli_extract_dir: None,
+ mode: ClientMode::default(),
}
}
}
@@ -831,6 +853,15 @@ impl ClientOptions {
self.bundled_cli_extract_dir = Some(dir.into());
self
}
+
+ /// Set the SDK [`ClientMode`]. Use [`ClientMode::Empty`] for any
+ /// scenario where CLI-like ambient behavior is unsafe (e.g. multi-user
+ /// servers). Empty mode additionally requires [`Self::base_directory`]
+ /// or [`Self::session_fs`] to be set, validated at [`Client::start`].
+ pub fn with_mode(mut self, mode: ClientMode) -> Self {
+ self.mode = mode;
+ self
+ }
}
/// Validate a [`SessionFsConfig`] before sending `sessionFs.setProvider`.
@@ -904,6 +935,9 @@ struct ClientInner {
/// `None` for stdio and for external-server transport without an
/// explicit token.
effective_connection_token: Option,
+ /// SDK [`ClientMode`] captured at start time. Drives empty-mode safe
+ /// defaults inside `create_session` / `resume_session`.
+ pub(crate) mode: ClientMode,
}
impl Client {
@@ -921,6 +955,16 @@ impl Client {
/// backend.
pub async fn start(options: ClientOptions) -> Result {
let start_time = Instant::now();
+ if options.mode == ClientMode::Empty
+ && options.base_directory.is_none()
+ && options.session_fs.is_none()
+ {
+ return Err(Error::InvalidConfig(
+ "ClientMode::Empty requires either `base_directory` or \
+ `session_fs` to be set (no implicit ~/.copilot fallback)."
+ .to_string(),
+ ));
+ }
if let Some(cfg) = &options.session_fs {
validate_session_fs_config(cfg)?;
}
@@ -1036,6 +1080,7 @@ impl Client {
session_fs_sqlite_declared,
options.on_get_trace_context,
effective_connection_token.clone(),
+ options.mode,
)?
}
Transport::Tcp {
@@ -1062,6 +1107,7 @@ impl Client {
session_fs_sqlite_declared,
options.on_get_trace_context,
effective_connection_token.clone(),
+ options.mode,
)?
}
Transport::Stdio => {
@@ -1079,6 +1125,7 @@ impl Client {
session_fs_sqlite_declared,
options.on_get_trace_context,
effective_connection_token.clone(),
+ options.mode,
)?
}
};
@@ -1126,7 +1173,18 @@ impl Client {
writer: impl AsyncWrite + Unpin + Send + 'static,
cwd: PathBuf,
) -> Result {
- Self::from_transport(reader, writer, None, cwd, None, false, false, None, None)
+ Self::from_transport(
+ reader,
+ writer,
+ None,
+ cwd,
+ None,
+ false,
+ false,
+ None,
+ None,
+ ClientMode::default(),
+ )
}
/// Construct a [`Client`] from raw streams with a
@@ -1153,6 +1211,7 @@ impl Client {
false,
Some(provider),
None,
+ ClientMode::default(),
)
}
@@ -1166,7 +1225,18 @@ impl Client {
cwd: PathBuf,
token: Option,
) -> Result {
- Self::from_transport(reader, writer, None, cwd, None, false, false, None, token)
+ Self::from_transport(
+ reader,
+ writer,
+ None,
+ cwd,
+ None,
+ false,
+ false,
+ None,
+ token,
+ ClientMode::default(),
+ )
}
/// Public test-only wrapper around the random connection-token
@@ -1190,6 +1260,7 @@ impl Client {
session_fs_sqlite_declared: bool,
on_get_trace_context: Option>,
effective_connection_token: Option,
+ mode: ClientMode,
) -> Result {
let setup_start = Instant::now();
let (request_tx, request_rx) = mpsc::unbounded_channel::();
@@ -1221,6 +1292,7 @@ impl Client {
session_fs_sqlite_declared,
on_get_trace_context,
effective_connection_token,
+ mode,
}),
};
client.spawn_lifecycle_dispatcher();
@@ -1308,6 +1380,11 @@ impl Client {
if let Some(dir) = &options.base_directory {
command.env("COPILOT_HOME", dir);
}
+ // Empty mode disables the process-wide system keychain so the CLI
+ // falls back to file-based credentials scoped to COPILOT_HOME.
+ if options.mode == ClientMode::Empty {
+ command.env("COPILOT_DISABLE_KEYTAR", "1");
+ }
if let Transport::Tcp {
connection_token: Some(token),
..
@@ -1489,6 +1566,11 @@ impl Client {
&self.inner.cwd
}
+ /// Returns the SDK [`ClientMode`] this client was started with.
+ pub fn mode(&self) -> ClientMode {
+ self.inner.mode
+ }
+
/// Typed RPC namespace for server-level methods.
///
/// Every protocol method lives here under its schema-aligned path —
@@ -2607,6 +2689,7 @@ mod tests {
session_fs_sqlite_declared: false,
on_get_trace_context: None,
effective_connection_token: None,
+ mode: ClientMode::default(),
}),
}
}
diff --git a/rust/src/mode.rs b/rust/src/mode.rs
new file mode 100644
index 000000000..01d1038b1
--- /dev/null
+++ b/rust/src/mode.rs
@@ -0,0 +1,461 @@
+/*---------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ *--------------------------------------------------------------------------------------------*/
+
+//! Client-level "empty" mode for minimal/safe defaults.
+//!
+//! See the plan in :
+//! [`ClientMode::Empty`] disables ambient CLI-style behavior by default so an
+//! app must explicitly opt back into features. This module exposes the public
+//! enum, the [`ToolSet`] builder for source-qualified tool filter patterns,
+//! and the [`BUILTIN_TOOLS_ISOLATED`] curated allowlist.
+
+use std::collections::HashMap;
+
+use crate::types::{SectionOverride, SystemMessageConfig};
+
+/// Controls SDK defaults for ambient CLI-style behavior.
+///
+/// - [`ClientMode::CopilotCli`] (default): defaults equivalent to Copilot CLI.
+/// Useful when building a coding agent that shares sessions with Copilot CLI.
+/// **Do not use this mode for server-based multi-user applications** — the
+/// default coding agent has tools and capabilities that operate across
+/// sessions and can access the host OS environment.
+/// - [`ClientMode::Empty`]: disables optional features by default. The app
+/// must explicitly opt into anything it needs. Required for any scenario
+/// where CLI-like ambient behavior is unsafe (e.g. multi-user servers).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ClientMode {
+ /// Defaults equivalent to Copilot CLI (the default).
+ #[default]
+ CopilotCli,
+ /// Disables optional features by default; app must opt in explicitly.
+ Empty,
+}
+
+/// Tool name character set enforced by the runtime at every registration
+/// boundary. Mirrors the runtime's `VALID_TOOL_NAME_REGEX`.
+fn is_valid_tool_name(name: &str) -> bool {
+ !name.is_empty()
+ && name
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
+}
+
+fn validate_name(kind: &str, name: &str) -> Result<(), crate::Error> {
+ if name == "*" {
+ return Ok(());
+ }
+ if !is_valid_tool_name(name) {
+ return Err(crate::Error::InvalidConfig(format!(
+ "Invalid {kind} tool name '{name}': tool names must match \
+ /^[a-zA-Z0-9_-]+$/ or be the wildcard '*'."
+ )));
+ }
+ Ok(())
+}
+
+/// Builder that produces source-qualified tool filter strings (e.g.
+/// `"builtin:bash"`, `"mcp:*"`, `"custom:foo"`) for the session's
+/// `available_tools` list.
+///
+/// Tools are classified by the runtime at registration time, not from name
+/// parsing — so `add_builtin("foo")` matches only tools registered as
+/// built-in, even if an MCP server happens to register a tool with the same
+/// wire name.
+///
+/// # Example
+///
+/// ```
+/// # use github_copilot_sdk::mode::{ToolSet, BUILTIN_TOOLS_ISOLATED};
+/// let tools = ToolSet::new()
+/// .add_builtin_many(BUILTIN_TOOLS_ISOLATED)?
+/// .add_mcp("*")?
+/// .add_custom("*")?
+/// .to_vec();
+/// # Ok::<(), github_copilot_sdk::Error>(())
+/// ```
+#[derive(Debug, Clone, Default)]
+pub struct ToolSet {
+ items: Vec,
+}
+
+impl ToolSet {
+ /// Construct an empty tool set.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a single built-in tool pattern. Pass a specific name (e.g.
+ /// `"bash"`) or `"*"` to match all built-in tools.
+ pub fn add_builtin(mut self, name: &str) -> Result {
+ validate_name("builtin", name)?;
+ self.items.push(format!("builtin:{name}"));
+ Ok(self)
+ }
+
+ /// Add a list of built-in tool patterns (e.g. [`BUILTIN_TOOLS_ISOLATED`]).
+ pub fn add_builtin_many(mut self, names: I) -> Result
+ where
+ I: IntoIterator- ,
+ S: AsRef,
+ {
+ for name in names {
+ let name = name.as_ref();
+ validate_name("builtin", name)?;
+ self.items.push(format!("builtin:{name}"));
+ }
+ Ok(self)
+ }
+
+ /// Add a custom tool pattern. Matches tools registered via the SDK's
+ /// `tools` option or via custom agents.
+ pub fn add_custom(mut self, name: &str) -> Result {
+ validate_name("custom", name)?;
+ self.items.push(format!("custom:{name}"));
+ Ok(self)
+ }
+
+ /// Add an MCP tool pattern. Pass the runtime's canonical wire name
+ /// (e.g. `"github-list_issues"`) or `"*"` to match all MCP tools.
+ pub fn add_mcp(mut self, tool_name: &str) -> Result {
+ validate_name("mcp", tool_name)?;
+ self.items.push(format!("mcp:{tool_name}"));
+ Ok(self)
+ }
+
+ /// Returns a defensive copy of the accumulated filter strings.
+ pub fn to_vec(&self) -> Vec {
+ self.items.clone()
+ }
+
+ /// Returns the accumulated filter strings, consuming the builder.
+ pub fn into_vec(self) -> Vec {
+ self.items
+ }
+
+ /// Number of accumulated filter strings.
+ pub fn len(&self) -> usize {
+ self.items.len()
+ }
+
+ /// Returns `true` if no filter strings have been added.
+ pub fn is_empty(&self) -> bool {
+ self.items.is_empty()
+ }
+}
+
+impl From for Vec {
+ fn from(value: ToolSet) -> Self {
+ value.into_vec()
+ }
+}
+
+/// Built-in tools that operate only within the bounds of a single session —
+/// no host filesystem access outside the session, no cross-session state,
+/// no host environment access, no network.
+///
+/// Safe to enable in [`ClientMode::Empty`] scenarios (e.g. multi-tenant
+/// servers) without leaking host capabilities.
+///
+/// **Contract:** tools in this set MUST NOT be extended (even behind options
+/// or args) to read or write state outside the session boundary. Adding
+/// cross-session or host-state behavior to one of these tools is a breaking
+/// change that requires removing it from this set.
+pub const BUILTIN_TOOLS_ISOLATED: &[&str] = &[
+ "ask_user",
+ "task_complete",
+ "exit_plan_mode",
+ "task",
+ "read_agent",
+ "write_agent",
+ "list_agents",
+ "send_inbox",
+ "context_board",
+ "skill",
+];
+
+/// Validate a tool filter list (`available_tools` or `excluded_tools`).
+/// Rejects the bare `"*"` shorthand with a clear error pointing the developer
+/// at the source-qualified forms.
+pub(crate) fn validate_tool_filter_list(
+ field: &str,
+ list: Option<&[String]>,
+) -> Result<(), crate::Error> {
+ let Some(list) = list else { return Ok(()) };
+ for item in list {
+ if item == "*" {
+ return Err(crate::Error::InvalidConfig(format!(
+ "{field} contains a bare '*' which matches no tool. Use \
+ source-qualified wildcards instead: \
+ ToolSet::new().add_builtin(\"*\").add_mcp(\"*\").add_custom(\"*\")."
+ )));
+ }
+ }
+ Ok(())
+}
+
+/// Returns the system message config to use, adjusted for the current mode.
+/// In empty mode we ensure the `environment_context` section is removed
+/// unless the app has already taken control of it.
+pub(crate) fn system_message_for_mode(
+ mode: ClientMode,
+ supplied: Option,
+) -> Option {
+ if mode != ClientMode::Empty {
+ return supplied;
+ }
+ let strip_env = || {
+ let mut sections = HashMap::new();
+ sections.insert(
+ "environment_context".to_string(),
+ SectionOverride {
+ action: Some("remove".to_string()),
+ content: None,
+ },
+ );
+ sections
+ };
+ let Some(supplied) = supplied else {
+ return Some(SystemMessageConfig {
+ mode: Some("customize".to_string()),
+ content: None,
+ sections: Some(strip_env()),
+ });
+ };
+ let mode_str = supplied.mode.as_deref().unwrap_or("append");
+ match mode_str {
+ "replace" => Some(supplied),
+ "customize" => {
+ if supplied
+ .sections
+ .as_ref()
+ .is_some_and(|s| s.contains_key("environment_context"))
+ {
+ Some(supplied)
+ } else {
+ let mut sections = supplied.sections.unwrap_or_default();
+ sections.insert(
+ "environment_context".to_string(),
+ SectionOverride {
+ action: Some("remove".to_string()),
+ content: None,
+ },
+ );
+ Some(SystemMessageConfig {
+ mode: Some("customize".to_string()),
+ content: supplied.content,
+ sections: Some(sections),
+ })
+ }
+ }
+ // "append" or any unrecognized value: promote to customize so we
+ // can also strip environment_context; the runtime appends `content`
+ // to additional instructions either way.
+ _ => Some(SystemMessageConfig {
+ mode: Some("customize".to_string()),
+ content: supplied.content,
+ sections: Some(strip_env()),
+ }),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tool_set_emits_source_qualified_patterns() {
+ let v = ToolSet::new()
+ .add_builtin("bash")
+ .unwrap()
+ .add_builtin("*")
+ .unwrap()
+ .add_custom("foo")
+ .unwrap()
+ .add_custom("*")
+ .unwrap()
+ .add_mcp("github-list_issues")
+ .unwrap()
+ .add_mcp("*")
+ .unwrap()
+ .to_vec();
+ assert_eq!(
+ v,
+ vec![
+ "builtin:bash",
+ "builtin:*",
+ "custom:foo",
+ "custom:*",
+ "mcp:github-list_issues",
+ "mcp:*",
+ ]
+ );
+ }
+
+ #[test]
+ fn tool_set_add_builtin_many() {
+ let v = ToolSet::new()
+ .add_builtin_many(BUILTIN_TOOLS_ISOLATED)
+ .unwrap()
+ .into_vec();
+ assert_eq!(v.len(), BUILTIN_TOOLS_ISOLATED.len());
+ assert_eq!(v[0], format!("builtin:{}", BUILTIN_TOOLS_ISOLATED[0]));
+ }
+
+ #[test]
+ fn tool_set_rejects_invalid_names() {
+ for bad in ["bash!", "with space", "colon:name", "", "wild*card"] {
+ assert!(
+ ToolSet::new().add_builtin(bad).is_err(),
+ "expected '{bad}' to be rejected"
+ );
+ assert!(ToolSet::new().add_custom(bad).is_err());
+ assert!(ToolSet::new().add_mcp(bad).is_err());
+ }
+ }
+
+ #[test]
+ fn tool_set_accepts_wildcard_and_underscores_and_dashes() {
+ assert!(ToolSet::new().add_builtin("*").is_ok());
+ assert!(ToolSet::new().add_mcp("github-list_issues").is_ok());
+ assert!(ToolSet::new().add_custom("A_b-9").is_ok());
+ }
+
+ #[test]
+ fn into_vec_is_idempotent_with_to_vec() {
+ let ts = ToolSet::new().add_builtin("bash").unwrap();
+ assert_eq!(ts.to_vec(), vec!["builtin:bash"]);
+ assert_eq!(ts.into_vec(), vec!["builtin:bash"]);
+ }
+
+ #[test]
+ fn into_vec_string_conversion() {
+ let v: Vec = ToolSet::new().add_mcp("*").unwrap().into();
+ assert_eq!(v, vec!["mcp:*"]);
+ }
+
+ #[test]
+ fn validate_tool_filter_list_rejects_bare_star() {
+ let bad = vec!["*".to_string()];
+ assert!(validate_tool_filter_list("availableTools", Some(&bad)).is_err());
+ }
+
+ #[test]
+ fn validate_tool_filter_list_allows_qualified_star() {
+ let ok = vec!["builtin:*".to_string(), "mcp:*".to_string()];
+ assert!(validate_tool_filter_list("availableTools", Some(&ok)).is_ok());
+ }
+
+ #[test]
+ fn validate_tool_filter_list_none_is_ok() {
+ assert!(validate_tool_filter_list("availableTools", None).is_ok());
+ }
+
+ #[test]
+ fn builtin_tools_isolated_contents() {
+ assert!(BUILTIN_TOOLS_ISOLATED.contains(&"ask_user"));
+ assert!(BUILTIN_TOOLS_ISOLATED.contains(&"task_complete"));
+ assert!(BUILTIN_TOOLS_ISOLATED.contains(&"skill"));
+ assert!(!BUILTIN_TOOLS_ISOLATED.contains(&"bash"));
+ assert!(!BUILTIN_TOOLS_ISOLATED.contains(&"edit"));
+ assert!(!BUILTIN_TOOLS_ISOLATED.contains(&"web_fetch"));
+ }
+
+ #[test]
+ fn client_mode_default_is_copilot_cli() {
+ assert_eq!(ClientMode::default(), ClientMode::CopilotCli);
+ }
+
+ #[test]
+ fn system_message_copilot_cli_passes_through_unchanged() {
+ let cfg = SystemMessageConfig {
+ mode: Some("append".to_string()),
+ content: Some("hello".to_string()),
+ sections: None,
+ };
+ let out = system_message_for_mode(ClientMode::CopilotCli, Some(cfg.clone()));
+ let out = out.unwrap();
+ assert_eq!(out.mode.as_deref(), Some("append"));
+ assert_eq!(out.content.as_deref(), Some("hello"));
+ }
+
+ #[test]
+ fn system_message_empty_none_injects_strip() {
+ let out = system_message_for_mode(ClientMode::Empty, None).unwrap();
+ assert_eq!(out.mode.as_deref(), Some("customize"));
+ let sections = out.sections.unwrap();
+ let env = sections.get("environment_context").unwrap();
+ assert_eq!(env.action.as_deref(), Some("remove"));
+ }
+
+ #[test]
+ fn system_message_empty_append_promoted_to_customize() {
+ let cfg = SystemMessageConfig {
+ mode: Some("append".to_string()),
+ content: Some("hi".to_string()),
+ sections: None,
+ };
+ let out = system_message_for_mode(ClientMode::Empty, Some(cfg)).unwrap();
+ assert_eq!(out.mode.as_deref(), Some("customize"));
+ assert_eq!(out.content.as_deref(), Some("hi"));
+ let sections = out.sections.unwrap();
+ assert!(sections.contains_key("environment_context"));
+ }
+
+ #[test]
+ fn system_message_empty_replace_passes_through() {
+ let cfg = SystemMessageConfig {
+ mode: Some("replace".to_string()),
+ content: Some("verbatim".to_string()),
+ sections: None,
+ };
+ let out = system_message_for_mode(ClientMode::Empty, Some(cfg.clone())).unwrap();
+ assert_eq!(out.mode.as_deref(), Some("replace"));
+ assert_eq!(out.content.as_deref(), Some("verbatim"));
+ assert!(out.sections.is_none());
+ }
+
+ #[test]
+ fn system_message_empty_customize_with_env_context_preserved() {
+ let mut sections = HashMap::new();
+ sections.insert(
+ "environment_context".to_string(),
+ SectionOverride {
+ action: Some("replace".to_string()),
+ content: Some("custom env".to_string()),
+ },
+ );
+ let cfg = SystemMessageConfig {
+ mode: Some("customize".to_string()),
+ content: None,
+ sections: Some(sections),
+ };
+ let out = system_message_for_mode(ClientMode::Empty, Some(cfg)).unwrap();
+ let env = out.sections.unwrap().remove("environment_context").unwrap();
+ assert_eq!(env.action.as_deref(), Some("replace"));
+ assert_eq!(env.content.as_deref(), Some("custom env"));
+ }
+
+ #[test]
+ fn system_message_empty_customize_without_env_context_gets_strip() {
+ let mut sections = HashMap::new();
+ sections.insert(
+ "other_section".to_string(),
+ SectionOverride {
+ action: Some("replace".to_string()),
+ content: Some("body".to_string()),
+ },
+ );
+ let cfg = SystemMessageConfig {
+ mode: Some("customize".to_string()),
+ content: None,
+ sections: Some(sections),
+ };
+ let out = system_message_for_mode(ClientMode::Empty, Some(cfg)).unwrap();
+ let secs = out.sections.unwrap();
+ assert!(secs.contains_key("other_section"));
+ let env = secs.get("environment_context").unwrap();
+ assert_eq!(env.action.as_deref(), Some("remove"));
+ }
+}
diff --git a/rust/src/session.rs b/rust/src/session.rs
index d401a7d45..9e1f444d6 100644
--- a/rust/src/session.rs
+++ b/rust/src/session.rs
@@ -801,6 +801,29 @@ impl Client {
if let Some(transforms) = config.system_message_transform.clone() {
inject_transform_sections(&mut config, transforms.as_ref());
}
+ let mode = self.inner.mode;
+ if mode == crate::ClientMode::Empty && config.available_tools.is_none() {
+ return Err(Error::InvalidConfig(
+ "ClientMode::Empty requires available_tools to be set on the session config. \
+ Use ToolSet to specify which tools the session may use (e.g. \
+ ToolSet::new().add_builtin_many(BUILTIN_TOOLS_ISOLATED))."
+ .to_string(),
+ ));
+ }
+ crate::mode::validate_tool_filter_list(
+ "available_tools",
+ config.available_tools.as_deref(),
+ )?;
+ crate::mode::validate_tool_filter_list("excluded_tools", config.excluded_tools.as_deref())?;
+ config.system_message =
+ crate::mode::system_message_for_mode(mode, config.system_message.take());
+ if mode == crate::ClientMode::Empty && config.enable_session_telemetry.is_none() {
+ config.enable_session_telemetry = Some(false);
+ }
+ let opt_skip_custom_instructions = config.skip_custom_instructions;
+ let opt_custom_agents_local_only = config.custom_agents_local_only;
+ let opt_coauthor_enabled = config.coauthor_enabled;
+ let opt_manage_schedule_enabled = config.manage_schedule_enabled;
let (wire, mut runtime) = config.into_wire(session_id.clone())?;
let permission_handler = crate::permission::resolve_handler(
@@ -907,7 +930,7 @@ impl Client {
"Client::create_session complete"
);
registration.disarm();
- Ok(Session {
+ let session = Session {
id: session_id,
cwd: self.cwd().clone(),
workspace_path: create_result.workspace_path,
@@ -919,7 +942,17 @@ impl Client {
capabilities,
open_canvases: Arc::new(parking_lot::RwLock::new(Vec::new())),
event_tx,
- })
+ };
+ apply_mode_post_create_patch(
+ &session,
+ mode,
+ opt_skip_custom_instructions,
+ opt_custom_agents_local_only,
+ opt_coauthor_enabled,
+ opt_manage_schedule_enabled,
+ )
+ .await?;
+ Ok(session)
}
/// Resume an existing session on the CLI.
@@ -941,6 +974,29 @@ impl Client {
if let Some(transforms) = config.system_message_transform.clone() {
inject_transform_sections_resume(&mut config, transforms.as_ref());
}
+ let mode = self.inner.mode;
+ if mode == crate::ClientMode::Empty && config.available_tools.is_none() {
+ return Err(Error::InvalidConfig(
+ "ClientMode::Empty requires available_tools to be set on the session config. \
+ Use ToolSet to specify which tools the session may use (e.g. \
+ ToolSet::new().add_builtin_many(BUILTIN_TOOLS_ISOLATED))."
+ .to_string(),
+ ));
+ }
+ crate::mode::validate_tool_filter_list(
+ "available_tools",
+ config.available_tools.as_deref(),
+ )?;
+ crate::mode::validate_tool_filter_list("excluded_tools", config.excluded_tools.as_deref())?;
+ config.system_message =
+ crate::mode::system_message_for_mode(mode, config.system_message.take());
+ if mode == crate::ClientMode::Empty && config.enable_session_telemetry.is_none() {
+ config.enable_session_telemetry = Some(false);
+ }
+ let opt_skip_custom_instructions = config.skip_custom_instructions;
+ let opt_custom_agents_local_only = config.custom_agents_local_only;
+ let opt_coauthor_enabled = config.coauthor_enabled;
+ let opt_manage_schedule_enabled = config.manage_schedule_enabled;
let (wire, mut runtime) = config.into_wire()?;
let permission_handler = crate::permission::resolve_handler(
@@ -1080,7 +1136,7 @@ impl Client {
"Client::resume_session complete"
);
registration.disarm();
- Ok(Session {
+ let session = Session {
id: session_id,
cwd: self.cwd().clone(),
workspace_path: resume_result.workspace_path,
@@ -1092,12 +1148,69 @@ impl Client {
capabilities,
open_canvases,
event_tx,
- })
+ };
+ apply_mode_post_create_patch(
+ &session,
+ mode,
+ opt_skip_custom_instructions,
+ opt_custom_agents_local_only,
+ opt_coauthor_enabled,
+ opt_manage_schedule_enabled,
+ )
+ .await?;
+ Ok(session)
}
}
type CommandHandlerMap = HashMap>;
+async fn apply_mode_post_create_patch(
+ session: &Session,
+ mode: crate::ClientMode,
+ opt_skip_custom_instructions: Option,
+ opt_custom_agents_local_only: Option,
+ opt_coauthor_enabled: Option,
+ opt_manage_schedule_enabled: Option,
+) -> Result<(), Error> {
+ use crate::generated::api_types::SessionUpdateOptionsParams;
+ let mut patch = SessionUpdateOptionsParams::default();
+ let should_send = if mode == crate::ClientMode::Empty {
+ patch.skip_custom_instructions = Some(opt_skip_custom_instructions.unwrap_or(true));
+ patch.custom_agents_local_only = Some(opt_custom_agents_local_only.unwrap_or(true));
+ patch.coauthor_enabled = Some(opt_coauthor_enabled.unwrap_or(false));
+ patch.manage_schedule_enabled = Some(opt_manage_schedule_enabled.unwrap_or(false));
+ patch.installed_plugins = Vec::new();
+ true
+ } else {
+ let mut any = false;
+ if let Some(v) = opt_skip_custom_instructions {
+ patch.skip_custom_instructions = Some(v);
+ any = true;
+ }
+ if let Some(v) = opt_custom_agents_local_only {
+ patch.custom_agents_local_only = Some(v);
+ any = true;
+ }
+ if let Some(v) = opt_coauthor_enabled {
+ patch.coauthor_enabled = Some(v);
+ any = true;
+ }
+ if let Some(v) = opt_manage_schedule_enabled {
+ patch.manage_schedule_enabled = Some(v);
+ any = true;
+ }
+ any
+ };
+ if !should_send {
+ return Ok(());
+ }
+ if let Err(error) = session.rpc().options().update(patch).await {
+ let _ = session.disconnect().await;
+ return Err(error);
+ }
+ Ok(())
+}
+
fn build_command_handler_map(commands: Option<&[CommandDefinition]>) -> Arc {
let map = match commands {
Some(commands) => commands
diff --git a/rust/src/types.rs b/rust/src/types.rs
index 6f5c826c6..f9b29600d 100644
--- a/rust/src/types.rs
+++ b/rust/src/types.rs
@@ -1234,6 +1234,22 @@ pub struct SessionConfig {
/// `systemMessage.transform` RPC callbacks to it during the session.
/// Use [`with_system_message_transform`](Self::with_system_message_transform) to install one.
pub system_message_transform: Option>,
+ /// Whether to skip loading custom-instruction sources for this session.
+ /// Applied via `session.options.update` after create/resume. Defaults to
+ /// `true` in [`crate::ClientMode::Empty`] when unset.
+ pub skip_custom_instructions: Option,
+ /// Whether to constrain custom agents to local-only execution. Applied
+ /// via `session.options.update` after create/resume. Defaults to `true`
+ /// in [`crate::ClientMode::Empty`] when unset.
+ pub custom_agents_local_only: Option,
+ /// Whether to include the `Co-authored-by` trailer in commit messages.
+ /// Applied via `session.options.update` after create/resume. Defaults to
+ /// `false` in [`crate::ClientMode::Empty`] when unset.
+ pub coauthor_enabled: Option,
+ /// Whether to expose the `manage_schedule` tool. Applied via
+ /// `session.options.update` after create/resume. Defaults to `false` in
+ /// [`crate::ClientMode::Empty`] when unset.
+ pub manage_schedule_enabled: Option,
}
impl std::fmt::Debug for SessionConfig {
@@ -1369,6 +1385,10 @@ impl Default for SessionConfig {
hooks_handler: None,
permission_policy: None,
system_message_transform: None,
+ skip_custom_instructions: None,
+ custom_agents_local_only: None,
+ coauthor_enabled: None,
+ manage_schedule_enabled: None,
}
}
}
@@ -1456,6 +1476,7 @@ impl SessionConfig {
extension_info: self.extension_info,
available_tools: self.available_tools,
excluded_tools: self.excluded_tools,
+ tool_filter_precedence: "excluded",
mcp_servers: self.mcp_servers,
env_value_mode: "direct",
enable_config_discovery: self.enable_config_discovery,
@@ -1837,6 +1858,30 @@ impl SessionConfig {
self.cloud = Some(cloud);
self
}
+
+ /// Set [`Self::skip_custom_instructions`].
+ pub fn with_skip_custom_instructions(mut self, value: bool) -> Self {
+ self.skip_custom_instructions = Some(value);
+ self
+ }
+
+ /// Set [`Self::custom_agents_local_only`].
+ pub fn with_custom_agents_local_only(mut self, value: bool) -> Self {
+ self.custom_agents_local_only = Some(value);
+ self
+ }
+
+ /// Set [`Self::coauthor_enabled`].
+ pub fn with_coauthor_enabled(mut self, value: bool) -> Self {
+ self.coauthor_enabled = Some(value);
+ self
+ }
+
+ /// Set [`Self::manage_schedule_enabled`].
+ pub fn with_manage_schedule_enabled(mut self, value: bool) -> Self {
+ self.manage_schedule_enabled = Some(value);
+ self
+ }
}
/// Configuration for resuming an existing session via the `session.resume` RPC.
@@ -1965,6 +2010,14 @@ pub struct ResumeSessionConfig {
pub(crate) permission_policy: Option,
/// System-message transform. See [`SessionConfig::system_message_transform`].
pub system_message_transform: Option>,
+ /// See [`SessionConfig::skip_custom_instructions`].
+ pub skip_custom_instructions: Option,
+ /// See [`SessionConfig::custom_agents_local_only`].
+ pub custom_agents_local_only: Option,
+ /// See [`SessionConfig::coauthor_enabled`].
+ pub coauthor_enabled: Option,
+ /// See [`SessionConfig::manage_schedule_enabled`].
+ pub manage_schedule_enabled: Option,
}
impl std::fmt::Debug for ResumeSessionConfig {
@@ -2108,6 +2161,7 @@ impl ResumeSessionConfig {
extension_info: self.extension_info,
available_tools: self.available_tools,
excluded_tools: self.excluded_tools,
+ tool_filter_precedence: "excluded",
mcp_servers: self.mcp_servers,
env_value_mode: "direct",
enable_config_discovery: self.enable_config_discovery,
@@ -2205,6 +2259,10 @@ impl ResumeSessionConfig {
hooks_handler: None,
permission_policy: None,
system_message_transform: None,
+ skip_custom_instructions: None,
+ custom_agents_local_only: None,
+ coauthor_enabled: None,
+ manage_schedule_enabled: None,
}
}
@@ -2531,6 +2589,30 @@ impl ResumeSessionConfig {
self.continue_pending_work = Some(continue_pending);
self
}
+
+ /// Set [`Self::skip_custom_instructions`].
+ pub fn with_skip_custom_instructions(mut self, value: bool) -> Self {
+ self.skip_custom_instructions = Some(value);
+ self
+ }
+
+ /// Set [`Self::custom_agents_local_only`].
+ pub fn with_custom_agents_local_only(mut self, value: bool) -> Self {
+ self.custom_agents_local_only = Some(value);
+ self
+ }
+
+ /// Set [`Self::coauthor_enabled`].
+ pub fn with_coauthor_enabled(mut self, value: bool) -> Self {
+ self.coauthor_enabled = Some(value);
+ self
+ }
+
+ /// Set [`Self::manage_schedule_enabled`].
+ pub fn with_manage_schedule_enabled(mut self, value: bool) -> Self {
+ self.manage_schedule_enabled = Some(value);
+ self
+ }
}
/// Controls how the system message is constructed.
diff --git a/rust/src/wire.rs b/rust/src/wire.rs
index b97aea261..29f89d84d 100644
--- a/rust/src/wire.rs
+++ b/rust/src/wire.rs
@@ -67,6 +67,9 @@ pub(crate) struct SessionCreateWire {
pub available_tools: Option>,
#[serde(skip_serializing_if = "Option::is_none")]
pub excluded_tools: Option>,
+ /// SDK always sends `"excluded"` so include + exclude lists compose
+ /// naturally (everything matching X except Y).
+ pub tool_filter_precedence: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option>,
pub env_value_mode: &'static str,
@@ -143,6 +146,8 @@ pub(crate) struct SessionResumeWire {
pub available_tools: Option>,
#[serde(skip_serializing_if = "Option::is_none")]
pub excluded_tools: Option>,
+ /// SDK always sends `"excluded"`. See create-wire docs.
+ pub tool_filter_precedence: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option>,
pub env_value_mode: &'static str,
diff --git a/rust/tests/e2e.rs b/rust/tests/e2e.rs
index 8589bca47..b24a647cd 100644
--- a/rust/tests/e2e.rs
+++ b/rust/tests/e2e.rs
@@ -33,6 +33,8 @@ mod hooks;
mod hooks_extended;
#[path = "e2e/mcp_and_agents.rs"]
mod mcp_and_agents;
+#[path = "e2e/mode_empty.rs"]
+mod mode_empty;
#[path = "e2e/mode_handlers.rs"]
mod mode_handlers;
#[path = "e2e/multi_client.rs"]
diff --git a/rust/tests/e2e/mode_empty.rs b/rust/tests/e2e/mode_empty.rs
new file mode 100644
index 000000000..9e3e72de5
--- /dev/null
+++ b/rust/tests/e2e/mode_empty.rs
@@ -0,0 +1,378 @@
+//! E2E coverage for `ClientMode::Empty` + `ToolSet` patterns.
+//!
+//! The runtime is mode-agnostic — these tests verify the SDK's
+//! translation reaches the runtime correctly by inspecting the
+//! resulting CapiProxy chat-completion request (the LLM only sees
+//! tools the runtime exposed for the session) and end-to-end behavior.
+//!
+//! Mirrors `nodejs/test/e2e/mode_empty.e2e.test.ts` and shares the
+//! same recorded cassettes under `test/snapshots/mode_empty/`.
+
+use std::sync::Arc;
+
+use github_copilot_sdk::handler::ApproveAllHandler;
+use github_copilot_sdk::types::SystemMessageConfig;
+use github_copilot_sdk::{
+ BUILTIN_TOOLS_ISOLATED, Client, ClientMode, SessionConfig, ToolSet,
+};
+use serde_json::Value;
+
+use super::support::{assistant_message_content, with_e2e_context};
+
+const SHELL_TOOL_NAME: &str = if cfg!(windows) { "powershell" } else { "bash" };
+
+fn isolated_tool_set() -> Vec {
+ ToolSet::new()
+ .add_builtin_many(BUILTIN_TOOLS_ISOLATED.iter().copied())
+ .expect("isolated tool set should be valid")
+ .into()
+}
+
+fn star_builtin_tool_set() -> Vec {
+ ToolSet::new()
+ .add_builtin("*")
+ .expect("builtin wildcard should be valid")
+ .into()
+}
+
+fn tool_names_from_request(exchange: &Value) -> Vec {
+ let Some(tools) = exchange
+ .get("request")
+ .and_then(|r| r.get("tools"))
+ .and_then(|t| t.as_array())
+ else {
+ return Vec::new();
+ };
+ tools
+ .iter()
+ .filter_map(|t| {
+ let type_ok = t.get("type").and_then(Value::as_str) == Some("function");
+ if !type_ok {
+ return None;
+ }
+ t.get("function")
+ .and_then(|f| f.get("name"))
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ })
+ .collect()
+}
+
+fn system_message_from_request(exchange: &Value) -> String {
+ let Some(messages) = exchange
+ .get("request")
+ .and_then(|r| r.get("messages"))
+ .and_then(|m| m.as_array())
+ else {
+ return String::new();
+ };
+ for m in messages {
+ if m.get("role").and_then(Value::as_str) != Some("system") {
+ continue;
+ }
+ let content = m.get("content");
+ if let Some(text) = content.and_then(Value::as_str) {
+ return text.to_owned();
+ }
+ if let Some(parts) = content.and_then(Value::as_array) {
+ return parts
+ .iter()
+ .filter_map(|p| p.get("text").and_then(Value::as_str))
+ .collect::>()
+ .join("\n");
+ }
+ }
+ String::new()
+}
+
+#[tokio::test]
+async fn empty_mode_isolated_set_shell_tool_is_not_exposed() {
+ with_e2e_context(
+ "mode_empty",
+ "empty_mode_isolated_set_shell_tool_is_not_exposed",
+ |ctx| {
+ Box::pin(async move {
+ ctx.set_default_copilot_user();
+ let options = ctx
+ .client_options()
+ .with_mode(ClientMode::Empty)
+ .with_base_directory(ctx.work_dir().to_path_buf());
+ let client = Client::start(options).await.expect("start client");
+ let session = client
+ .create_session(
+ SessionConfig::default()
+ .with_permission_handler(Arc::new(ApproveAllHandler))
+ .with_github_token(super::support::DEFAULT_TEST_TOKEN)
+ .with_available_tools(isolated_tool_set()),
+ )
+ .await
+ .expect("create session");
+
+ let _ = session.send_and_wait("Say hi.").await;
+
+ let exchanges = ctx.exchanges();
+ assert!(!exchanges.is_empty(), "expected at least one exchange");
+ let tool_names = tool_names_from_request(exchanges.last().unwrap());
+ for banned in ["bash", "powershell", "edit", "grep", "web_fetch"] {
+ assert!(
+ !tool_names.iter().any(|n| n == banned),
+ "isolated set must not expose {banned:?}, got {tool_names:?}"
+ );
+ }
+ let any_isolated = BUILTIN_TOOLS_ISOLATED
+ .iter()
+ .any(|n| tool_names.iter().any(|t| t == n));
+ assert!(
+ any_isolated,
+ "expected at least one isolated tool to be registered, got {tool_names:?}"
+ );
+
+ session.disconnect().await.expect("disconnect");
+ client.stop().await.expect("stop");
+ })
+ },
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn empty_mode_builtin_star_exposes_all_built_in_tools() {
+ with_e2e_context(
+ "mode_empty",
+ "empty_mode_builtin_star_exposes_all_built_in_tools",
+ |ctx| {
+ Box::pin(async move {
+ ctx.set_default_copilot_user();
+ let options = ctx
+ .client_options()
+ .with_mode(ClientMode::Empty)
+ .with_base_directory(ctx.work_dir().to_path_buf());
+ let client = Client::start(options).await.expect("start client");
+ let session = client
+ .create_session(
+ SessionConfig::default()
+ .with_permission_handler(Arc::new(ApproveAllHandler))
+ .with_github_token(super::support::DEFAULT_TEST_TOKEN)
+ .with_available_tools(star_builtin_tool_set()),
+ )
+ .await
+ .expect("create session");
+
+ let _ = session.send_and_wait("Say hi.").await;
+
+ let exchanges = ctx.exchanges();
+ let tool_names = tool_names_from_request(exchanges.last().unwrap());
+ assert!(
+ tool_names.iter().any(|n| n == SHELL_TOOL_NAME),
+ "builtin:* should expose {SHELL_TOOL_NAME}, got {tool_names:?}"
+ );
+
+ session.disconnect().await.expect("disconnect");
+ client.stop().await.expect("stop");
+ })
+ },
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn empty_mode_excluded_tools_subtracts_from_available_tools() {
+ with_e2e_context(
+ "mode_empty",
+ "empty_mode_excluded_tools_subtracts_from_available_tools",
+ |ctx| {
+ Box::pin(async move {
+ ctx.set_default_copilot_user();
+ let options = ctx
+ .client_options()
+ .with_mode(ClientMode::Empty)
+ .with_base_directory(ctx.work_dir().to_path_buf());
+ let client = Client::start(options).await.expect("start client");
+ let session = client
+ .create_session(
+ SessionConfig::default()
+ .with_permission_handler(Arc::new(ApproveAllHandler))
+ .with_github_token(super::support::DEFAULT_TEST_TOKEN)
+ .with_available_tools(star_builtin_tool_set())
+ .with_excluded_tools(vec![format!("builtin:{SHELL_TOOL_NAME}")]),
+ )
+ .await
+ .expect("create session");
+
+ let _ = session.send_and_wait("Say hi.").await;
+
+ let exchanges = ctx.exchanges();
+ let tool_names = tool_names_from_request(exchanges.last().unwrap());
+ assert!(
+ !tool_names.iter().any(|n| n == SHELL_TOOL_NAME),
+ "excluded {SHELL_TOOL_NAME} must not be exposed, got {tool_names:?}"
+ );
+ assert!(!tool_names.is_empty());
+
+ session.disconnect().await.expect("disconnect");
+ client.stop().await.expect("stop");
+ })
+ },
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn empty_mode_strips_environment_context_from_the_system_message_by_default() {
+ with_e2e_context(
+ "mode_empty",
+ "empty_mode_strips_environment_context_from_the_system_message_by_default",
+ |ctx| {
+ Box::pin(async move {
+ ctx.set_default_copilot_user();
+ let options = ctx
+ .client_options()
+ .with_mode(ClientMode::Empty)
+ .with_base_directory(ctx.work_dir().to_path_buf());
+ let client = Client::start(options).await.expect("start client");
+ let session = client
+ .create_session(
+ SessionConfig::default()
+ .with_permission_handler(Arc::new(ApproveAllHandler))
+ .with_github_token(super::support::DEFAULT_TEST_TOKEN)
+ .with_available_tools(isolated_tool_set())
+ .with_system_message(
+ SystemMessageConfig::new()
+ .with_mode("customize")
+ .with_content(
+ "If the user asks you to name an element, reply with exactly the single word ARGON in all caps and nothing else.",
+ ),
+ ),
+ )
+ .await
+ .expect("create session");
+
+ let event = session
+ .send_and_wait("Name an element.")
+ .await
+ .expect("send")
+ .expect("assistant message");
+ let content = assistant_message_content(&event);
+ assert!(content.contains("ARGON"), "expected ARGON in reply, got {content:?}");
+
+ let exchanges = ctx.exchanges();
+ let system_message = system_message_from_request(exchanges.last().unwrap());
+ assert!(
+ !system_message.to_lowercase().contains("current working directory:"),
+ "env context should be stripped, got: {system_message}"
+ );
+ assert!(
+ !system_message.to_lowercase().contains("operating system:"),
+ "env context should be stripped, got: {system_message}"
+ );
+
+ session.disconnect().await.expect("disconnect");
+ client.stop().await.expect("stop");
+ })
+ },
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn empty_mode_system_message_replace_llm_follows_caller_content_verbatim() {
+ with_e2e_context(
+ "mode_empty",
+ "empty_mode_system_message_replace_llm_follows_caller_content_verbatim",
+ |ctx| {
+ Box::pin(async move {
+ ctx.set_default_copilot_user();
+ let options = ctx
+ .client_options()
+ .with_mode(ClientMode::Empty)
+ .with_base_directory(ctx.work_dir().to_path_buf());
+ let client = Client::start(options).await.expect("start client");
+ let session = client
+ .create_session(
+ SessionConfig::default()
+ .with_permission_handler(Arc::new(ApproveAllHandler))
+ .with_github_token(super::support::DEFAULT_TEST_TOKEN)
+ .with_available_tools(isolated_tool_set())
+ .with_system_message(
+ SystemMessageConfig::new()
+ .with_mode("replace")
+ .with_content(
+ "You are a test fixture. Whenever the user asks anything, reply with exactly the single word KRYPTON in all caps and nothing else.",
+ ),
+ ),
+ )
+ .await
+ .expect("create session");
+
+ let event = session
+ .send_and_wait("Hello.")
+ .await
+ .expect("send")
+ .expect("assistant message");
+ let content = assistant_message_content(&event);
+ assert!(content.contains("KRYPTON"), "expected KRYPTON in reply, got {content:?}");
+
+ session.disconnect().await.expect("disconnect");
+ client.stop().await.expect("stop");
+ })
+ },
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn empty_mode_append_caller_instruction_takes_effect_and_env_context_stripped() {
+ with_e2e_context(
+ "mode_empty",
+ "empty_mode_append_caller_instruction_takes_effect_and_env_context_stripped",
+ |ctx| {
+ Box::pin(async move {
+ ctx.set_default_copilot_user();
+ let options = ctx
+ .client_options()
+ .with_mode(ClientMode::Empty)
+ .with_base_directory(ctx.work_dir().to_path_buf());
+ let client = Client::start(options).await.expect("start client");
+ let session = client
+ .create_session(
+ SessionConfig::default()
+ .with_permission_handler(Arc::new(ApproveAllHandler))
+ .with_github_token(super::support::DEFAULT_TEST_TOKEN)
+ .with_available_tools(isolated_tool_set())
+ .with_system_message(
+ SystemMessageConfig::new()
+ .with_mode("append")
+ .with_content(
+ "If the user asks you to name a noble gas, reply with exactly the single word XENON in all caps and nothing else.",
+ ),
+ ),
+ )
+ .await
+ .expect("create session");
+
+ let event = session
+ .send_and_wait("Name a noble gas.")
+ .await
+ .expect("send")
+ .expect("assistant message");
+ let content = assistant_message_content(&event);
+ assert!(content.contains("XENON"), "expected XENON in reply, got {content:?}");
+
+ let exchanges = ctx.exchanges();
+ let system_message = system_message_from_request(exchanges.last().unwrap());
+ assert!(
+ !system_message.to_lowercase().contains("current working directory:"),
+ "env context should be stripped, got: {system_message}"
+ );
+ assert!(
+ !system_message.to_lowercase().contains("operating system:"),
+ "env context should be stripped, got: {system_message}"
+ );
+
+ session.disconnect().await.expect("disconnect");
+ client.stop().await.expect("stop");
+ })
+ },
+ )
+ .await;
+}
diff --git a/test/snapshots/mode_empty/empty_mode_append_caller_instruction_takes_effect_and_env_context_stripped.yaml b/test/snapshots/mode_empty/empty_mode_append_caller_instruction_takes_effect_and_env_context_stripped.yaml
new file mode 100644
index 000000000..fac88270d
--- /dev/null
+++ b/test/snapshots/mode_empty/empty_mode_append_caller_instruction_takes_effect_and_env_context_stripped.yaml
@@ -0,0 +1,10 @@
+models:
+ - claude-sonnet-4.5
+conversations:
+ - messages:
+ - role: system
+ content: ${system}
+ - role: user
+ content: Name a noble gas.
+ - role: assistant
+ content: XENON
diff --git a/test/snapshots/mode_empty/empty_mode_builtin_star_exposes_all_built_in_tools.yaml b/test/snapshots/mode_empty/empty_mode_builtin_star_exposes_all_built_in_tools.yaml
new file mode 100644
index 000000000..701fde22e
--- /dev/null
+++ b/test/snapshots/mode_empty/empty_mode_builtin_star_exposes_all_built_in_tools.yaml
@@ -0,0 +1,8 @@
+models:
+ - claude-sonnet-4.5
+conversations:
+ - messages:
+ - role: system
+ content: ${system}
+ - role: user
+ content: Say hi.
diff --git a/test/snapshots/mode_empty/empty_mode_excluded_tools_subtracts_from_available_tools.yaml b/test/snapshots/mode_empty/empty_mode_excluded_tools_subtracts_from_available_tools.yaml
new file mode 100644
index 000000000..701fde22e
--- /dev/null
+++ b/test/snapshots/mode_empty/empty_mode_excluded_tools_subtracts_from_available_tools.yaml
@@ -0,0 +1,8 @@
+models:
+ - claude-sonnet-4.5
+conversations:
+ - messages:
+ - role: system
+ content: ${system}
+ - role: user
+ content: Say hi.
diff --git a/test/snapshots/mode_empty/empty_mode_isolated_set_shell_tool_is_not_exposed.yaml b/test/snapshots/mode_empty/empty_mode_isolated_set_shell_tool_is_not_exposed.yaml
new file mode 100644
index 000000000..701fde22e
--- /dev/null
+++ b/test/snapshots/mode_empty/empty_mode_isolated_set_shell_tool_is_not_exposed.yaml
@@ -0,0 +1,8 @@
+models:
+ - claude-sonnet-4.5
+conversations:
+ - messages:
+ - role: system
+ content: ${system}
+ - role: user
+ content: Say hi.
diff --git a/test/snapshots/mode_empty/empty_mode_strips_environment_context_from_the_system_message_by_default.yaml b/test/snapshots/mode_empty/empty_mode_strips_environment_context_from_the_system_message_by_default.yaml
new file mode 100644
index 000000000..6f23714d9
--- /dev/null
+++ b/test/snapshots/mode_empty/empty_mode_strips_environment_context_from_the_system_message_by_default.yaml
@@ -0,0 +1,10 @@
+models:
+ - claude-sonnet-4.5
+conversations:
+ - messages:
+ - role: system
+ content: ${system}
+ - role: user
+ content: Name an element.
+ - role: assistant
+ content: ARGON
diff --git a/test/snapshots/mode_empty/empty_mode_system_message_replace_llm_follows_caller_content_verbatim.yaml b/test/snapshots/mode_empty/empty_mode_system_message_replace_llm_follows_caller_content_verbatim.yaml
new file mode 100644
index 000000000..5d63a9401
--- /dev/null
+++ b/test/snapshots/mode_empty/empty_mode_system_message_replace_llm_follows_caller_content_verbatim.yaml
@@ -0,0 +1,10 @@
+models:
+ - claude-sonnet-4.5
+conversations:
+ - messages:
+ - role: system
+ content: ${system}
+ - role: user
+ content: Hello.
+ - role: assistant
+ content: KRYPTON