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
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
//! Template rendering for one server and client with secret delivery (SPEC
//! 11.2, 11.4): path variables become paths, and each value holding
//! references is written in the mode [`Policy::choose`] picks:
//!
//! - `env`: the client's own variable syntax (`${NAME}`, `${env:NAME}`),
//!   or a forwarded variable name (Codex);
//! - `launch`: the key leaves the entry's `env`, and the entry starts
//!   `surject exec --ref KEY=REF ... -- <command> <args>` instead;
//! - `command`: omp and Pi get `!<surjection> secret get --ref REF`, Claude
//!   Code gets one `headersHelper` running `<surjection> secret-header`;
//! - `inline`: the resolved value, kept for masking in diffs.
//!
//! Command templates mark a value with `{secret:KEY}`, bound by `--ref
//! KEY=REF`: no `$`, `%` or `!`, so neither a client nor a shell expands it.

use std::path::Path;
use std::sync::Arc;

use crate::adapters::caps::{Caps, CommandRef, EnvRefSyntax, FieldSet};
use crate::adapters::mapper::{RemoteLaunch, StdioLaunch};
use crate::brand;
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::model::server::{DeliveryMode, Transport};
use crate::secrets::SecretValue;
use crate::secrets::catalog::Catalog;
use crate::secrets::delivery::{
    DeliveryEnv, Mode, Policy, Sharing, Slot, Source, check_available, env_syntax, field_name,
    op_env, source_of_alias,
};
use crate::secrets::grammar::{PathVar, SecretRef, TemplatePart, parse_template};
use crate::secrets::providers::{Resolver, env};
use crate::secrets::scanner::SecretMemory;

/// The placeholder opening of a bound value in command templates.
pub const PLACEHOLDER: &str = "{secret:";

/// What rendering reads: Surjection's environment (paths, inline `env:`
/// values), the catalog and this machine's providers.
#[derive(Clone, Copy)]
pub struct RenderEnv<'a> {
    pub env: &'a Env,
    pub fs: &'a dyn Fs,
    pub surjection_home: &'a Path,
    pub catalog: &'a Catalog,
    pub delivery: &'a DeliveryEnv,
    pub memory: &'a Arc<SecretMemory>,
    /// The project folder `${project}` stands for; `None` at system scope.
    pub project: Option<&'a Path>,
}

/// A stdio `env` value as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnvValue {
    Value(String),
    /// Forwarded from the client's environment under the same name (Codex
    /// `env_vars`).
    Forward(String),
    /// Set by `surject exec` when the server starts.
    Launched,
}

/// A header value as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderValue {
    Value(String),
    /// `Authorization: Bearer <variable>` (Codex `bearer_token_env_var`).
    Bearer(String),
    /// The whole value from a variable (Codex `env_http_headers`).
    FromEnv(String),
    /// Printed by the entry's `headersHelper`.
    Helper,
}

#[derive(Debug, Clone)]
enum Piece {
    Text(String),
    Ref(Source),
}

/// Renders the values of one server for one client.
pub struct Renderer<'a> {
    rx: RenderEnv<'a>,
    policy: Policy<'a>,
    transport: Transport,
    modes: Vec<Mode>,
    launch: Vec<(String, Source)>,
    helper_refs: Vec<(String, Source)>,
    helper_headers: Vec<(String, String)>,
    /// Values written in plain text (`inline`), for masking.
    pub inline: Vec<SecretValue>,
    /// `inline_env_fallback` warnings.
    pub warnings: Vec<CoreError>,
}

