surjection-core 1.2.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! One owned entry made self-contained: the `surject exec` launcher
//! unwrapped, `!<surjection> secret get` hooks and Claude Code's
//! `headersHelper` running `<surjection> secret-header` replaced by the
//! client's own variable references, through the client's mapper so every
//! other field reads back as it was.

use std::collections::BTreeMap;
use std::path::Path;

use serde::Serialize;

use crate::adapters::AdapterSpec;
use crate::adapters::caps::{Caps, EnvRefSyntax, FieldSet};
use crate::adapters::mapper::{
    EntryMapper, Launch, RemoteLaunch, RenderedServer, ServerDef, StdioLaunch, WriteCx,
};
use crate::brand;
use crate::env::Os;
use crate::error::{CoreError, ErrorCode};
use crate::formats::NativeValue;
use crate::model::server::Transport;
use crate::secrets::catalog::Catalog;
use crate::secrets::delivery::env_syntax;
use crate::secrets::grammar::SecretRef;
use crate::secrets::render::{PLACEHOLDER, Spell, parse_binding, spell};

/// An environment variable the user sets for an ejected entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct EnvNeed {
    /// The variable name.
    pub name: String,
    /// The catalog alias it stands for, when there is one.
    pub secret: Option<String>,
    /// The reference the value comes from (`op://...`, `keyring://...`,
    /// `env:NAME`): two entries needing one name for different references
    /// are a conflict.
    pub reference: String,
}

/// A value the client cannot read from the environment: the user pastes it
/// into the entry. The value is never written by Surjection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ManualSecret {
    /// `env` or `headers`.
    pub field: &'static str,
    /// The env key or header name.
    pub key: String,
    /// The alias, or the reference when no alias names it.
    pub secret: String,
    /// The variable name this value would have used, when an earlier entry
    /// already uses that name for a different secret.
    pub conflicts_with: Option<String>,
}

/// What eject does with one entry.
#[derive(Debug, Clone)]
pub(crate) enum Analysis {
    /// No Surjection reference.
    Keep { uses_data_folder: bool },
    Rewrite {
        value: NativeValue,
        needs_env: Vec<EnvNeed>,
        manual: Vec<ManualSecret>,
        uses_data_folder: bool,
    },
    /// Depends on Surjection but cannot be rewritten safely.
    Manual(CoreError),
}

/// A part of a value delivered through Surjection.
#[derive(Debug, Clone)]
enum Part {
    Text(String),
    /// A reference; `key` is its binding (`--ref KEY=REF`), if any.
    Ref {
        key: Option<String>,
        reference: SecretRef,
    },
}

/// Variable names handed out so far in one eject, with the reference and
/// label each stands for.
pub(crate) type Taken = std::cell::RefCell<BTreeMap<String, (String, String)>>;

pub(crate) struct Rewriter<'a> {
    pub spec: &'static AdapterSpec,
    pub os: Os,
    pub catalog: &'a Catalog,
    /// The `surject` binary entries start, when known.
    pub launcher: Option<&'a Path>,
    pub surjection_home: &'a Path,
    /// Names earlier entries of this eject use.
    pub taken: &'a Taken,
}

#[derive(Default)]
struct Needs {
    env: Vec<EnvNeed>,
    manual: Vec<ManualSecret>,
}

impl Needs {
    fn env(&mut self, name: &str, secret: Option<String>, reference: &str) {
        if !self.env.iter().any(|need| need.name == name) {
            self.env.push(EnvNeed {
                name: name.to_owned(),
                secret,
                reference: reference.to_owned(),
            });
        }
    }
}

