surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Client ids and `store/clients.toml` preferences (SPEC 5.4, 7.3, 7.5).

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;

use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::{self, Deserializer, SeqAccess, Visitor};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};

use crate::error::ErrorCode;
use crate::model::validate::{Diagnostics, at, join};
use crate::model::{SCHEMA_VERSION, StoreModel};

/// Key accepted in every `client.<id>` table: the native entry name for that
/// client when it differs from the server id (SPEC 5.1).
pub const NATIVE_NAME_KEY: &str = "native_name";

/// A client id the adapter table knows, with the native fields a server may
/// pass through to it in `[client.<id>]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KnownClient {
    pub id: &'static str,
    /// Native fields with no canonical equivalent (SPEC 7.3). Fields Surjection
    /// renders itself (transport, env, headers, tool filters, enablement,
    /// delivery helpers) are not listed.
    pub passthrough: &'static [&'static str],
}

const fn client(id: &'static str, passthrough: &'static [&'static str]) -> KnownClient {
    KnownClient { id, passthrough }
}

/// Every client id of SPEC 7.3 and 7.5, in table order, with its
/// passthrough allowlist. Validation reads ids from here because most
/// clients have no adapter yet; adapters (`crate::adapters`) take their
/// allowlist from here through [`passthrough_of`], so there is one list.
pub const KNOWN_CLIENTS: &[KnownClient] = &[
    // Tier A (Pi is Tier B since 2026-11-21; built with Tier A in M5)
    client("claude-code", &[]),
    client("omp", &["timeout", "instructions", "auth", "oauth"]),
    client("pi", &["exposure", "timeout", "oauth"]),
    client("codex", &["startup_timeout_sec", "tool_timeout_sec"]),
    client("claude-desktop", &[]),
    // Tier B
    client("copilot", &["oauthClientId"]),
    client("cursor", &["envFile"]),
    // Tier C
    client("gemini", &["timeout", "trust"]),
    client("antigravity", &["timeoutSeconds"]),
    client("opencode", &[]),
    client("grok", &["startup_timeout_sec", "tool_timeout_sec"]),
    // Tier D
    client("vscode-legacy", &[]),
    client("windsurf", &[]),
    client("devin", &[]),
    client("augment", &[]),
    client("cline", &[]),
    client("roo-code", &[]),
    client("kilo-code", &[]),
    client("kiro", &[]),
    client("junie", &[]),
    client("droid", &[]),
    client("commandcode", &[]),
    client("crush", &[]),
    client("qoder", &[]),
    client("trae", &[]),
    client("trae-cn", &[]),
    client("codebuddy", &[]),
    client("iflow", &[]),
    // A Gemini CLI fork, written through Gemini's mapper.
    client("qwen-code", &["timeout", "trust"]),
    client("zencoder", &[]),
    client("openclaw", &[]),
    client("mimo-code", &[]),
    client("workbuddy", &[]),
    client("zcode", &[]),
    client("continue", &[]),
    client("goose", &[]),
    client("hermes", &[]),
    client("intellij", &[]),
];

/// The table entry for `id`, if the client is known.
pub fn known_client(id: &str) -> Option<&'static KnownClient> {
    KNOWN_CLIENTS.iter().find(|client| client.id == id)
}

/// The passthrough allowlist of known client `id`, for the adapter table.
/// Used in constants, where an unknown id fails the build.
pub const fn passthrough_of(id: &str) -> &'static [&'static str] {
    let mut index = 0;
    while index < KNOWN_CLIENTS.len() {
        if const_str_eq(KNOWN_CLIENTS[index].id, id) {
            return KNOWN_CLIENTS[index].passthrough;
        }
        index += 1;
    }
    panic!("passthrough_of: unknown client id");
}

const fn const_str_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut index = 0;
    while index < a.len() {
        if a[index] != b[index] {
            return false;
        }
        index += 1;
    }
    true
}

const ALL_DETECTED: &str = "all-detected";

/// Which clients an item is enabled for: `"all-detected"` or a list of ids.
/// Unknown ids are kept as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientSelection {
    /// Every detected client whose capabilities fit.
    AllDetected,
    List(Vec<String>),
}