impl<'a> Renderer<'a> {
    pub fn new(rx: RenderEnv<'a>, policy: Policy<'a>, transport: Transport) -> Self {
        Self {
            rx,
            policy,
            transport,
            modes: Vec::new(),
            launch: Vec::new(),
            helper_refs: Vec::new(),
            helper_headers: Vec::new(),
            inline: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// The entry's delivery: its most consequential mode, if it holds
    /// references.
    pub fn delivery(&self) -> Option<Mode> {
        self.modes.iter().copied().max()
    }

    /// A `command`, `args`, `cwd`, `url` or client field value.
    pub fn value(&mut self, text: &str, field: FieldSet) -> Result<String, CoreError> {
        let pieces = self.pieces(text)?;
        let sources = sources(&pieces);
        if sources.is_empty() {
            return self.literal(&pieces, field);
        }
        let mode = self.choose(field, &pieces, &sources, false)?;
        match mode {
            Mode::Env => self.spell(&pieces, field),
            Mode::Inline => self.inline_value(&pieces, field),
            Mode::Launch | Mode::Command => Err(CoreError::new(
                ErrorCode::DeliveryUnavailable,
                format!(
                    "`{}` cannot be delivered to `{}`",
                    mode.as_str(),
                    field_name(field)
                ),
            )),
        }
    }

    /// The value of stdio `env.<key>`.
    pub fn env_value(&mut self, key: &str, text: &str) -> Result<EnvValue, CoreError> {
        let pieces = self.pieces(text)?;
        let sources = sources(&pieces);
        if sources.is_empty() {
            return self.literal(&pieces, FieldSet::ENV).map(EnvValue::Value);
        }
        let whole = is_whole(&pieces);
        let forwardable = self.policy.forwards() && whole && sources[0].variable() == key;
        match self.choose(FieldSet::ENV, &pieces, &sources, forwardable)? {
            Mode::Env if forwardable => Ok(EnvValue::Forward(sources[0].variable().to_owned())),
            Mode::Env => self.spell(&pieces, FieldSet::ENV).map(EnvValue::Value),
            Mode::Launch => {
                let source = sources[0].clone();
                self.available(&source)?;
                self.launch.push((key.to_owned(), source));
                Ok(EnvValue::Launched)
            }
            Mode::Command => self.bang(&pieces).map(EnvValue::Value),
            Mode::Inline => self
                .inline_value(&pieces, FieldSet::ENV)
                .map(EnvValue::Value),
        }
    }

    /// The value of header `name`.
    pub fn header(&mut self, name: &str, text: &str) -> Result<HeaderValue, CoreError> {
        let pieces = self.pieces(text)?;
        let sources = sources(&pieces);
        if sources.is_empty() {
            return self
                .literal(&pieces, FieldSet::HEADERS)
                .map(HeaderValue::Value);
        }
        let whole = is_whole(&pieces);
        let bearer = name.eq_ignore_ascii_case("authorization")
            && matches!(pieces.as_slice(), [Piece::Text(prefix), Piece::Ref(_)] if prefix == "Bearer ");
        let forwardable = self.policy.forwards() && (whole || bearer);
        match self.choose(FieldSet::HEADERS, &pieces, &sources, forwardable)? {
            Mode::Env if forwardable => {
                let variable = sources[0].variable().to_owned();
                Ok(if bearer {
                    HeaderValue::Bearer(variable)
                } else {
                    HeaderValue::FromEnv(variable)
                })
            }
            Mode::Env => self
                .spell(&pieces, FieldSet::HEADERS)
                .map(HeaderValue::Value),
            Mode::Command if self.policy.caps.command_ref == Some(CommandRef::HeadersHelper) => {
                let template = self.template(&pieces, true)?;
                self.helper_headers.push((name.to_owned(), template));
                Ok(HeaderValue::Helper)
            }
            Mode::Command => self.bang(&pieces).map(HeaderValue::Value),
            Mode::Inline => self
                .inline_value(&pieces, FieldSet::HEADERS)
                .map(HeaderValue::Value),
            Mode::Launch => Err(CoreError::new(
                ErrorCode::DeliveryUnavailable,
                "`launch` delivery cannot bring a header value",
            )),
        }
    }

    /// Wraps the command in `surject exec` when a value is launched.
    pub fn finish_stdio(&mut self, stdio: &mut StdioLaunch) -> Result<(), CoreError> {
        if self.launch.is_empty() {
            return Ok(());
        }
        let launcher = self.rx.delivery.launcher(self.policy.sharing)?;
        let mut args = vec!["exec".to_owned()];
        let mut environment: Option<String> = None;
        let mut maps = Vec::new();
        if let Some(account) = self.op_account(self.launch.iter().map(|(_, s)| s)) {
            args.push("--op-account".to_owned());
            args.push(account.to_owned());
        }
        for (key, source) in &self.launch {
            match source.reference() {
                SecretRef::OnePasswordEnvironment {
                    environment: id,
                    name,
                } => {
                    if environment.as_ref().is_some_and(|other| *other != id) {
                        return Err(CoreError::new(
                            ErrorCode::DeliveryUnavailable,
                            "`surject exec` takes variables from one 1Password Environment per \
                             server; this server uses several",
                        ));
                    }
                    environment = Some(id);
                    maps.push(format!("{key}={name}"));
                }
                reference => {
                    args.push("--ref".to_owned());
                    args.push(format!("{key}={reference}"));
                }
            }
        }
        if let Some(id) = environment {
            args.push("--op-env".to_owned());
            args.push(id);
            for map in maps {
                args.push("--map".to_owned());
                args.push(map);
            }
        }
        args.push("--".to_owned());
        args.push(std::mem::take(&mut stdio.command));
        args.append(&mut stdio.args);
        stdio.command = launcher;
        stdio.args = args;
        Ok(())
    }

    /// Sets the `headersHelper` of the entry when a header uses it.
    pub fn finish_remote(&mut self, remote: &mut RemoteLaunch) -> Result<(), CoreError> {
        if self.helper_headers.is_empty() {
            return Ok(());
        }
        let os = self.rx.env.os();
        let mut command = vec![
            shell_quote(os, &self.rx.delivery.launcher(self.policy.sharing)?)?,
            "secret-header".to_owned(),
        ];
        if let Some(account) = self.op_account(self.helper_refs.iter().map(|(_, s)| s)) {
            command.push("--op-account".to_owned());
            command.push(shell_quote(os, account)?);
        }
        for (key, source) in &self.helper_refs {
            command.push("--ref".to_owned());
            command.push(shell_quote(os, &format!("{key}={}", source.reference()))?);
        }
        for (name, template) in &self.helper_headers {
            command.push(shell_quote(os, &format!("{name}={template}"))?);
        }
        remote.headers_helper = Some(command.join(" "));
        Ok(())
    }

    fn choose(
        &mut self,
        field: FieldSet,
        pieces: &[Piece],
        sources: &[Source],
        forwardable: bool,
    ) -> Result<Mode, CoreError> {
        let mode = self.policy.choose(&Slot {
            field,
            transport: self.transport,
            whole: is_whole(pieces),
            forwardable,
            sources,
        })?;
        if mode == Mode::Inline && self.policy.requested == DeliveryMode::Auto {
            let names: Vec<&str> = sources.iter().map(Source::variable).collect();
            self.warnings.push(CoreError::new(
                ErrorCode::InlineEnvFallback,
                format!(
                    "{} cannot get `${{env:{}}}` in `{}` otherwise; the value from {}'s \
                     environment is written into its config file",
                    self.policy.client,
                    names.join("}`, `${env:"),
                    field_name(field),
                    brand::PRODUCT_NAME
                ),
            ));
        }
        self.modes.push(mode);
        Ok(mode)
    }

    /// The template as pieces: path variables filled in, references looked
    /// up in the catalog.
    fn pieces(&self, text: &str) -> Result<Vec<Piece>, CoreError> {
        let mut pieces: Vec<Piece> = Vec::new();
        let push_text = |pieces: &mut Vec<Piece>, text: &str| match pieces.last_mut() {
            Some(Piece::Text(last)) => last.push_str(text),
            _ => pieces.push(Piece::Text(text.to_owned())),
        };
        for part in parse_template(text)? {
            match part {
                TemplatePart::Literal(literal) => push_text(&mut pieces, &literal),
                TemplatePart::Var(PathVar::Home) => {
                    push_text(&mut pieces, &self.rx.env.home().to_string_lossy());
                }
                TemplatePart::Var(PathVar::SurjectionHome) => {
                    push_text(&mut pieces, &self.rx.surjection_home.to_string_lossy());
                }
                TemplatePart::Var(PathVar::Project) => match self.rx.project {
                    Some(project) => push_text(&mut pieces, &project.to_string_lossy()),
                    None => {
                        return Err(CoreError::new(
                            ErrorCode::InvalidRef,
                            format!("`${{project}}` in {text:?} has no value at system scope"),
                        ));
                    }
                },
                TemplatePart::Env(name) => pieces.push(Piece::Ref(Source::Env { name })),
                TemplatePart::Secret(alias) => {
                    pieces.push(Piece::Ref(source_of_alias(self.rx.catalog, &alias)?));
                }
            }
        }
        Ok(pieces)
    }

    /// Literal text; escaped where the client has an escape (Pi), refused
    /// where the client would expand part of it otherwise
    /// ([`expanded_token`]).
    fn literal(&self, pieces: &[Piece], field: FieldSet) -> Result<String, CoreError> {
        let mut out = String::new();
        for piece in pieces {
            if let Piece::Text(text) = piece {
                self.push_literal(&mut out, text, field)?;
            }
        }
        Ok(self.guard_command(out, field))
    }

    /// Whether the client reads `$$` as a literal `$` and `$!` as a literal
    /// `!` in `field` (Pi), so literal text is written escaped.
    fn escapes(&self, field: FieldSet) -> bool {
        self.policy.env_syntax(field) == Some(EnvRefSyntax::Dollar)
    }

    /// Appends literal text the way the client reads it back unchanged.
    fn push_literal(&self, out: &mut String, text: &str, field: FieldSet) -> Result<(), CoreError> {
        push_literal(self.policy.env_syntax(field), self.policy.client, out, text)
    }

    /// `value` with a leading literal `!` written as `$!` where the client
    /// would otherwise run the value as a command (Pi). References are
    /// spelled with a leading `$`, so a leading `!` is always literal text;
    /// Surjection's own commands come from [`Renderer::bang`], never from here.
    fn guard_command(&self, value: String, field: FieldSet) -> String {
        guard_command(self.policy.env_syntax(field), value)
    }

    /// `env` delivery in the client's syntax.
    fn spell(&self, pieces: &[Piece], field: FieldSet) -> Result<String, CoreError> {
        let spelled: Vec<Spell<'_>> = pieces
            .iter()
            .map(|piece| match piece {
                Piece::Text(text) => Spell::Text(text),
                Piece::Ref(source) => Spell::Variable(source.variable()),
            })
            .collect();
        spell(self.policy.caps, self.policy.client, field, &spelled)
    }

    /// `inline` delivery: values resolved now. A resolved value is literal
    /// text too, escaped like any other; the escaped spelling is kept for
    /// masking as well when it differs.
    fn inline_value(&mut self, pieces: &[Piece], field: FieldSet) -> Result<String, CoreError> {
        let mut out = String::new();
        for piece in pieces {
            match piece {
                Piece::Text(text) => self.push_literal(&mut out, text, field)?,
                Piece::Ref(source) => {
                    let value = self.resolve(source)?;
                    if self.escapes(field) && value.expose().contains('$') {
                        let escaped = value.expose().replace('$', "$$");
                        self.rx.memory.record(&escaped);
                        out.push_str(&escaped);
                        self.inline.push(SecretValue::new(escaped));
                    } else {
                        // The value is secret: the message names the
                        // reference, never the value.
                        if let Some(token) =
                            expanded_token(self.policy.env_syntax(field), value.expose())
                        {
                            return Err(CoreError::new(
                                ErrorCode::DeliveryUnavailable,
                                format!(
                                    "{} would expand `{token}` in the value of `{}` written \
                                     inline; it has no escape for it (use another delivery mode)",
                                    self.policy.client,
                                    source.variable()
                                ),
                            ));
                        }
                        out.push_str(value.expose());
                    }
                    self.inline.push(value);
                }
            }
        }
        Ok(self.guard_command(out, field))
    }

    fn resolve(&self, source: &Source) -> Result<SecretValue, CoreError> {
        let value = match source {
            Source::Env { name } => {
                env::resolve(self.rx.env, name).map_err(|resolution| resolution.into_error(name))?
            }
            Source::Provider {
                alias,
                reference: SecretRef::OnePasswordEnvironment { .. },
                ..
            } => {
                return Err(CoreError::new(
                    ErrorCode::DeliveryUnavailable,
                    format!(
                        "{alias}: 1Password Environment variables reach a server only through \
                         `op run` when it starts (`launch` delivery); they are never written inline"
                    ),
                ));
            }
            Source::Provider {
                alias, reference, ..
            } => {
                let keyring = self.rx.delivery.keyring();
                let env = op_env(self.rx.env, keyring, self.rx.catalog.op_account.as_deref());
                let op = self.rx.delivery.op(self.rx.env, self.rx.fs);
                Resolver::new(&env, keyring, op, self.rx.memory.clone())
                    .resolve(reference)
                    .map_err(|resolution| resolution.into_error(alias))?
            }
        };
        self.rx.memory.record(value.expose());
        Ok(value)
    }

    fn available(&self, source: &Source) -> Result<(), CoreError> {
        check_available(
            source,
            self.rx.env,
            self.rx.fs,
            self.rx.delivery,
            self.rx.memory,
        )
    }

    /// `--op-account` for a `surject` command resolving `sources`: the
    /// configured 1Password account when any of them is a 1Password
    /// reference (gate V1 FB-7). Never in a shared file: the account is
    /// this machine's, so a committed file relies on `OP_ACCOUNT` or each
    /// machine's own setting, which `surject exec` reads at run time.
    fn op_account<'s>(&self, mut sources: impl Iterator<Item = &'s Source>) -> Option<&'a str> {
        if self.policy.sharing == Sharing::Shared {
            return None;
        }
        let account = self.rx.catalog.op_account.as_deref()?;
        sources
            .any(|source| {
                matches!(
                    source.reference(),
                    SecretRef::OnePassword { .. } | SecretRef::OnePasswordEnvironment { .. }
                )
            })
            .then_some(account)
    }