impl Rewriter<'_> {
    fn caps(&self) -> &'static Caps {
        &self.spec.mcp.as_ref().expect("an MCP client").caps
    }

    fn mapper(&self) -> &'static dyn EntryMapper {
        self.spec.mcp.as_ref().expect("an MCP client").mapper
    }

    /// What eject does with entry `key` holding `value`.
    pub(crate) fn analyze(&self, key: &str, value: &NativeValue) -> Analysis {
        let uses_data_folder = any_string(value, &|text| self.mentions_home(text));
        let mapper = self.mapper();
        let def = match mapper.from_native(key, value) {
            Ok(def) => def,
            Err(_) if any_string(value, &|text| self.mentions_launcher(text)) => {
                return Analysis::Manual(manual(format!(
                    "the entry starts `{}` but {} cannot read it back",
                    brand::BIN_NAME,
                    brand::PRODUCT_NAME
                )));
            }
            Err(_) => return Analysis::Keep { uses_data_folder },
        };
        if !self.depends(&def) {
            return Analysis::Keep { uses_data_folder };
        }
        let cx = WriteCx {
            os: self.os,
            existing: Some(value),
        };
        // The entry must read back exactly before anything in it changes.
        let same = self
            .rendered(key, def.clone())
            .and_then(|server| mapper.to_native(&server, &cx).map_err(CoreError::from));
        if !matches!(&same, Ok(same) if mapper.canonical(same) == mapper.canonical(value)) {
            return Analysis::Manual(manual(format!(
                "{} cannot rewrite this entry without changing other fields",
                brand::PRODUCT_NAME
            )));
        }
        let mut needs = Needs::default();
        let rewritten = self
            .transform(def, &mut needs)
            .and_then(|def| self.rendered(key, def))
            .and_then(|server| mapper.to_native(&server, &cx).map_err(CoreError::from));
        let value = match rewritten {
            Ok(value) => value,
            Err(err) => return Analysis::Manual(err),
        };
        if any_string(&value, &|text| self.mentions_launcher(text)) {
            return Analysis::Manual(manual(format!(
                "the entry still starts `{}` after the rewrite",
                brand::BIN_NAME
            )));
        }
        Analysis::Rewrite {
            uses_data_folder: any_string(&value, &|text| self.mentions_home(text)),
            value,
            needs_env: needs.env,
            manual: needs.manual,
        }
    }

    /// Whether the entry starts `surject` (the launcher, a hook, a
    /// `headersHelper`).
    fn depends(&self, def: &ServerDef) -> bool {
        let fields = &def.fields;
        let launched = fields
            .command
            .as_deref()
            .is_some_and(|c| self.is_launcher(c))
            && fields
                .args
                .as_deref()
                .and_then(<[String]>::first)
                .is_some_and(|arg| arg == "exec");
        let hook = [&fields.env, &fields.headers]
            .into_iter()
            .flat_map(|map| map.iter().flatten())
            .any(|(_, value)| self.is_hook(value).is_some());
        let helper = def
            .headers_helper
            .as_deref()
            .is_some_and(|helper| self.starts_launcher(helper));
        launched || hook || helper
    }

    /// The command text of a `!<surjection> ...` value.
    fn is_hook<'v>(&self, value: &'v str) -> Option<&'v str> {
        value
            .strip_prefix('!')
            .filter(|command| self.starts_launcher(command))
    }

    fn transform(&self, mut def: ServerDef, needs: &mut Needs) -> Result<ServerDef, CoreError> {
        let caps = self.caps();
        let fields = &mut def.fields;
        let launched = fields
            .command
            .as_deref()
            .is_some_and(|c| self.is_launcher(c))
            && fields
                .args
                .as_deref()
                .and_then(<[String]>::first)
                .is_some_and(|arg| arg == "exec");
        if launched {
            let args = fields.args.take().unwrap_or_default();
            let exec = parse_exec(&args[1..])?;
            fields.command = Some(exec.command);
            fields.args = Some(exec.args);
            let env = fields.env.get_or_insert_with(BTreeMap::new);
            for (key, reference) in exec.refs {
                if caps.env_ref == Some(EnvRefSyntax::CodexForward) {
                    // Forwarded under its own name: the user sets KEY.
                    let alias = self.alias_of(&reference).map(|(_, alias)| alias);
                    let text = reference.to_string();
                    match self.conflict(&key, &text) {
                        Some(name) => {
                            env.remove(&key);
                            needs.manual.push(ManualSecret {
                                field: "env",
                                key: key.clone(),
                                secret: self.label(&reference),
                                conflicts_with: Some(name),
                            });
                        }
                        None => {
                            env.insert(key.clone(), format!("${{env:{key}}}"));
                            self.take(&key, &text, &self.label(&reference));
                            needs.env(&key, alias, &text);
                        }
                    }
                } else {
                    let parts = vec![Part::Ref {
                        key: Some(key.clone()),
                        reference,
                    }];
                    self.set(env, &key, &parts, FieldSet::ENV, needs)?;
                }
            }
            if env.is_empty() {
                fields.env = None;
            }
        }
        for (field, map) in [
            (FieldSet::ENV, &mut fields.env),
            (FieldSet::HEADERS, &mut fields.headers),
        ] {
            let Some(map) = map else {
                continue;
            };
            let hooks: Vec<(String, String)> = map
                .iter()
                .filter_map(|(key, value)| {
                    self.is_hook(value)
                        .map(|command| (key.clone(), command.to_owned()))
                })
                .collect();
            for (key, command) in hooks {
                let words = shell_words(&command).ok_or_else(|| unparsed(&command))?;
                let parts = parse_secret_get(&words[1..])?;
                // A bare reference is bound to the env key it fills.
                let parts = match (field, parts.as_slice()) {
                    (
                        FieldSet::ENV,
                        [
                            Part::Ref {
                                key: None,
                                reference,
                            },
                        ],
                    ) => vec![Part::Ref {
                        key: Some(key.clone()),
                        reference: reference.clone(),
                    }],
                    _ => parts,
                };
                self.set(map, &key, &parts, field, needs)?;
            }
        }
        if let Some(helper) = def.headers_helper.take() {
            if self.starts_launcher(&helper) {
                let words = shell_words(&helper).ok_or_else(|| unparsed(&helper))?;
                let headers = parse_secret_header(&words[1..])?;
                let map = def.fields.headers.get_or_insert_with(BTreeMap::new);
                for (name, parts) in headers {
                    self.set(map, &name, &parts, FieldSet::HEADERS, needs)?;
                }
            } else {
                def.headers_helper = Some(helper);
            }
        }
        Ok(def)
    }

    /// Sets `map[key]` to `parts` in the client's syntax, or leaves the key
    /// out and records a manual secret when the client cannot expand them
    /// there (or a name they need already stands for another secret). Fails
    /// (the entry stays as it is, `manual`) when the client would expand
    /// part of the literal text.
    fn set(
        &self,
        map: &mut BTreeMap<String, String>,
        key: &str,
        parts: &[Part],
        field: FieldSet,
        needs: &mut Needs,
    ) -> Result<(), CoreError> {
        let field_name = if field == FieldSet::HEADERS {
            "headers"
        } else {
            "env"
        };
        // (variable, alias, reference text, label)
        let mut names: Vec<(String, Option<String>, String, String)> = Vec::new();
        let mut missing: Option<String> = None;
        for part in parts {
            if let Part::Ref { key, reference } = part {
                match self.variable(reference, key.as_deref()) {
                    Some((name, alias)) => {
                        names.push((name, alias, reference.to_string(), self.label(reference)))
                    }
                    None => {
                        missing.get_or_insert_with(|| self.label(reference));
                    }
                }
            }
        }
        let conflict = names
            .iter()
            .find_map(|(name, _, reference, _)| self.conflict(name, reference));
        if missing.is_none() && conflict.is_none() {
            let mut index = 0;
            let pieces: Vec<Spell<'_>> = parts
                .iter()
                .map(|part| match part {
                    Part::Text(text) => Spell::Text(text),
                    Part::Ref { .. } => {
                        index += 1;
                        Spell::Variable(&names[index - 1].0)
                    }
                })
                .collect();
            match spell(self.caps(), self.spec.display_name, field, &pieces) {
                Ok(value) => {
                    map.insert(key.to_owned(), value);
                    for (name, alias, reference, label) in names {
                        self.take(&name, &reference, &label);
                        needs.env(&name, alias, &reference);
                    }
                    return Ok(());
                }
                // The client expands variables here, so it is the literal
                // text around them it cannot hold: leave the entry as it is.
                Err(err) if env_syntax(self.caps(), field).is_some() => {
                    return Err(manual(format!(
                        "{}; the entry still starts `{}`",
                        err.message(),
                        brand::BIN_NAME
                    )));
                }
                Err(_) => {}
            }
        }
        map.remove(key);
        let secret = missing.unwrap_or_else(|| {
            parts
                .iter()
                .find_map(|part| match part {
                    Part::Ref { reference, .. } => Some(self.label(reference)),
                    Part::Text(_) => None,
                })
                .unwrap_or_default()
        });
        needs.manual.push(ManualSecret {
            field: field_name,
            key: key.to_owned(),
            secret,
            conflicts_with: conflict,
        });
        Ok(())
    }

    /// `name` when an earlier entry of this eject uses it for a reference
    /// other than `reference`.
    fn conflict(&self, name: &str, reference: &str) -> Option<String> {
        self.taken
            .borrow()
            .get(name)
            .filter(|(taken, _)| taken != reference)
            .map(|_| name.to_owned())
    }

    fn take(&self, name: &str, reference: &str, label: &str) {
        self.taken
            .borrow_mut()
            .entry(name.to_owned())
            .or_insert_with(|| (reference.to_owned(), label.to_owned()));
    }

    /// The variable a reference becomes, and its alias: `env:NAME` keeps
    /// `NAME`; a reference this machine's catalog names becomes the alias's
    /// `env_name` (else the alias); any other the binding key.
    fn variable(
        &self,
        reference: &SecretRef,
        key: Option<&str>,
    ) -> Option<(String, Option<String>)> {
        if let SecretRef::Env { name } = reference {
            return Some((name.clone(), None));
        }
        if let Some((name, alias)) = self.alias_of(reference) {
            return Some((name, Some(alias)));
        }
        let key =
            key.filter(|key| crate::model::ids::is_valid(crate::model::ids::IdKind::EnvVar, key))?;
        Some((key.to_owned(), None))
    }

    /// The `env_name` and alias of the catalog alias with this reference.
    fn alias_of(&self, reference: &SecretRef) -> Option<(String, String)> {
        self.catalog
            .iter()
            .find(|alias| alias.parsed().ok().as_ref() == Some(reference))
            .map(|alias| (alias.env_name().to_owned(), alias.alias.clone()))
    }

    /// How messages name a reference: its alias, else the reference.
    fn label(&self, reference: &SecretRef) -> String {
        self.alias_of(reference)
            .map_or_else(|| reference.to_string(), |(_, alias)| alias)
    }

    /// The entry as a [`RenderedServer`], with Codex's forwarded variables
    /// (read back as `${env:NAME}`) forwarded again.
    fn rendered(&self, key: &str, def: ServerDef) -> Result<RenderedServer, CoreError> {
        let forwards = self.caps().env_ref == Some(EnvRefSyntax::CodexForward);
        let fields = def.fields;
        let transport = fields
            .transport
            .ok_or_else(|| CoreError::new(ErrorCode::MissingField, "`transport` is required"))?;
        let launch = match transport {
            Transport::Stdio => {
                let mut env = fields.env.unwrap_or_default();
                let mut forward_env = Vec::new();
                if forwards {
                    env.retain(|name, value| {
                        if whole_env_ref(value) == Some(name.as_str()) {
                            forward_env.push(name.clone());
                            false
                        } else {
                            true
                        }
                    });
                }
                Launch::Stdio(StdioLaunch {
                    command: fields.command.unwrap_or_default(),
                    args: fields.args.unwrap_or_default(),
                    env,
                    forward_env,
                    cwd: fields.cwd,
                })
            }
            Transport::Http | Transport::Sse => {
                let mut headers = fields.headers.unwrap_or_default();
                let mut bearer_env = None;
                let mut headers_env = BTreeMap::new();
                if forwards {
                    headers.retain(|name, value| {
                        if name == "Authorization"
                            && let Some(variable) =
                                value.strip_prefix("Bearer ").and_then(whole_env_ref)
                        {
                            bearer_env = Some(variable.to_owned());
                            return false;
                        }
                        if let Some(variable) = whole_env_ref(value) {
                            headers_env.insert(name.clone(), variable.to_owned());
                            return false;
                        }
                        true
                    });
                }
                let remote = RemoteLaunch {
                    url: fields.url.unwrap_or_default(),
                    headers,
                    headers_helper: def.headers_helper,
                    bearer_env,
                    headers_env,
                };
                match transport {
                    Transport::Http => Launch::Http(remote),
                    _ => Launch::Sse(remote),
                }
            }
        };
        Ok(RenderedServer {
            name: key.to_owned(),
            launch,
            enabled: !def.disabled,
            tools: def.tools,
            passthrough: def.passthrough,
        })
    }

    /// Whether `command` is the `surject` binary: the launcher path, or a
    /// file named `surject` (`surject.exe`).
    fn is_launcher(&self, command: &str) -> bool {
        if self
            .launcher
            .is_some_and(|launcher| same_text(&launcher.to_string_lossy(), command))
        {
            return true;
        }
        let name = command.rsplit(['/', '\\']).next().unwrap_or(command);
        let stem = name
            .get(name.len().saturating_sub(4)..)
            .filter(|suffix| suffix.eq_ignore_ascii_case(".exe"))
            .map_or(name, |_| &name[..name.len() - 4]);
        stem.eq_ignore_ascii_case(brand::BIN_NAME)
    }

    /// Whether a command line starts the `surject` binary.
    fn starts_launcher(&self, command: &str) -> bool {
        shell_words(command)
            .and_then(|words| words.into_iter().next())
            .is_some_and(|first| self.is_launcher(&first))
    }

    /// Whether `text` starts the `surject` binary (as a command or hook) or
    /// names the launcher path.
    fn mentions_launcher(&self, text: &str) -> bool {
        self.is_launcher(text)
            || self.starts_launcher(text.strip_prefix('!').unwrap_or(text))
            || self
                .launcher
                .is_some_and(|launcher| contains_path(text, launcher))
    }

    /// Whether `text` holds a path into the data folder.
    fn mentions_home(&self, text: &str) -> bool {
        contains_path(text, self.surjection_home)
    }
}

