dekopon-shell 0.46.2

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
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
//! This interpreter is native Rust, not Wasm, so there is no fuel meter, memory ceiling, or engine
//! deadline to fall back on; every bound a script can exhaust must be owned and enforced here.

use std::{collections::VecDeque, time::Duration};

use crate::{CallBudget, CapabilityInvoker, TreeContext};

pub const DEFAULT_MAX_STEPS: u64 = 100_000;
/// Function calls, `$( )`, `${ }` and compound commands all recurse on the native stack against
/// this one depth; 32 keeps the deepest measured script inside a 2 MiB thread even in a debug build.
pub const DEFAULT_MAX_RECURSION_DEPTH: u32 = 32;
pub const DEFAULT_MAX_OUTPUT_BYTES: usize = 256 * 1024;
pub const DEFAULT_MAX_OUTPUT_LINES: usize = 2_000;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_MAX_CAPABILITY_CALLS: u32 = 32;
pub const DEFAULT_MAX_VALUE_BYTES: u64 = 32 * 1024 * 1024;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Limits {
    pub max_steps: u64,
    pub max_recursion_depth: u32,
    pub max_output_bytes: usize,
    pub max_output_lines: usize,
    pub timeout: Duration,
    pub max_capability_calls: u32,
    pub max_value_bytes: u64,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_steps: DEFAULT_MAX_STEPS,
            max_recursion_depth: DEFAULT_MAX_RECURSION_DEPTH,
            max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
            max_output_lines: DEFAULT_MAX_OUTPUT_LINES,
            timeout: DEFAULT_TIMEOUT,
            max_capability_calls: DEFAULT_MAX_CAPABILITY_CALLS,
            max_value_bytes: DEFAULT_MAX_VALUE_BYTES,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LimitExceeded {
    Steps { maximum: u64 },
    RecursionDepth { maximum: u32 },
    Deadline { timeout_ms: u128 },
    CapabilityCalls { maximum: u32 },
    ValueBytes { maximum: u64 },
    Cancelled,
}

#[derive(Debug)]
pub struct Budget {
    limits: Limits,
    tree: TreeContext,
    depth: u32,
}

impl Budget {
    #[must_use]
    pub fn start(limits: Limits) -> Self {
        Self::start_tree(
            limits,
            TreeContext::new(limits, CallBudget::new(limits.max_capability_calls)),
        )
    }

    #[must_use]
    pub fn start_tree(limits: Limits, tree: TreeContext) -> Self {
        Self {
            limits,
            tree,
            depth: 0,
        }
    }

    pub(crate) const fn tree(&self) -> &TreeContext {
        &self.tree
    }

    pub(crate) fn fork(&self) -> Self {
        Self {
            limits: self.limits,
            tree: self.tree.clone(),
            depth: self.depth,
        }
    }

    pub fn charge_step_with(
        &mut self,
        invoker: &dyn CapabilityInvoker,
    ) -> Result<(), LimitExceeded> {
        if invoker.cancelled() {
            Err(LimitExceeded::Cancelled)
        } else {
            self.charge_step()
        }
    }

    /// This is the only backstop against an infinite loop; the deadline is re-read every step
    /// rather than sampled, since a script can spend minutes in very few steps and a sampled clock
    /// would leave it unbounded.
    pub fn charge_step(&mut self) -> Result<(), LimitExceeded> {
        self.tree.charge_step()?;
        self.check_deadline()
    }

    pub fn charge_value_bytes(&self, bytes: u64) -> Result<crate::RetainedBytes, LimitExceeded> {
        self.tree.retain(bytes)
    }

    pub fn check_deadline(&self) -> Result<(), LimitExceeded> {
        self.tree.check_deadline()
    }

    #[must_use]
    pub fn remaining(&self) -> Duration {
        self.tree.remaining()
    }

    pub fn enter_nesting(&mut self) -> Result<(), LimitExceeded> {
        if self.depth >= self.limits.max_recursion_depth {
            return Err(LimitExceeded::RecursionDepth {
                maximum: self.limits.max_recursion_depth,
            });
        }
        self.depth = self.depth.saturating_add(1);
        Ok(())
    }

    pub fn leave_nesting(&mut self) {
        self.depth = self.depth.saturating_sub(1);
    }

    /// Capability calls are budgeted independently of steps, since one script can loop to drive
    /// many calls where a single model tool call drives exactly one today, and that amplification
    /// needs its own ceiling.
    pub fn charge_capability_call(&mut self) -> Result<(), LimitExceeded> {
        self.tree.calls().charge()
    }

    #[must_use]
    pub fn capability_calls(&self) -> u32 {
        self.tree.calls().used()
    }

    #[must_use]
    pub fn steps(&self) -> u64 {
        self.tree.steps()
    }

    #[must_use]
    pub fn value_bytes(&self) -> u64 {
        self.tree.value_bytes()
    }

    #[must_use]
    pub fn max_value_bytes(&self) -> u64 {
        self.tree.max_value_bytes()
    }
}

/// Byte and line ceilings are independent so one oversized line cannot slip past a line-count-only
/// limit; when either trips, both head and tail are kept, since head-only truncation would hide the
/// final result.
#[derive(Debug)]
pub struct OutputBuffer {
    max_bytes: usize,
    max_lines: usize,
    head: Vec<String>,
    head_bytes: usize,
    tail: VecDeque<String>,
    tail_bytes: usize,
    total_lines: usize,
    truncated: bool,
    pending: String,
    pending_truncated: bool,
}

impl OutputBuffer {
    #[must_use]
    pub fn new(limits: &Limits) -> Self {
        Self {
            max_bytes: limits.max_output_bytes.max(1),
            max_lines: limits.max_output_lines.max(1),
            head: Vec::new(),
            head_bytes: 0,
            tail: VecDeque::new(),
            tail_bytes: 0,
            total_lines: 0,
            truncated: false,
            pending: String::new(),
            pending_truncated: false,
        }
    }

    fn tail_line_budget(&self) -> usize {
        (self.max_lines / 2).max(1)
    }

    fn tail_byte_budget(&self) -> usize {
        (self.max_bytes / 2).max(1)
    }

    pub fn push_line(&mut self, line: &str) {
        self.total_lines = self.total_lines.saturating_add(1);

        if !self.truncated {
            let clamped = clamp_line(line, self.max_bytes);
            let cost = clamped.len().saturating_add(1);
            let fits = self.head.len() < self.max_lines
                && self.head_bytes.saturating_add(cost) <= self.max_bytes;
            if fits {
                self.head_bytes = self.head_bytes.saturating_add(cost);
                self.head.push(clamped);
                return;
            }
            self.begin_truncation();
        }

        let clamped = clamp_line(line, self.tail_byte_budget().saturating_sub(1));
        self.tail_bytes = self
            .tail_bytes
            .saturating_add(clamped.len().saturating_add(1));
        self.tail.push_back(clamped);
        self.evict_tail();
    }

    pub fn push_fragment(&mut self, fragment: &str) {
        for (index, part) in fragment.split('\n').enumerate() {
            if index != 0 {
                self.flush_pending();
            }
            if !self.pending_truncated {
                let room = self.max_bytes.saturating_sub(self.pending.len());
                let mut end = part.len().min(room);
                while !part.is_char_boundary(end) {
                    end -= 1;
                }
                self.pending.push_str(&part[..end]);
                if end < part.len() {
                    self.pending_truncated = true;
                }
            }
        }
    }

    pub fn push_block(&mut self, block: &str) {
        self.push_fragment(block);
        self.flush_pending();
    }

    fn flush_pending(&mut self) {
        let mut line = std::mem::take(&mut self.pending);
        if self.pending_truncated {
            line = clamp_line(&line, self.max_bytes);
            self.pending_truncated = false;
        }
        self.push_line(&line);
    }

    pub fn finish(&mut self) {
        if !self.pending.is_empty() || self.pending_truncated {
            self.flush_pending();
        }
    }

    fn begin_truncation(&mut self) {
        self.truncated = true;
        let head_lines = self.max_lines.saturating_sub(self.tail_line_budget());
        let head_bytes = self.max_bytes.saturating_sub(self.tail_byte_budget());
        while self.head.len() > head_lines || self.head_bytes > head_bytes {
            let Some(dropped) = self.head.pop() else {
                break;
            };
            self.head_bytes = self
                .head_bytes
                .saturating_sub(dropped.len().saturating_add(1));
        }
    }

    fn evict_tail(&mut self) {
        while self.tail.len() > 1
            && (self.tail.len() > self.tail_line_budget()
                || self.tail_bytes > self.tail_byte_budget())
        {
            let Some(dropped) = self.tail.pop_front() else {
                break;
            };
            self.tail_bytes = self
                .tail_bytes
                .saturating_sub(dropped.len().saturating_add(1));
        }
    }

    #[must_use]
    pub fn is_truncated(&self) -> bool {
        self.truncated
    }

    #[must_use]
    pub fn render(&self) -> String {
        let mut lines = Vec::with_capacity(self.head.len() + self.tail.len() + 1);
        lines.extend(self.head.iter().cloned());
        if self.truncated {
            lines.push(format!(
                "... Output truncated ({} total lines) ...",
                self.total_lines
            ));
            lines.extend(self.tail.iter().cloned());
        }
        lines.join("\n")
    }
}

/// The truncation marker counts against the budget itself, so appending it after clamping cannot
/// push a line back over the ceiling and get it dropped entirely.
fn clamp_line(line: &str, maximum: usize) -> String {
    if line.len() <= maximum {
        return line.to_owned();
    }
    const MARKER: &str = "...";
    let mut end = maximum.saturating_sub(MARKER.len());
    while end > 0 && !line.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}{MARKER}", &line[..end])
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::{Budget, LimitExceeded, Limits, OutputBuffer};

    #[test]
    fn step_budget_trips_at_the_configured_ceiling() {
        let mut budget = Budget::start(Limits {
            max_steps: 3,
            ..Limits::default()
        });
        assert!(budget.charge_step().is_ok());
        assert!(budget.charge_step().is_ok());
        assert!(budget.charge_step().is_ok());
        assert_eq!(
            budget.charge_step(),
            Err(LimitExceeded::Steps { maximum: 3 })
        );
    }

    #[test]
    fn recursion_depth_is_capped_and_released() {
        let mut budget = Budget::start(Limits {
            max_recursion_depth: 2,
            ..Limits::default()
        });
        assert!(budget.enter_nesting().is_ok());
        assert!(budget.enter_nesting().is_ok());
        assert_eq!(
            budget.enter_nesting(),
            Err(LimitExceeded::RecursionDepth { maximum: 2 })
        );
        budget.leave_nesting();
        assert!(budget.enter_nesting().is_ok());
    }

    #[test]
    fn capability_calls_are_counted_separately_from_steps() {
        let mut budget = Budget::start(Limits {
            max_capability_calls: 1,
            ..Limits::default()
        });
        assert!(budget.charge_capability_call().is_ok());
        assert_eq!(
            budget.charge_capability_call(),
            Err(LimitExceeded::CapabilityCalls { maximum: 1 })
        );
        assert_eq!(budget.steps(), 0);
        assert_eq!(budget.capability_calls(), 1);
    }

    #[test]
    fn retained_bytes_are_shared_and_refunded_on_drop() {
        let first = Budget::start(Limits {
            max_value_bytes: 10,
            ..Limits::default()
        });
        let second = Budget::start_tree(Limits::default(), first.tree.clone());
        let retained = first.charge_value_bytes(6).expect("fits");
        assert!(matches!(
            second.charge_value_bytes(6),
            Err(LimitExceeded::ValueBytes { maximum: 10 })
        ));
        assert_eq!(second.value_bytes(), 6);
        drop(retained);
        assert_eq!(second.value_bytes(), 0);
        assert!(second.charge_value_bytes(6).is_ok());
    }

    #[test]
    fn two_budgets_share_one_step_allowance() {
        let mut first = Budget::start(Limits {
            max_steps: 3,
            ..Limits::default()
        });
        let mut second = Budget::start_tree(Limits::default(), first.tree.clone());
        first.charge_step().expect("first");
        second.charge_step().expect("second");
        first.charge_step().expect("third");
        assert_eq!(
            second.charge_step(),
            Err(LimitExceeded::Steps { maximum: 3 })
        );
        assert_eq!(first.steps(), second.steps());
    }

    #[test]
    fn an_expired_deadline_is_reported_immediately() {
        let budget = Budget::start(Limits {
            timeout: Duration::ZERO,
            ..Limits::default()
        });
        std::thread::sleep(Duration::from_millis(2));
        assert!(matches!(
            budget.check_deadline(),
            Err(LimitExceeded::Deadline { .. })
        ));
        assert_eq!(budget.remaining(), Duration::ZERO);
    }

    #[test]
    fn charging_a_step_re_reads_the_deadline() {
        let mut budget = Budget::start(Limits {
            max_steps: u64::MAX,
            timeout: Duration::from_millis(5),
            ..Limits::default()
        });
        assert!(budget.charge_step().is_ok());
        std::thread::sleep(Duration::from_millis(10));
        assert!(matches!(
            budget.charge_step(),
            Err(LimitExceeded::Deadline { .. })
        ));
        assert_eq!(budget.steps(), 2);
    }

    #[test]
    fn fragmented_line_never_grows_pending_past_the_output_ceiling() {
        let mut buffer = OutputBuffer::new(&Limits {
            max_output_bytes: 32,
            ..Limits::default()
        });
        for _ in 0..100_000 {
            buffer.push_fragment("abcdefgh");
            assert!(buffer.pending.len() <= 32);
        }
        buffer.push_fragment("\ntail");
        buffer.finish();
        assert!(buffer.is_truncated());
        assert!(buffer.render().ends_with("tail"));
    }

    #[test]
    fn output_under_both_ceilings_is_preserved_exactly() {
        let mut buffer = OutputBuffer::new(&Limits::default());
        buffer.push_line("first");
        buffer.push_block("second\nthird");
        assert!(!buffer.is_truncated());
        assert_eq!(buffer.render(), "first\nsecond\nthird");
    }

    #[test]
    fn the_line_ceiling_keeps_head_and_tail() {
        let mut buffer = OutputBuffer::new(&Limits {
            max_output_lines: 4,
            ..Limits::default()
        });
        for index in 0..20 {
            buffer.push_line(&format!("line-{index}"));
        }
        let rendered = buffer.render();
        assert!(buffer.is_truncated());
        assert!(rendered.starts_with("line-0\nline-1\n"), "{rendered}");
        assert!(rendered.ends_with("line-18\nline-19"), "{rendered}");
        assert!(
            rendered.contains("... Output truncated (20 total lines) ..."),
            "{rendered}"
        );
    }

    #[test]
    fn one_oversized_line_cannot_bypass_the_byte_ceiling() {
        let mut buffer = OutputBuffer::new(&Limits {
            max_output_bytes: 32,
            max_output_lines: 10_000,
            ..Limits::default()
        });
        buffer.push_line(&"x".repeat(4096));
        buffer.push_line("tail");
        assert!(buffer.is_truncated());
        assert!(buffer.render().len() < 200, "{}", buffer.render());
        assert!(buffer.render().ends_with("tail"));
    }

    #[test]
    fn a_large_final_line_survives_as_a_clamped_prefix() {
        let mut buffer = OutputBuffer::new(&Limits {
            max_output_bytes: 64,
            max_output_lines: 100,
            ..Limits::default()
        });
        for index in 0..10 {
            buffer.push_line(&format!("diagnostic {index}"));
        }
        buffer.push_line(&format!("{{\"result\":\"{}\"}}", "y".repeat(4096)));

        let rendered = buffer.render();
        assert!(buffer.is_truncated());
        assert!(rendered.contains("{\"result\":\"yy"), "{rendered}");
        assert!(rendered.ends_with("..."), "{rendered}");
        assert!(rendered.len() < 4 * 64, "{rendered}");
    }

    #[test]
    fn a_line_longer_than_the_whole_ceiling_still_leaves_a_prefix() {
        let mut buffer = OutputBuffer::new(&Limits {
            max_output_bytes: 32,
            max_output_lines: 10_000,
            ..Limits::default()
        });
        buffer.push_line(&format!("head {}", "z".repeat(4096)));

        let rendered = buffer.render();
        assert!(buffer.is_truncated());
        assert!(rendered.contains("head zz"), "{rendered}");
        assert!(rendered.len() < 128, "{rendered}");
    }
}