    /// `!<surjection> secret get --ref REF` (omp, Pi), with a template when the
    /// value has text around the reference.
    fn bang(&mut self, pieces: &[Piece]) -> Result<String, CoreError> {
        let os = self.rx.env.os();
        let launcher = shell_quote(os, &self.rx.delivery.launcher(self.policy.sharing)?)?;
        let mut command = format!("!{launcher} secret get");
        if let [Piece::Ref(source)] = pieces {
            self.available(source)?;
            if let Some(account) = self.op_account(std::iter::once(source)) {
                command.push_str(&format!(" --op-account {}", shell_quote(os, account)?));
            }
            command.push_str(&format!(
                " --ref {}",
                shell_quote(os, &source.reference().to_string())?
            ));
            return Ok(command);
        }
        let start = self.helper_refs.len();
        let template = self.template(pieces, false)?;
        let bound: Vec<(String, Source)> = self.helper_refs.drain(start..).collect();
        if let Some(account) = self.op_account(bound.iter().map(|(_, s)| s)) {
            command.push_str(&format!(" --op-account {}", shell_quote(os, account)?));
        }
        for (key, source) in &bound {
            command.push_str(&format!(
                " --ref {}",
                shell_quote(os, &format!("{key}={}", source.reference()))?
            ));
        }
        command.push_str(&format!(" --template {}", shell_quote(os, &template)?));
        Ok(command)
    }