/// `${env:NAME}` alone: `NAME`.
fn whole_env_ref(value: &str) -> Option<&str> {
    let name = value.strip_prefix("${env:")?.strip_suffix('}')?;
    crate::model::ids::is_valid(crate::model::ids::IdKind::EnvVar, name).then_some(name)
}

fn same_text(a: &str, b: &str) -> bool {
    if cfg!(windows) {
        a.eq_ignore_ascii_case(b)
    } else {
        a == b
    }
}

/// Whether `text` holds `path`, with either separator (case-insensitive on
/// Windows).
fn contains_path(text: &str, path: &Path) -> bool {
    let path = path.to_string_lossy();
    if path.is_empty() {
        return false;
    }
    let (text, path) = if cfg!(windows) {
        (text.to_lowercase(), path.to_lowercase())
    } else {
        (text.to_owned(), path.into_owned())
    };
    let text = text.replace('\\', "/");
    text.contains(&path.replace('\\', "/"))
}

/// Calls `f` on every string in `value`; whether one matched.
fn any_string(value: &NativeValue, f: &dyn Fn(&str) -> bool) -> bool {
    match value {
        NativeValue::String(text) => f(text),
        NativeValue::Array(items) => items.iter().any(|item| any_string(item, f)),
        NativeValue::Object(map) => map.iter().any(|(_, item)| any_string(item, f)),
        _ => false,
    }
}

