dekopon-shell 0.5.0

Sandboxed bash-flavored script interpreter whose commands dispatch to Dekopon capabilities
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
//! Command-word resolution and the argv-to-JSON convention for capability calls.
//!
//! Resolution order is fixed:
//!
//! 1. words this shell refuses outright (`eval`, `exec`, `source`, job control, `declare`),
//! 2. shell functions declared earlier in the same script,
//! 3. the fixed builtin table,
//! 4. capability fallback, and
//! 5. `cap <id>`, which is itself a builtin and therefore already covered by step 3.
//!
//! Otherwise the word is "command not found", exit code 127.
//!
//! Steps 3 and 4 cannot collide. Every builtin name is separator-free, and capability fallback only
//! fires for words containing `.`, `-`, or `_`. The two sets are disjoint by construction, not by
//! luck, and [`tests::builtin_and_capability_namespaces_are_disjoint`] proves it.

use std::collections::BTreeSet;

use dekopon_core::CapabilityId;
use serde_json::Value;

use crate::{
    CapabilityInvoker,
    builtins::{self, BuiltinKind, CommandFailure},
    parser::REJECTED_COMMANDS,
    value::{object_from_pairs, scalar_from_token},
};

/// How one command word resolves.
pub(crate) enum Resolution {
    /// A shell function declared earlier in this script.
    Function,
    /// A builtin.
    Builtin(BuiltinKind),
    /// A granted capability, invoked through the fallback rule.
    Capability,
    /// A command word a loaded provider contributed, rewritten by that provider into a proposal.
    ProviderCommand,
    /// A capability identifier in a namespace this session holds, but not one it was granted.
    ///
    /// Dispatches exactly as [`Resolution::NotFound`] does — same message, same exit code. The
    /// distinction exists only for telemetry: it is the difference between "the model typed
    /// nonsense" and "the model keeps reaching for something we never granted", and only the
    /// second is a trend worth acting on.
    NotGranted {
        /// The provider namespace, taken from the session's own granted set.
        namespace: String,
    },
    /// A word this shell refuses, with the reason why.
    Rejected(&'static str),
    /// Nothing matched.
    NotFound,
}

/// Resolves one command word.
pub(crate) fn resolve(
    word: &str,
    functions: &BTreeSet<String>,
    invoker: &dyn CapabilityInvoker,
) -> Resolution {
    if let Some((_, reason)) = REJECTED_COMMANDS
        .iter()
        .find(|(rejected, _)| *rejected == word)
    {
        return Resolution::Rejected(reason);
    }
    if functions.contains(word) {
        return Resolution::Function;
    }
    if let Some(builtin) = builtins::lookup(word) {
        return Resolution::Builtin(builtin);
    }
    // After builtins, so a provider can never shadow one. A provider claiming a builtin name is
    // refused at load rather than silently losing here; this ordering is the second line.
    if invoker
        .command_words()
        .iter()
        .any(|candidate| candidate == word)
    {
        return Resolution::ProviderCommand;
    }
    if looks_like_capability(word) {
        if invoker.is_granted(word) {
            return Resolution::Capability;
        }
        if let Some(namespace) = granted_namespace_of(word, invoker) {
            return Resolution::NotGranted { namespace };
        }
    }
    Resolution::NotFound
}

/// Returns the provider namespace of a word, when this session already holds that namespace.
///
/// Deliberately bounded by the session's *own* granted set rather than by anything global. The
/// namespace it returns is therefore always a string the deployment chose, never one the model
/// composed, which is what makes it safe to export while the word itself stays withheld. A word in
/// a namespace the session does not hold reveals nothing and yields `None`.
fn granted_namespace_of(word: &str, invoker: &dyn CapabilityInvoker) -> Option<String> {
    let namespace = word.split('.').next()?;
    if namespace.is_empty() || namespace == word {
        return None;
    }
    invoker
        .granted()
        .iter()
        .any(|granted| {
            granted
                .split('.')
                .next()
                .is_some_and(|candidate| candidate == namespace)
        })
        .then(|| namespace.to_owned())
}

/// Reports whether a word could be a capability identifier.
///
/// A capability identifier is not *required* to contain a separator by `dekopon-core`'s rules, but
/// this shell requires one before it will try capability fallback. That extra condition is what
/// keeps the builtin and capability namespaces provably disjoint; a separator-free capability
/// remains reachable through `cap <id>`.
#[must_use]
pub(crate) fn looks_like_capability(word: &str) -> bool {
    word.contains(['.', '-', '_']) && word.parse::<CapabilityId>().is_ok()
}

/// Converts argv into a capability input object.
///
/// `some.capability --post-id 7 --include-body` becomes `{"postId": 7, "includeBody": true}`, so
/// kebab-case flags land on the camelCase keys this workspace uses everywhere. A single bare
/// argument starting with `{` bypasses conversion and is parsed as the literal input object.
pub(crate) fn arguments_to_input(
    command: &str,
    arguments: &[String],
) -> Result<Value, CommandFailure> {
    if arguments.is_empty() {
        return Ok(Value::Object(serde_json::Map::new()));
    }

    if let [single] = arguments
        && single.trim_start().starts_with('{')
    {
        let parsed = serde_json::from_str::<Value>(single).map_err(|error| {
            CommandFailure::usage(format!("{command}: input is not valid JSON: {error}"))
        })?;
        if !parsed.is_object() {
            return Err(CommandFailure::usage(format!(
                "{command}: capability input must be a JSON object"
            )));
        }
        return Ok(parsed);
    }

    let mut pairs = Vec::new();
    let mut index = 0;
    while index < arguments.len() {
        let argument = arguments[index].as_str();
        let Some(flag) = argument.strip_prefix("--") else {
            return Err(CommandFailure::usage(format!(
                "{command}: unexpected argument {argument:?}; pass capability input as --kebab-case flags or one JSON object"
            )));
        };
        if flag.is_empty() {
            return Err(CommandFailure::usage(format!(
                "{command}: `--` is not a capability input flag"
            )));
        }

        let key = to_camel_case(flag);
        match arguments.get(index + 1) {
            // A flag followed by another flag, or nothing, is a boolean present-flag.
            None => {
                pairs.push((key, Value::Bool(true)));
                index += 1;
            }
            Some(next) if next.starts_with("--") => {
                pairs.push((key, Value::Bool(true)));
                index += 1;
            }
            Some(next) => {
                pairs.push((key, scalar_from_token(next)));
                index += 2;
            }
        }
    }

    Ok(object_from_pairs(pairs))
}

/// Converts one kebab-case flag name to camelCase.
fn to_camel_case(flag: &str) -> String {
    let mut output = String::with_capacity(flag.len());
    let mut capitalize = false;
    for character in flag.chars() {
        if character == '-' || character == '_' {
            capitalize = true;
            continue;
        }
        if capitalize {
            output.extend(character.to_uppercase());
            capitalize = false;
        } else {
            output.push(character);
        }
    }
    output
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use serde_json::{Value, json};

    use crate::{CapabilityCallResult, CapabilityInvoker, builtins};

    use super::{Resolution, arguments_to_input, looks_like_capability, resolve, to_camel_case};

    struct Granted;

    impl CapabilityInvoker for Granted {
        fn granted(&self) -> Vec<String> {
            vec![
                "echo.echo".to_owned(),
                "http-probe.fetch".to_owned(),
                "with_underscore".to_owned(),
            ]
        }

        fn invoke(&self, _capability: &str, input: Value) -> CapabilityCallResult {
            CapabilityCallResult::Succeeded(input)
        }
    }

    fn arguments(items: &[&str]) -> Vec<String> {
        items.iter().map(|item| (*item).to_owned()).collect()
    }

    #[test]
    fn resolution_follows_the_documented_priority_order() {
        let mut functions = BTreeSet::new();
        functions.insert("greet".to_owned());

        assert!(matches!(
            resolve("greet", &functions, &Granted),
            Resolution::Function
        ));
        assert!(matches!(
            resolve("jq", &functions, &Granted),
            Resolution::Builtin(_)
        ));
        assert!(matches!(
            resolve("echo.echo", &functions, &Granted),
            Resolution::Capability
        ));
        assert!(matches!(
            resolve("eval", &functions, &Granted),
            Resolution::Rejected(_)
        ));
        assert!(matches!(
            resolve("nothing.here", &functions, &Granted),
            Resolution::NotFound
        ));
        assert!(matches!(
            resolve("unknown", &functions, &Granted),
            Resolution::NotFound
        ));
    }

    #[test]
    fn a_function_takes_priority_over_a_granted_capability() {
        let mut functions = BTreeSet::new();
        functions.insert("echo.echo".to_owned());
        assert!(matches!(
            resolve("echo.echo", &functions, &Granted),
            Resolution::Function
        ));
    }

    #[test]
    fn a_function_shadows_a_builtin_only_by_being_declared() {
        let mut functions = BTreeSet::new();
        assert!(matches!(
            resolve("jq", &functions, &Granted),
            Resolution::Builtin(_)
        ));
        functions.insert("jq".to_owned());
        assert!(matches!(
            resolve("jq", &functions, &Granted),
            Resolution::Function
        ));
    }

    #[test]
    fn builtin_and_capability_namespaces_are_disjoint() {
        // Capability fallback demands a separator; builtin names have none. No word can satisfy
        // both rules, so no builtin can ever be shadowed by a granted capability.
        for name in builtins::names() {
            assert!(
                !looks_like_capability(name),
                "builtin {name:?} is reachable through capability fallback"
            );
        }
        assert!(looks_like_capability("echo.echo"));
        assert!(looks_like_capability("http-probe.fetch"));
        assert!(looks_like_capability("with_underscore"));
        // Separator-free identifiers are valid capability IDs but stay out of fallback on purpose.
        assert!(!looks_like_capability("echo"));
        assert!(!looks_like_capability("Echo.Echo"));
        assert!(!looks_like_capability("bad..id"));
    }

    #[test]
    fn kebab_flags_become_camel_case_keys() {
        assert_eq!(to_camel_case("post-id"), "postId");
        assert_eq!(to_camel_case("include-body"), "includeBody");
        assert_eq!(to_camel_case("id"), "id");
        assert_eq!(to_camel_case("a-b-c"), "aBC");
    }

    #[test]
    fn argv_converts_to_the_camel_case_input_object() {
        assert_eq!(
            arguments_to_input("cap", &arguments(&["--post-id", "7", "--include-body"]))
                .expect("valid argv"),
            json!({"postId": 7, "includeBody": true})
        );
        assert_eq!(
            arguments_to_input("cap", &arguments(&["--message", "hello"])).expect("valid argv"),
            json!({"message": "hello"})
        );
        assert_eq!(
            arguments_to_input("cap", &arguments(&[])).expect("valid argv"),
            json!({})
        );
    }

    #[test]
    fn a_single_json_argument_bypasses_flag_conversion() {
        assert_eq!(
            arguments_to_input("cap", &arguments(&[r#"{"postId": 7}"#])).expect("valid argv"),
            json!({"postId": 7})
        );
        assert!(arguments_to_input("cap", &arguments(&["{not json}"])).is_err());
        assert!(arguments_to_input("cap", &arguments(&["{\"a\": 1}", "extra"])).is_err());
    }

    #[test]
    fn repeated_flags_fold_into_arrays() {
        assert_eq!(
            arguments_to_input("cap", &arguments(&["--tag", "a", "--tag", "b"]))
                .expect("valid argv"),
            json!({"tag": ["a", "b"]})
        );
    }

    #[test]
    fn positional_arguments_are_rejected_with_guidance() {
        let failure =
            arguments_to_input("cap", &arguments(&["bare"])).expect_err("bare words are rejected");
        assert!(format!("{failure:?}").contains("kebab-case"), "{failure:?}");
    }
}

#[cfg(test)]
mod reserved {
    use std::collections::BTreeSet;

    use crate::{builtins, interp::telemetry::CONTROL_WORDS, parser::REJECTED_COMMANDS};

    /// `dekopon_core::RESERVED_COMMAND_WORDS` and this crate's live tables must agree exactly.
    ///
    /// The list lives in `dekopon-core` so the broker can report command-word conflicts at its own
    /// startup without linking an interpreter it never runs. That mirroring is only safe while it
    /// is checked, and it has to be checked in **both** directions.
    ///
    /// Missing a word means a provider could claim something the shell would then shadow, and the
    /// manifest would be a lie. Reserving a word no table owns is the opposite failure and the one
    /// worth naming: when the `gh` builtin is deleted and `gh` becomes an ordinary provider command
    /// word, a stale entry here would keep the real `gh` provider from claiming its own name.
    #[test]
    fn the_reserved_list_matches_the_shells_own_tables() {
        let live = builtins::names()
            .into_iter()
            .chain(CONTROL_WORDS.iter().copied())
            .chain(REJECTED_COMMANDS.iter().map(|(word, _)| *word))
            .collect::<BTreeSet<_>>();
        let declared = dekopon_core::RESERVED_COMMAND_WORDS
            .iter()
            .copied()
            .collect::<BTreeSet<_>>();

        let missing = live.difference(&declared).collect::<Vec<_>>();
        assert!(
            missing.is_empty(),
            "dekopon_core::RESERVED_COMMAND_WORDS is missing {missing:?}; a provider could claim \
             one and be silently shadowed"
        );
        let stale = declared.difference(&live).collect::<Vec<_>>();
        assert!(
            stale.is_empty(),
            "dekopon_core::RESERVED_COMMAND_WORDS reserves {stale:?}, which no table owns; a \
             provider that should be able to claim one cannot"
        );
    }
}