    /// The pieces as a command template; references are bound in
    /// `helper_refs` (shared by every header of a `headersHelper` when
    /// `shared`).
    fn template(&mut self, pieces: &[Piece], shared: bool) -> Result<String, CoreError> {
        let start = if shared { 0 } else { self.helper_refs.len() };
        let mut out = String::new();
        for piece in pieces {
            match piece {
                Piece::Text(text) => {
                    if text.contains(PLACEHOLDER) {
                        return Err(CoreError::new(
                            ErrorCode::DeliveryUnavailable,
                            format!(
                                "the literal {PLACEHOLDER:?} in {text:?} cannot be written in a command template"
                            ),
                        ));
                    }
                    out.push_str(text);
                }
                Piece::Ref(source) => {
                    self.available(source)?;
                    let key = source.label().to_owned();
                    let bound = self.helper_refs[start..].iter().find(|(k, _)| *k == key);
                    match bound {
                        Some((_, existing)) if existing != source => {
                            return Err(CoreError::new(
                                ErrorCode::DeliveryUnavailable,
                                format!("{key} names two different references here"),
                            ));
                        }
                        Some(_) => {}
                        None => self.helper_refs.push((key.clone(), source.clone())),
                    }
                    out.push_str(&format!("{PLACEHOLDER}{key}}}"));
                }
            }
        }
        Ok(out)
    }
}