fn manual(message: String) -> CoreError {
    CoreError::new(ErrorCode::NeedsManualSecret, message)
}

fn unparsed(command: &str) -> CoreError {
    let _ = command;
    manual(format!(
        "the `{}` command in the entry cannot be read",
        brand::BIN_NAME
    ))
}

/// `surject exec` arguments after `exec`.
struct Exec {
    refs: Vec<(String, SecretRef)>,
    command: String,
    args: Vec<String>,
}

fn parse_exec(args: &[String]) -> Result<Exec, CoreError> {
    let bad = || {
        manual(format!(
            "the `{} exec` arguments cannot be read",
            brand::BIN_NAME
        ))
    };
    let mut refs = Vec::new();
    let mut environment: Option<String> = None;
    let mut maps: Vec<(String, String)> = Vec::new();
    let mut rest = args.iter();
    loop {
        let arg = rest.next().ok_or_else(bad)?;
        let (flag, inline) = match arg.split_once('=') {
            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_owned())),
            _ => (arg.as_str(), None),
        };
        let mut value = || {
            inline
                .clone()
                .or_else(|| rest.next().cloned())
                .ok_or_else(bad)
        };
        match flag {
            "--" => break,
            "--ref" => {
                let (key, reference) = parse_binding(&value()?).map_err(|_| bad())?;
                refs.push((key, reference));
            }
            "--op-account" => {
                value()?;
            }
            "--op-env" => environment = Some(value()?),
            "--map" => {
                let map = value()?;
                let (key, name) = map.split_once('=').ok_or_else(bad)?;
                maps.push((key.to_owned(), name.to_owned()));
            }
            _ => return Err(bad()),
        }
    }
    for (key, name) in maps {
        let environment = environment.clone().ok_or_else(bad)?;
        refs.push((key, SecretRef::OnePasswordEnvironment { environment, name }));
    }
    let command = rest.next().ok_or_else(bad)?.clone();
    Ok(Exec {
        refs,
        command,
        args: rest.cloned().collect(),
    })
}

