Skip to main content

muse_code_sdk/msp/method/lifecycle/
session_config_mt.rs

1// @generated from the MSP stable schema and protocol sources; do not edit by hand.
2
3use serde::Deserialize;
4use serde::Deserializer;
5use serde::Serialize;
6use serde::de::Error as _;
7use std::collections::BTreeMap;
8use std::fmt;
9
10/// the governing rules: a flat settings patch for one session — dotted key
11/// paths in file spelling verbatim (the `settings/*` key-path vocabulary)
12/// mapped to their new absolute scalar values. `null` clears the member to
13/// absent, exactly as a `settings/writeValue` edit does.
14///
15/// Credentials never travel here: a secret-shaped key (by key class, with
16/// a fail-closed default for unrecognized secret-shaped spellings) fails
17/// the decode at the wire boundary, before the value can reach any
18/// settings composition.
19#[derive(Clone, Default, PartialEq, Eq, Serialize)]
20#[serde(transparent)]
21pub struct SessionSettingsOverrides {
22    /// The patch entries, keyed by dotted key path verbatim. Private so
23    /// every construction runs the key-class guard: the wire decoder and
24    /// [`Self::new`] are the only doors, and neither admits a
25    /// secret-shaped key.
26    values: BTreeMap<String, SessionSettingsOverrideValue>,
27}
28
29impl SessionSettingsOverrides {
30    /// The validated constructor: every key must pass the same
31    /// fail-closed guard the wire decoder runs, so no caller can build
32    /// (or mutate into) a patch carrying credential material.
33    pub fn new(
34        values: BTreeMap<String, SessionSettingsOverrideValue>,
35    ) -> Result<Self, &'static str> {
36        for key in values.keys() {
37            validate_override_key(key)?;
38        }
39        Ok(Self { values })
40    }
41
42    /// One entry by dotted key path, if present.
43    pub fn get(&self, key: &str) -> Option<&SessionSettingsOverrideValue> {
44        self.values.get(key)
45    }
46
47    /// The patch entries, read-only.
48    pub fn values(&self) -> &BTreeMap<String, SessionSettingsOverrideValue> {
49        &self.values
50    }
51}
52
53impl fmt::Debug for SessionSettingsOverrides {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        formatter
56            .debug_struct("SessionSettingsOverrides")
57            .field("key_paths", &self.values.keys().collect::<Vec<_>>())
58            .finish()
59    }
60}
61
62impl<'de> Deserialize<'de> for SessionSettingsOverrides {
63    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
64    where
65        D: Deserializer<'de>,
66    {
67        let value = serde_json::Value::deserialize(deserializer)?;
68        let object = value.as_object().ok_or_else(|| {
69            D::Error::custom("session config settingsOverrides must be an object")
70        })?;
71        let mut values = BTreeMap::new();
72        for (key, value) in object {
73            validate_override_key(key).map_err(D::Error::custom)?;
74            let value = match value {
75                serde_json::Value::String(text) => {
76                    SessionSettingsOverrideValue::String(text.clone())
77                }
78                serde_json::Value::Bool(flag) => SessionSettingsOverrideValue::Bool(*flag),
79                serde_json::Value::Null => SessionSettingsOverrideValue::Null,
80                _ => {
81                    return Err(D::Error::custom(
82                        "session config settingsOverrides values must be strings, booleans, or null",
83                    ));
84                }
85            };
86            values.insert(key.clone(), value);
87        }
88        Ok(Self { values })
89    }
90}
91
92/// One `SessionSettingsOverrides` leaf: exactly the `settings/*` write
93/// value domain — a string, a boolean, or `null` for clear-to-absent.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(untagged)]
96pub enum SessionSettingsOverrideValue {
97    /// A string leaf.
98    String(String),
99    /// A boolean leaf.
100    Bool(bool),
101    /// Clear the member to absent; the built-in fallback applies.
102    Null,
103}
104
105fn validate_override_key(key: &str) -> Result<(), &'static str> {
106    if key.trim().is_empty() {
107        return Err("session config settingsOverrides keys must not be blank");
108    }
109    if key.trim() != key {
110        return Err(
111            "session config settingsOverrides keys must not contain surrounding whitespace",
112        );
113    }
114    if key.split('.').any(str::is_empty) {
115        return Err("session config settingsOverrides keys must not contain empty segments");
116    }
117    if is_secret_shaped_key(key) {
118        return Err("session config settingsOverrides contains a secret-shaped key");
119    }
120    Ok(())
121}
122
123/// the governing rules key-class guard, fail-closed by meaning rather than by
124/// one enumerated spelling list: the key is tokenized across `.`/`_`/`-`
125/// separators and camelCase boundaries, then refused when any token, any fused
126/// token containing a secret stem, or any adjacent token pair names credential
127/// material — so `providerApiKey`, `model.access_token`, `x-client-secret`,
128/// `signingPassphrase`, and `bearerTokenValue` all refuse alongside the bare
129/// `api_key` spelling. Bare `*Key` spellings (`signingKey`, `encryptionKey`,
130/// `masterKey`, `sshKey`) and the `pwd`, `jwt`, and `oauth` tokens refuse by
131/// the same class: no legitimate settings key ends in a `key` token or names
132/// any of them.
133fn is_secret_shaped_key(key: &str) -> bool {
134    const SECRET_TOKENS: &[&str] = &[
135        "secret",
136        "secrets",
137        "token",
138        "tokens",
139        "password",
140        "passphrase",
141        "passwd",
142        "pwd",
143        "credential",
144        "credentials",
145        "bearer",
146        "authorization",
147        "auth",
148        "apikey",
149        "privatekey",
150        "accesskey",
151        "cookie",
152        "cookies",
153        "key",
154        "jwt",
155        "oauth",
156    ];
157    const SECRET_STEMS: &[&str] = &[
158        "secret",
159        "password",
160        "passphrase",
161        "passwd",
162        "credential",
163        "token",
164        "apikey",
165    ];
166    let tokens = key_tokens(key);
167    if tokens
168        .iter()
169        .any(|token| SECRET_TOKENS.contains(&token.as_str()))
170    {
171        return true;
172    }
173    if tokens.iter().any(|token| {
174        SECRET_STEMS
175            .iter()
176            .any(|stem| token.len() > stem.len() && token.contains(stem))
177    }) {
178        return true;
179    }
180    if tokens
181        .iter()
182        .any(|token| token.len() > 3 && token.ends_with("key"))
183    {
184        return true;
185    }
186    tokens.windows(2).any(|pair| {
187        matches!(
188            (pair[0].as_str(), pair[1].as_str()),
189            ("api", "key")
190                | ("private", "key")
191                | ("access", "key")
192                | ("client", "secret")
193                | ("shared", "secret")
194        )
195    })
196}
197
198/// Split a dotted key path into lowercase word tokens, breaking on every
199/// non-alphanumeric separator and on camelCase boundaries (including the
200/// acronym boundary in `APIKey` -> `api`, `key`).
201fn key_tokens(key: &str) -> Vec<String> {
202    let mut tokens = Vec::new();
203    for chunk in key.split(|c: char| !c.is_ascii_alphanumeric()) {
204        if chunk.is_empty() {
205            continue;
206        }
207        let chars: Vec<char> = chunk.chars().collect();
208        let mut start = 0;
209        for index in 1..chars.len() {
210            let boundary = (chars[index - 1].is_ascii_lowercase()
211                || chars[index - 1].is_ascii_digit())
212                && chars[index].is_ascii_uppercase()
213                || chars[index - 1].is_ascii_uppercase()
214                    && chars[index].is_ascii_uppercase()
215                    && chars.get(index + 1).is_some_and(|c| c.is_ascii_lowercase());
216            if boundary {
217                tokens.push(
218                    chars[start..index]
219                        .iter()
220                        .collect::<String>()
221                        .to_lowercase(),
222                );
223                start = index;
224            }
225        }
226        tokens.push(chars[start..].iter().collect::<String>().to_lowercase());
227    }
228    tokens
229}
230
231/// the governing rules: the per-session model endpoint transport override,
232/// mirroring the` `EndpointTransportConfig` fields under MSP camelCase wire
233/// names (`base_url` -> `baseUrl`, `http_headers` -> `httpHeaders`, and so on;
234/// the mTLS path fields travel as strings, paths being a host concern). Every
235/// field is optional; all absent is the default transport. Resolution against
236/// managed egress policy is a later slice.
237#[derive(Clone, Default, PartialEq, Eq, Serialize)]
238#[serde(rename_all = "camelCase")]
239pub struct SessionModelEndpointTransportOverride {
240    /// Endpoint base URL. Configuration diagnostics never echo it.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub base_url: Option<String>,
243    /// Closed grant allowing an explicit OpenAI URL to reuse this block.
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub allow_openai: Option<bool>,
246    /// Literal provider request headers.
247    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
248    pub http_headers: BTreeMap<String, String>,
249    /// Provider header name -> environment variable name.
250    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
251    pub env_http_headers: BTreeMap<String, String>,
252    /// An explicit HTTP proxy URL. Diagnostics never echo it.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub proxy: Option<String>,
255    /// Path to the mTLS client certificate (PEM).
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub client_cert: Option<String>,
258    /// Path to the mTLS client private key (PEM).
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub client_key: Option<String>,
261    /// Optional CA bundle (PEM) to trust for the server side.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub ca_bundle: Option<String>,
264    /// Auth mode. Absent = `bearer` (the default transport behavior).
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub auth: Option<SessionEndpointTransportAuthMode>,
267    /// Provider-scoped endpoints. `meta` merges over the fields above;
268    /// `anthropic` is the session's own Anthropic endpoint. Absent: the fields
269    /// above, and the host's Anthropic route.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub providers: Option<super::SessionEndpointProviders>,
272}
273
274impl fmt::Debug for SessionModelEndpointTransportOverride {
275    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
276        formatter
277            .debug_struct("SessionModelEndpointTransportOverride")
278            .field("base_url_present", &self.base_url.is_some())
279            .field("allow_openai", &self.allow_openai)
280            .field("http_header_name_count", &self.http_headers.len())
281            .field("env_http_header_name_count", &self.env_http_headers.len())
282            .field("proxy_present", &self.proxy.is_some())
283            .field("client_cert_present", &self.client_cert.is_some())
284            .field("client_key_present", &self.client_key.is_some())
285            .field("ca_bundle_present", &self.ca_bundle.is_some())
286            .field("auth", &self.auth)
287            .field("providers", &self.providers)
288            .finish()
289    }
290}
291
292impl<'de> Deserialize<'de> for SessionModelEndpointTransportOverride {
293    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
294    where
295        D: Deserializer<'de>,
296    {
297        #[derive(Deserialize)]
298        #[serde(rename_all = "camelCase")]
299        struct Wire {
300            #[serde(default)]
301            base_url: Option<String>,
302            #[serde(default)]
303            allow_openai: Option<bool>,
304            #[serde(default)]
305            http_headers: BTreeMap<String, String>,
306            #[serde(default)]
307            env_http_headers: BTreeMap<String, String>,
308            #[serde(default)]
309            proxy: Option<String>,
310            #[serde(default)]
311            client_cert: Option<String>,
312            #[serde(default)]
313            client_key: Option<String>,
314            #[serde(default)]
315            ca_bundle: Option<String>,
316            #[serde(default)]
317            auth: Option<SessionEndpointTransportAuthMode>,
318            #[serde(default)]
319            providers: Option<super::SessionEndpointProviders>,
320        }
321
322        let value = serde_json::Value::deserialize(deserializer)?;
323        if !value.is_object() {
324            return Err(D::Error::custom(
325                "session config modelEndpointTransportOverride must be an object",
326            ));
327        }
328        let wire: Wire = serde_json::from_value(value).map_err(|_| {
329            D::Error::custom(
330                "session config modelEndpointTransportOverride has a field with the wrong type or an unknown option",
331            )
332        })?;
333        super::session_config_mt_providers::check_header_names(
334            wire.http_headers.keys().chain(wire.env_http_headers.keys()),
335        )
336        .map_err(D::Error::custom)?;
337        Ok(Self {
338            base_url: wire.base_url,
339            allow_openai: wire.allow_openai,
340            http_headers: wire.http_headers,
341            env_http_headers: wire.env_http_headers,
342            proxy: wire.proxy,
343            client_cert: wire.client_cert,
344            client_key: wire.client_key,
345            ca_bundle: wire.ca_bundle,
346            auth: wire.auth,
347            providers: wire.providers,
348        })
349    }
350}
351
352/// How a request to the overridden endpoint authenticates, mirroring the`
353/// `TransportAuthMode` spellings. Closed: an undeclared mode fails the decode
354/// rather than degrading to a default.
355#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
356#[serde(rename_all = "lowercase")]
357pub enum SessionEndpointTransportAuthMode {
358    /// Send the api key as a Bearer credential (the default).
359    #[default]
360    Bearer,
361    /// Send no `Authorization` header; the transport carries identity.
362    None,
363}