impl Serialize for ClientSelection {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::AllDetected => serializer.serialize_str(ALL_DETECTED),
            Self::List(ids) => ids.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for ClientSelection {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(KeywordOrList {
            keywords: &[ALL_DETECTED],
            keyword: |_| ClientSelection::AllDetected,
            list: ClientSelection::List,
        })
    }
}

impl JsonSchema for ClientSelection {
    fn schema_name() -> Cow<'static, str> {
        "ClientSelection".into()
    }

    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "description": "\"all-detected\" or a list of client ids",
            "oneOf": [
                { "const": ALL_DETECTED },
                { "type": "array", "items": { "type": "string" } }
            ]
        })
    }
}

/// The client list a selection writes after turning `clients` on
/// (`enabled`) or off, as the app's pill toggles and `surject server
/// enable|disable` do: a list keeps its order (named clients it lacks are
/// appended, removed ones dropped, other ids kept as written, including ids
/// this machine does not know); `all-detected` becomes the list of what it
/// selects on this machine (`here`) with the change applied; no selection
/// starts empty. `None` when nothing changes.
pub fn toggle_clients(
    current: Option<&ClientSelection>,
    here: impl FnOnce() -> Vec<String>,
    clients: &[String],
    enabled: bool,
) -> Option<Vec<String>> {
    let start = match current {
        Some(ClientSelection::List(ids)) => ids.clone(),
        Some(ClientSelection::AllDetected) => here(),
        None => Vec::new(),
    };
    let mut next = start.clone();
    for client in clients {
        if enabled && !next.contains(client) {
            next.push(client.clone());
        } else if !enabled {
            next.retain(|id| id != client);
        }
    }
    (next != start).then_some(next)
}

/// VS Code profiles to import: `"default"`, `"all"` or a list of profile ids.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileSelection {
    Default,
    All,
    List(Vec<String>),
}

impl Serialize for ProfileSelection {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Default => serializer.serialize_str("default"),
            Self::All => serializer.serialize_str("all"),
            Self::List(ids) => ids.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for ProfileSelection {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(KeywordOrList {
            keywords: &["default", "all"],
            keyword: |keyword| match keyword {
                "default" => ProfileSelection::Default,
                _ => ProfileSelection::All,
            },
            list: ProfileSelection::List,
        })
    }
}

impl JsonSchema for ProfileSelection {
    fn schema_name() -> Cow<'static, str> {
        "ProfileSelection".into()
    }

    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "description": "\"default\", \"all\" or a list of profile ids",
            "oneOf": [
                { "enum": ["default", "all"] },
                { "type": "array", "items": { "type": "string" } }
            ]
        })
    }
}

/// Accepts one of `keywords` or a list of strings.
struct KeywordOrList<T> {
    keywords: &'static [&'static str],
    /// Builds the value for a matched keyword.
    keyword: fn(&str) -> T,
    list: fn(Vec<String>) -> T,
}

impl<'de, T> Visitor<'de> for KeywordOrList<T> {
    type Value = T;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let keywords: Vec<String> = self.keywords.iter().map(|k| format!("{k:?}")).collect();
        write!(f, "{} or a list of ids", keywords.join(", "))
    }

    fn visit_str<E: de::Error>(self, value: &str) -> Result<T, E> {
        match self.keywords.iter().find(|keyword| **keyword == value) {
            Some(keyword) => Ok((self.keyword)(keyword)),
            None => Err(E::invalid_value(de::Unexpected::Str(value), &self)),
        }
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<T, A::Error> {
        let mut ids = Vec::new();
        while let Some(id) = seq.next_element::<String>()? {
            ids.push(id);
        }
        Ok((self.list)(ids))
    }
}

/// `store/clients.toml`: one table per client id.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(title = "Surjection client preferences (store/clients.toml)")]
pub struct ClientPrefsFile {
    /// Schema version; always 1.
    #[schemars(extend("const" = 1))]
    pub schema: i64,
    /// Preferences keyed by client id.
    #[serde(flatten)]
    pub clients: BTreeMap<String, ClientPrefs>,
}