/// `secret get` arguments (the words after the binary).
fn parse_secret_get(words: &[String]) -> Result<Vec<Part>, CoreError> {
    let bad = || {
        manual(format!(
            "the `{} secret get` hook cannot be read",
            brand::BIN_NAME
        ))
    };
    let [secret, get, rest @ ..] = words else {
        return Err(bad());
    };
    if secret != "secret" || get != "get" {
        return Err(bad());
    }
    let mut refs: Vec<String> = Vec::new();
    let mut template: Option<String> = None;
    let mut rest = rest.iter();
    while let Some(flag) = rest.next() {
        let value = rest.next().ok_or_else(bad)?;
        match flag.as_str() {
            "--ref" => refs.push(value.clone()),
            "--template" => template = Some(value.clone()),
            "--op-account" => {}
            _ => return Err(bad()),
        }
    }
    match template {
        None => {
            let [reference] = refs.as_slice() else {
                return Err(bad());
            };
            let reference = SecretRef::parse(reference).map_err(|_| bad())?;
            Ok(vec![Part::Ref {
                key: None,
                reference,
            }])
        }
        Some(template) => {
            let bindings = refs
                .iter()
                .map(|binding| parse_binding(binding))
                .collect::<Result<Vec<_>, _>>()
                .map_err(|_| bad())?;
            split_template(&template, &bindings).ok_or_else(bad)
        }
    }
}

