1use 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
16pub const NATIVE_NAME_KEY: &str = "native_name";
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct KnownClient {
24 pub id: &'static str,
25 pub passthrough: &'static [&'static str],
29}
30
31const fn client(id: &'static str, passthrough: &'static [&'static str]) -> KnownClient {
32 KnownClient { id, passthrough }
33}
34
35pub const KNOWN_CLIENTS: &[KnownClient] = &[
40 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 client("copilot", &["oauthClientId"]),
48 client("cursor", &["envFile"]),
49 client("gemini", &["timeout", "trust"]),
51 client("antigravity", &["timeoutSeconds"]),
52 client("opencode", &[]),
53 client("grok", &["startup_timeout_sec", "tool_timeout_sec"]),
54 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 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
85pub fn known_client(id: &str) -> Option<&'static KnownClient> {
87 KNOWN_CLIENTS.iter().find(|client| client.id == id)
88}
89
90pub 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#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum ClientSelection {
124 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
164pub 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#[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
240struct KeywordOrList<T> {
242 keywords: &'static [&'static str],
243 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
274#[schemars(title = "Surjection client preferences (store/clients.toml)")]
275pub struct ClientPrefsFile {
276 #[schemars(extend("const" = 1))]
278 pub schema: i64,
279 #[serde(flatten)]
281 pub clients: BTreeMap<String, ClientPrefs>,
282}
283
284impl StoreModel for ClientPrefsFile {
285 const SCHEMA_NAME: &'static str = "clients";
286}
287
288#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
290pub struct ClientPrefs {
291 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub enabled: Option<bool>,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
299 pub native_disable: Option<bool>,
300 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub project_shared_target: Option<String>,
303 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub project_local_target: Option<String>,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub profiles: Option<Vec<String>>,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub import_variants: Option<Vec<String>>,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub import_profiles: Option<ProfileSelection>,
315 #[serde(flatten)]
317 #[schemars(skip)]
318 pub extra: toml::Table,
319}
320
321pub 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}