impl StoreModel for ClientPrefsFile {
    const SCHEMA_NAME: &'static str = "clients";
}

/// Per-client preferences. Keys a client does not use are ignored by it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ClientPrefs {
    /// `false` opts the client out of everything; `true` forces it on even
    /// when it is not detected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// `true`: an owned entry that is no longer desired is disabled through
    /// the client's native mechanism (`enabled = false`) instead of being
    /// removed, when the client has one (SPEC 8.4).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_disable: Option<bool>,
    /// Where the shared project layer goes (Claude Code: `.mcp.json`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_shared_target: Option<String>,
    /// Where the private project layer goes (Claude Code: `local-scope`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_local_target: Option<String>,
    /// Named profiles to target (omp).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profiles: Option<Vec<String>>,
    /// VS Code variants to import from (`vscode-legacy`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub import_variants: Option<Vec<String>>,
    /// VS Code profiles to import from (`vscode-legacy`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub import_profiles: Option<ProfileSelection>,
    /// Keys this build does not model, kept on rewrite.
    #[serde(flatten)]
    #[schemars(skip)]
    pub extra: toml::Table,
}

/// VS Code variants `vscode-legacy` can import from.
pub const VSCODE_VARIANTS: [&str; 3] = ["Code", "Code - Insiders", "VSCodium"];

impl ClientPrefsFile {
    pub fn new() -> Self {
        Self {
            schema: SCHEMA_VERSION,
            clients: BTreeMap::new(),
        }
    }

    pub fn validate(&self) -> Diagnostics {
        let mut d = Diagnostics::new();
        for (id, prefs) in &self.clients {
            let base = join("", id);
            if known_client(id).is_none() {
                d.warning(
                    ErrorCode::UnknownClient,
                    &base,
                    format!("unknown client {id:?}; kept as written"),
                );
            }
            for (index, variant) in prefs.import_variants.iter().flatten().enumerate() {
                if !VSCODE_VARIANTS.contains(&variant.as_str()) {
                    d.error(
                        ErrorCode::InvalidValue,
                        at(&join(&base, "import_variants"), index),
                        format!(
                            "unknown VS Code variant {variant:?}; expected one of {VSCODE_VARIANTS:?}"
                        ),
                    );
                }
            }
        }
        d
    }
}

impl Default for ClientPrefsFile {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ids(list: &[&str]) -> Vec<String> {
        list.iter().map(|id| (*id).to_owned()).collect()
    }

    #[test]
    fn toggle_clients_edits_the_written_list() {
        let here = || panic!("a list never asks what is detected");
        let list = ClientSelection::List(ids(&["codex", "future-client"]));
        assert_eq!(
            toggle_clients(Some(&list), here, &ids(&["omp", "codex"]), true),
            Some(ids(&["codex", "future-client", "omp"]))
        );
        assert_eq!(
            toggle_clients(Some(&list), here, &ids(&["codex"]), false),
            Some(ids(&["future-client"]))
        );
        assert_eq!(
            toggle_clients(Some(&list), here, &ids(&["codex"]), true),
            None
        );
        assert_eq!(
            toggle_clients(Some(&list), here, &ids(&["omp"]), false),
            None
        );
        assert_eq!(
            toggle_clients(None, here, &ids(&["omp"]), true),
            Some(ids(&["omp"]))
        );
        assert_eq!(toggle_clients(None, here, &ids(&["omp"]), false), None);
    }

    #[test]
    fn toggle_clients_turns_all_detected_into_what_it_selects_here() {
        let all = ClientSelection::AllDetected;
        let here = || ids(&["claude-code", "codex"]);
        assert_eq!(
            toggle_clients(Some(&all), here, &ids(&["codex"]), false),
            Some(ids(&["claude-code"]))
        );
        assert_eq!(
            toggle_clients(Some(&all), here, &ids(&["omp"]), true),
            Some(ids(&["claude-code", "codex", "omp"]))
        );
        assert_eq!(
            toggle_clients(Some(&all), here, &ids(&["codex"]), true),
            None
        );
        assert_eq!(
            toggle_clients(Some(&all), here, &ids(&["omp"]), false),
            None
        );
    }
}