/// `secret-header` arguments (the words after the binary): each header and
/// its value as parts.
fn parse_secret_header(words: &[String]) -> Result<Vec<(String, Vec<Part>)>, CoreError> {
    let bad = || {
        manual(format!(
            "the `{} secret-header` helper cannot be read",
            brand::BIN_NAME
        ))
    };
    let [command, rest @ ..] = words else {
        return Err(bad());
    };
    if command != "secret-header" {
        return Err(bad());
    }
    let mut bindings = Vec::new();
    let mut headers: Vec<(String, String)> = Vec::new();
    let mut rest = rest.iter();
    while let Some(word) = rest.next() {
        match word.as_str() {
            "--ref" => {
                let binding = rest.next().ok_or_else(bad)?;
                bindings.push(parse_binding(binding).map_err(|_| bad())?);
            }
            "--op-account" => {
                rest.next().ok_or_else(bad)?;
            }
            header => {
                let (name, template) = header.split_once('=').ok_or_else(bad)?;
                headers.push((name.to_owned(), template.to_owned()));
            }
        }
    }
    headers
        .into_iter()
        .map(|(name, template)| {
            split_template(&template, &bindings)
                .map(|parts| (name, parts))
                .ok_or_else(bad)
        })
        .collect()
}

/// A command template (`{secret:KEY}` placeholders) as parts.
fn split_template(template: &str, bindings: &[(String, SecretRef)]) -> Option<Vec<Part>> {
    let mut parts = Vec::new();
    let mut rest = template;
    while let Some(start) = rest.find(PLACEHOLDER) {
        if start > 0 {
            parts.push(Part::Text(rest[..start].to_owned()));
        }
        let after = &rest[start + PLACEHOLDER.len()..];
        let end = after.find('}')?;
        let key = &after[..end];
        let reference = bindings
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, reference)| reference.clone())?;
        parts.push(Part::Ref {
            key: Some(key.to_owned()),
            reference,
        });
        rest = &after[end + 1..];
    }
    if !rest.is_empty() {
        parts.push(Part::Text(rest.to_owned()));
    }
    Some(parts)
}