/// One part of a value spelled in a client's own variable syntax
/// ([`spell`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Spell<'a> {
    /// Literal text.
    Text(&'a str),
    /// A variable the client expands itself.
    Variable(&'a str),
}

/// `pieces` as `client` writes them in `field` (SPEC 11.4 `env` delivery):
/// each variable in the client's syntax, literal text escaped where the
/// client has an escape (Pi) and refused where the client would expand part
/// of it. `delivery_unavailable` when the client does not expand variables
/// in `field`.
pub fn spell(
    caps: &Caps,
    client: &str,
    field: FieldSet,
    pieces: &[Spell<'_>],
) -> Result<String, CoreError> {
    let syntax = env_syntax(caps, field);
    let mut out = String::new();
    for piece in pieces {
        match piece {
            Spell::Text(text) => push_literal(syntax, client, &mut out, text)?,
            Spell::Variable(name) => match syntax {
                Some(EnvRefSyntax::DollarBrace { .. } | EnvRefSyntax::Dollar) => {
                    out.push_str(&format!("${{{name}}}"));
                }
                Some(EnvRefSyntax::DollarBraceEnv) => out.push_str(&format!("${{env:{name}}}")),
                Some(EnvRefSyntax::BraceEnv) => out.push_str(&format!("{{env:{name}}}")),
                Some(EnvRefSyntax::CodexForward) | None => {
                    return Err(CoreError::new(
                        ErrorCode::DeliveryUnavailable,
                        format!(
                            "{client} does not expand variables in `{}`",
                            field_name(field)
                        ),
                    ));
                }
            },
        }
    }
    Ok(guard_command(syntax, out))
}

/// Appends literal text the way a client expanding `syntax` reads it back
/// unchanged: escaped for Pi, refused where the client has no escape.
fn push_literal(
    syntax: Option<EnvRefSyntax>,
    client: &str,
    out: &mut String,
    text: &str,
) -> Result<(), CoreError> {
    if syntax == Some(EnvRefSyntax::Dollar) {
        out.push_str(&text.replace('$', "$$"));
    } else {
        check_literal(syntax, client, text)?;
        out.push_str(text);
    }
    Ok(())
}

fn check_literal(syntax: Option<EnvRefSyntax>, client: &str, text: &str) -> Result<(), CoreError> {
    if let Some(token) = expanded_token(syntax, text) {
        return Err(CoreError::new(
            ErrorCode::DeliveryUnavailable,
            format!(
                "{client} would expand the literal `{token}` in {text:?}; it has no escape for it"
            ),
        ));
    }
    Ok(())
}

/// `value` with a leading `!` written as `$!` for Pi (`Dollar`), which
/// would otherwise run the value as a command.
fn guard_command(syntax: Option<EnvRefSyntax>, mut value: String) -> String {
    if syntax == Some(EnvRefSyntax::Dollar) && value.starts_with('!') {
        value.insert(0, '$');
    }
    value
}

fn sources(pieces: &[Piece]) -> Vec<Source> {
    pieces
        .iter()
        .filter_map(|piece| match piece {
            Piece::Ref(source) => Some(source.clone()),
            Piece::Text(_) => None,
        })
        .collect()
}

fn is_whole(pieces: &[Piece]) -> bool {
    matches!(pieces, [Piece::Ref(_)])
}

/// The part of literal `text` a client expanding `syntax` would replace,
/// when the client has no escape for it: `${` (`DollarBrace`,
/// `DollarBraceEnv`), also `$` before a name character (`DollarBrace` with
/// `bare`), `{env:` or `{file:` (`BraceEnv`). `None` for text the client
/// reads as written, and for Pi (`Dollar`), whose literals are escaped.
fn expanded_token(syntax: Option<EnvRefSyntax>, text: &str) -> Option<&'static str> {
    match syntax? {
        EnvRefSyntax::DollarBrace { bare, .. } => {
            if text.contains("${") {
                Some("${")
            } else if bare
                && text.as_bytes().windows(2).any(|pair| {
                    pair[0] == b'$' && (pair[1].is_ascii_alphanumeric() || pair[1] == b'_')
                })
            {
                Some("$NAME")
            } else {
                None
            }
        }
        EnvRefSyntax::DollarBraceEnv => text.contains("${").then_some("${"),
        EnvRefSyntax::BraceEnv => ["{env:", "{file:"]
            .into_iter()
            .find(|token| text.contains(token)),
        EnvRefSyntax::Dollar | EnvRefSyntax::CodexForward => None,
    }
}

/// One argument of a command line run through the client's shell: single
/// quotes on Unix; double quotes on Windows. Which shell a Windows client
/// uses (`cmd.exe`, or a POSIX shell such as Git Bash) is not settled
/// (`scripts/verify-clients.md` DX-6, DX-7), so only text both read the
/// same inside double quotes passes: `"`, `%`, `$`, a backtick, a line
/// break and a trailing backslash are refused.
pub fn shell_quote(os: Os, text: &str) -> Result<String, CoreError> {
    match os {
        Os::Linux | Os::MacOs => Ok(format!("'{}'", text.replace('\'', r"'\''"))),
        Os::Windows => {
            if text.contains(['"', '%', '$', '`', '\n', '\r']) || text.ends_with('\\') {
                return Err(CoreError::new(
                    ErrorCode::DeliveryUnavailable,
                    format!(
                        "{text:?} cannot be quoted for a Windows command line (`\"`, `%`, `$`, a \
                         backtick, a line break or a trailing backslash)"
                    ),
                ));
            }
            Ok(format!("\"{text}\""))
        }
    }
}

/// Renders a command template: each `{secret:KEY}` becomes `values[KEY]`.
/// Fails on a placeholder with no value or an unterminated one.
pub fn fill_template(
    template: &str,
    values: &[(String, SecretValue)],
) -> Result<SecretValue, CoreError> {
    let mut out = String::new();
    let mut rest = template;
    while let Some(start) = rest.find(PLACEHOLDER) {
        out.push_str(&rest[..start]);
        let after = &rest[start + PLACEHOLDER.len()..];
        let end = after.find('}').ok_or_else(|| {
            CoreError::new(
                ErrorCode::InvalidRef,
                format!("unterminated {PLACEHOLDER:?} in the template"),
            )
        })?;
        let key = &after[..end];
        let value = values
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value)
            .ok_or_else(|| {
                CoreError::new(
                    ErrorCode::InvalidRef,
                    format!(
                        "the template uses {PLACEHOLDER}{key}}} but no --ref {key}=REF is given"
                    ),
                )
            })?;
        out.push_str(value.expose());
        rest = &after[end + 1..];
    }
    out.push_str(rest);
    Ok(SecretValue::new(out))
}

/// `KEY=REF` as given to `surject exec`, `secret get` and `secret-header`:
/// the key is a variable name, the reference a provider reference.
pub fn parse_binding(text: &str) -> Result<(String, SecretRef), CoreError> {
    let invalid = || {
        CoreError::new(
            ErrorCode::InvalidRef,
            format!("expected NAME=REF (a variable name and a provider reference), got {text:?}"),
        )
    };
    let (key, reference) = text.split_once('=').ok_or_else(invalid)?;
    if !crate::model::ids::is_valid(crate::model::ids::IdKind::EnvVar, key) {
        return Err(invalid());
    }
    Ok((key.to_owned(), SecretRef::parse(reference)?))
}