Skip to main content

surjection_core/model/
clients.rs

1//! Client ids and `store/clients.toml` preferences (SPEC 5.4, 7.3, 7.5).
2
3use std::borrow::Cow;
4use std::collections::BTreeMap;
5use std::fmt;
6
7use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
8use serde::de::{self, Deserializer, SeqAccess, Visitor};
9use serde::ser::Serializer;
10use serde::{Deserialize, Serialize};
11
12use crate::error::ErrorCode;
13use crate::model::validate::{Diagnostics, at, join};
14use crate::model::{SCHEMA_VERSION, StoreModel};
15
16/// Key accepted in every `client.<id>` table: the native entry name for that
17/// client when it differs from the server id (SPEC 5.1).
18pub const NATIVE_NAME_KEY: &str = "native_name";
19
20/// A client id the adapter table knows, with the native fields a server may
21/// pass through to it in `[client.<id>]`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct KnownClient {
24    pub id: &'static str,
25    /// Native fields with no canonical equivalent (SPEC 7.3). Fields Surjection
26    /// renders itself (transport, env, headers, tool filters, enablement,
27    /// delivery helpers) are not listed.
28    pub passthrough: &'static [&'static str],
29}
30
31const fn client(id: &'static str, passthrough: &'static [&'static str]) -> KnownClient {
32    KnownClient { id, passthrough }
33}
34
35/// Every client id of SPEC 7.3 and 7.5, in table order, with its
36/// passthrough allowlist. Validation reads ids from here because most
37/// clients have no adapter yet; adapters (`crate::adapters`) take their
38/// allowlist from here through [`passthrough_of`], so there is one list.
39pub const KNOWN_CLIENTS: &[KnownClient] = &[
40    // Tier A (Pi is Tier B since 2026-11-21; built with Tier A in M5)
41    client("claude-code", &[]),
42    client("omp", &["timeout", "instructions", "auth", "oauth"]),
43    client("pi", &["exposure", "timeout", "oauth"]),
44    client("codex", &["startup_timeout_sec", "tool_timeout_sec"]),
45    client("claude-desktop", &[]),
46    // Tier B
47    client("copilot", &["oauthClientId"]),
48    client("cursor", &["envFile"]),
49    // Tier C
50    client("gemini", &["timeout", "trust"]),
51    client("antigravity", &["timeoutSeconds"]),
52    client("opencode", &[]),
53    client("grok", &["startup_timeout_sec", "tool_timeout_sec"]),
54    // Tier D
55    client("vscode-legacy", &[]),
56    client("windsurf", &[]),
57    client("devin", &[]),
58    client("augment", &[]),
59    client("cline", &[]),
60    client("roo-code", &[]),
61    client("kilo-code", &[]),
62    client("kiro", &[]),
63    client("junie", &[]),
64    client("droid", &[]),
65    client("commandcode", &[]),
66    client("crush", &[]),
67    client("qoder", &[]),
68    client("trae", &[]),
69    client("trae-cn", &[]),
70    client("codebuddy", &[]),
71    client("iflow", &[]),
72    // A Gemini CLI fork, written through Gemini's mapper.
73    client("qwen-code", &["timeout", "trust"]),
74    client("zencoder", &[]),
75    client("openclaw", &[]),
76    client("mimo-code", &[]),
77    client("workbuddy", &[]),
78    client("zcode", &[]),
79    client("continue", &[]),
80    client("goose", &[]),
81    client("hermes", &[]),
82    client("intellij", &[]),
83];
84
85/// The table entry for `id`, if the client is known.
86pub fn known_client(id: &str) -> Option<&'static KnownClient> {
87    KNOWN_CLIENTS.iter().find(|client| client.id == id)
88}
89
90/// The passthrough allowlist of known client `id`, for the adapter table.
91/// Used in constants, where an unknown id fails the build.
92pub const fn passthrough_of(id: &str) -> &'static [&'static str] {
93    let mut index = 0;
94    while index < KNOWN_CLIENTS.len() {
95        if const_str_eq(KNOWN_CLIENTS[index].id, id) {
96            return KNOWN_CLIENTS[index].passthrough;
97        }
98        index += 1;
99    }
100    panic!("passthrough_of: unknown client id");
101}
102
103const fn const_str_eq(a: &str, b: &str) -> bool {
104    let (a, b) = (a.as_bytes(), b.as_bytes());
105    if a.len() != b.len() {
106        return false;
107    }
108    let mut index = 0;
109    while index < a.len() {
110        if a[index] != b[index] {
111            return false;
112        }
113        index += 1;
114    }
115    true
116}
117
118const ALL_DETECTED: &str = "all-detected";
119
120/// Which clients an item is enabled for: `"all-detected"` or a list of ids.
121/// Unknown ids are kept as written.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum ClientSelection {
124    /// Every detected client whose capabilities fit.
125    AllDetected,
126    List(Vec<String>),
127}
128
129impl Serialize for ClientSelection {
130    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
131        match self {
132            Self::AllDetected => serializer.serialize_str(ALL_DETECTED),
133            Self::List(ids) => ids.serialize(serializer),
134        }
135    }
136}
137
138impl<'de> Deserialize<'de> for ClientSelection {
139    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
140        deserializer.deserialize_any(KeywordOrList {
141            keywords: &[ALL_DETECTED],
142            keyword: |_| ClientSelection::AllDetected,
143            list: ClientSelection::List,
144        })
145    }
146}
147
148impl JsonSchema for ClientSelection {
149    fn schema_name() -> Cow<'static, str> {
150        "ClientSelection".into()
151    }
152
153    fn json_schema(_: &mut SchemaGenerator) -> Schema {
154        json_schema!({
155            "description": "\"all-detected\" or a list of client ids",
156            "oneOf": [
157                { "const": ALL_DETECTED },
158                { "type": "array", "items": { "type": "string" } }
159            ]
160        })
161    }
162}
163
164/// The client list a selection writes after turning `clients` on
165/// (`enabled`) or off, as the app's pill toggles and `surject server
166/// enable|disable` do: a list keeps its order (named clients it lacks are
167/// appended, removed ones dropped, other ids kept as written, including ids
168/// this machine does not know); `all-detected` becomes the list of what it
169/// selects on this machine (`here`) with the change applied; no selection
170/// starts empty. `None` when nothing changes.
171pub fn toggle_clients(
172    current: Option<&ClientSelection>,
173    here: impl FnOnce() -> Vec<String>,
174    clients: &[String],
175    enabled: bool,
176) -> Option<Vec<String>> {
177    let start = match current {
178        Some(ClientSelection::List(ids)) => ids.clone(),
179        Some(ClientSelection::AllDetected) => here(),
180        None => Vec::new(),
181    };
182    let mut next = start.clone();
183    for client in clients {
184        if enabled && !next.contains(client) {
185            next.push(client.clone());
186        } else if !enabled {
187            next.retain(|id| id != client);
188        }
189    }
190    (next != start).then_some(next)
191}
192
193/// VS Code profiles to import: `"default"`, `"all"` or a list of profile ids.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub enum ProfileSelection {
196    Default,
197    All,
198    List(Vec<String>),
199}
200
201impl Serialize for ProfileSelection {
202    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
203        match self {
204            Self::Default => serializer.serialize_str("default"),
205            Self::All => serializer.serialize_str("all"),
206            Self::List(ids) => ids.serialize(serializer),
207        }
208    }
209}
210
211impl<'de> Deserialize<'de> for ProfileSelection {
212    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
213        deserializer.deserialize_any(KeywordOrList {
214            keywords: &["default", "all"],
215            keyword: |keyword| match keyword {
216                "default" => ProfileSelection::Default,
217                _ => ProfileSelection::All,
218            },
219            list: ProfileSelection::List,
220        })
221    }
222}
223
224impl JsonSchema for ProfileSelection {
225    fn schema_name() -> Cow<'static, str> {
226        "ProfileSelection".into()
227    }
228
229    fn json_schema(_: &mut SchemaGenerator) -> Schema {
230        json_schema!({
231            "description": "\"default\", \"all\" or a list of profile ids",
232            "oneOf": [
233                { "enum": ["default", "all"] },
234                { "type": "array", "items": { "type": "string" } }
235            ]
236        })
237    }
238}
239
240/// Accepts one of `keywords` or a list of strings.
241struct KeywordOrList<T> {
242    keywords: &'static [&'static str],
243    /// Builds the value for a matched keyword.
244    keyword: fn(&str) -> T,
245    list: fn(Vec<String>) -> T,
246}
247
248impl<'de, T> Visitor<'de> for KeywordOrList<T> {
249    type Value = T;
250
251    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        let keywords: Vec<String> = self.keywords.iter().map(|k| format!("{k:?}")).collect();
253        write!(f, "{} or a list of ids", keywords.join(", "))
254    }
255
256    fn visit_str<E: de::Error>(self, value: &str) -> Result<T, E> {
257        match self.keywords.iter().find(|keyword| **keyword == value) {
258            Some(keyword) => Ok((self.keyword)(keyword)),
259            None => Err(E::invalid_value(de::Unexpected::Str(value), &self)),
260        }
261    }
262
263    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<T, A::Error> {
264        let mut ids = Vec::new();
265        while let Some(id) = seq.next_element::<String>()? {
266            ids.push(id);
267        }
268        Ok((self.list)(ids))
269    }
270}
271
272/// `store/clients.toml`: one table per client id.
273#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
274#[schemars(title = "Surjection client preferences (store/clients.toml)")]
275pub struct ClientPrefsFile {
276    /// Schema version; always 1.
277    #[schemars(extend("const" = 1))]
278    pub schema: i64,
279    /// Preferences keyed by client id.
280    #[serde(flatten)]
281    pub clients: BTreeMap<String, ClientPrefs>,
282}
283
284impl StoreModel for ClientPrefsFile {
285    const SCHEMA_NAME: &'static str = "clients";
286}
287
288/// Per-client preferences. Keys a client does not use are ignored by it.
289#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
290pub struct ClientPrefs {
291    /// `false` opts the client out of everything; `true` forces it on even
292    /// when it is not detected.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub enabled: Option<bool>,
295    /// `true`: an owned entry that is no longer desired is disabled through
296    /// the client's native mechanism (`enabled = false`) instead of being
297    /// removed, when the client has one (SPEC 8.4).
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub native_disable: Option<bool>,
300    /// Where the shared project layer goes (Claude Code: `.mcp.json`).
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub project_shared_target: Option<String>,
303    /// Where the private project layer goes (Claude Code: `local-scope`).
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub project_local_target: Option<String>,
306    /// Named profiles to target (omp).
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub profiles: Option<Vec<String>>,
309    /// VS Code variants to import from (`vscode-legacy`).
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub import_variants: Option<Vec<String>>,
312    /// VS Code profiles to import from (`vscode-legacy`).
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub import_profiles: Option<ProfileSelection>,
315    /// Keys this build does not model, kept on rewrite.
316    #[serde(flatten)]
317    #[schemars(skip)]
318    pub extra: toml::Table,
319}
320
321/// VS Code variants `vscode-legacy` can import from.
322pub const VSCODE_VARIANTS: [&str; 3] = ["Code", "Code - Insiders", "VSCodium"];
323
324impl ClientPrefsFile {
325    pub fn new() -> Self {
326        Self {
327            schema: SCHEMA_VERSION,
328            clients: BTreeMap::new(),
329        }
330    }
331
332    pub fn validate(&self) -> Diagnostics {
333        let mut d = Diagnostics::new();
334        for (id, prefs) in &self.clients {
335            let base = join("", id);
336            if known_client(id).is_none() {
337                d.warning(
338                    ErrorCode::UnknownClient,
339                    &base,
340                    format!("unknown client {id:?}; kept as written"),
341                );
342            }
343            for (index, variant) in prefs.import_variants.iter().flatten().enumerate() {
344                if !VSCODE_VARIANTS.contains(&variant.as_str()) {
345                    d.error(
346                        ErrorCode::InvalidValue,
347                        at(&join(&base, "import_variants"), index),
348                        format!(
349                            "unknown VS Code variant {variant:?}; expected one of {VSCODE_VARIANTS:?}"
350                        ),
351                    );
352                }
353            }
354        }
355        d
356    }
357}
358
359impl Default for ClientPrefsFile {
360    fn default() -> Self {
361        Self::new()
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    fn ids(list: &[&str]) -> Vec<String> {
370        list.iter().map(|id| (*id).to_owned()).collect()
371    }
372
373    #[test]
374    fn toggle_clients_edits_the_written_list() {
375        let here = || panic!("a list never asks what is detected");
376        let list = ClientSelection::List(ids(&["codex", "future-client"]));
377        assert_eq!(
378            toggle_clients(Some(&list), here, &ids(&["omp", "codex"]), true),
379            Some(ids(&["codex", "future-client", "omp"]))
380        );
381        assert_eq!(
382            toggle_clients(Some(&list), here, &ids(&["codex"]), false),
383            Some(ids(&["future-client"]))
384        );
385        assert_eq!(
386            toggle_clients(Some(&list), here, &ids(&["codex"]), true),
387            None
388        );
389        assert_eq!(
390            toggle_clients(Some(&list), here, &ids(&["omp"]), false),
391            None
392        );
393        assert_eq!(
394            toggle_clients(None, here, &ids(&["omp"]), true),
395            Some(ids(&["omp"]))
396        );
397        assert_eq!(toggle_clients(None, here, &ids(&["omp"]), false), None);
398    }
399
400    #[test]
401    fn toggle_clients_turns_all_detected_into_what_it_selects_here() {
402        let all = ClientSelection::AllDetected;
403        let here = || ids(&["claude-code", "codex"]);
404        assert_eq!(
405            toggle_clients(Some(&all), here, &ids(&["codex"]), false),
406            Some(ids(&["claude-code"]))
407        );
408        assert_eq!(
409            toggle_clients(Some(&all), here, &ids(&["omp"]), true),
410            Some(ids(&["claude-code", "codex", "omp"]))
411        );
412        assert_eq!(
413            toggle_clients(Some(&all), here, &ids(&["codex"]), true),
414            None
415        );
416        assert_eq!(
417            toggle_clients(Some(&all), here, &ids(&["omp"]), false),
418            None
419        );
420    }
421}