/// Splits a command line the way [`crate::secrets::render::shell_quote`]
/// quotes it: single quotes (with `'\''`) and double quotes; `None` for an
/// unterminated quote.
fn shell_words(text: &str) -> Option<Vec<String>> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut in_word = false;
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\'' | '"' => {
                in_word = true;
                loop {
                    match chars.next()? {
                        close if close == c => break,
                        other => current.push(other),
                    }
                }
            }
            '\\' if chars.peek() == Some(&'\'') => {
                in_word = true;
                current.push(chars.next()?);
            }
            c if c.is_whitespace() => {
                if in_word {
                    words.push(std::mem::take(&mut current));
                    in_word = false;
                }
            }
            c => {
                in_word = true;
                current.push(c);
            }
        }
    }
    if in_word {
        words.push(current);
    }
    Some(words)
}

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

    fn words(text: &str) -> Vec<String> {
        shell_words(text).unwrap()
    }

    #[test]
    fn shell_words_read_both_quote_styles() {
        assert_eq!(
            words(r#""C:\Program Files\Surjection\surject.exe" secret get --ref "op://v/i/f""#),
            [
                "C:\\Program Files\\Surjection\\surject.exe",
                "secret",
                "get",
                "--ref",
                "op://v/i/f"
            ]
        );
        assert_eq!(
            words(r"'/opt/it'\''s/surjection' secret-header 'Authorization=Bearer {secret:A}'"),
            [
                "/opt/it's/surjection",
                "secret-header",
                "Authorization=Bearer {secret:A}"
            ]
        );
        assert!(shell_words("'open").is_none());
    }

    #[test]
    fn exec_arguments_split_into_refs_and_the_command() {
        let args: Vec<String> = [
            "--op-account",
            "me",
            "--ref",
            "TOKEN=op://v/i/f",
            "--op-env",
            "abc",
            "--map",
            "DB=DB_URL",
            "--",
            "npx",
            "-y",
            "server",
        ]
        .map(str::to_owned)
        .to_vec();
        let exec = parse_exec(&args).unwrap();
        assert_eq!(exec.command, "npx");
        assert_eq!(exec.args, ["-y", "server"]);
        assert_eq!(exec.refs.len(), 2);
        assert_eq!(exec.refs[0].0, "TOKEN");
        assert_eq!(
            exec.refs[1].1,
            SecretRef::OnePasswordEnvironment {
                environment: "abc".to_owned(),
                name: "DB_URL".to_owned()
            }
        );
        assert!(parse_exec(&["--ref".to_owned()]).is_err());
    }

    #[test]
    fn templates_keep_their_literal_text() {
        let reference = SecretRef::parse("keyring://surjection/A").unwrap();
        let parts =
            split_template("Bearer {secret:A}!", &[("A".to_owned(), reference.clone())]).unwrap();
        assert!(matches!(&parts[0], Part::Text(text) if text == "Bearer "));
        assert!(matches!(&parts[1], Part::Ref { key: Some(key), .. } if key == "A"));
        assert!(matches!(&parts[2], Part::Text(text) if text == "!"));
        assert!(split_template("{secret:B}", &[("A".to_owned(), reference)]).is_none());
    }

    fn claude_helper(header: &str) -> NativeValue {
        let mut entry = crate::formats::NativeMap::new();
        entry.insert("type", "http".into());
        entry.insert("url", "https://mcp.example.test/mcp".into());
        entry.insert(
            "headersHelper",
            format!(
                "'/opt/surjection/bin/surject' secret-header --ref 'K=keyring://surjection/K' '{header}'"
            )
            .into(),
        );
        NativeValue::Object(entry)
    }

    fn analyze(header: &str) -> Analysis {
        let catalog = Catalog::default();
        let taken = Taken::default();
        let rewriter = Rewriter {
            spec: crate::adapters::adapter("claude-code").unwrap(),
            os: Os::Linux,
            catalog: &catalog,
            launcher: None,
            surjection_home: Path::new("/surjection-home"),
            taken: &taken,
        };
        rewriter.analyze("linear", &claude_helper(header))
    }

    #[test]
    fn a_literal_the_client_would_expand_leaves_the_entry_as_it_is() {
        // Claude Code expands `${` in headers and has no escape for it.
        let Analysis::Manual(err) = analyze("Authorization=a${b}{secret:K}") else {
            panic!("expected manual");
        };
        assert!(err.message().contains("surject"), "{err}");
        // Without the literal, the same header is rewritten.
        let Analysis::Rewrite { value, .. } = analyze("Authorization=Bearer {secret:K}") else {
            panic!("expected a rewrite");
        };
        let headers = value.as_object().unwrap().get("headers").unwrap();
        assert_eq!(
            headers.as_object().unwrap().get("Authorization"),
            Some(&NativeValue::from("Bearer ${K}"))
        );
    }
}