ghostmode 0.1.1

Code Mode for Rust agents. The model writes a Python script that calls your tools, and ghostmode runs it in a sandbox.
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
//! The backend that runs each session's scripts in its own Monty worker process, checked out
//! from a monty-pool pool. Only this module talks to monty-pool.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::{error, fmt};

use monty_pool::{
    Checkout, Pool, PoolConfig, PoolError, PrintFuture, ReplConfig, ResumeValue, TurnEvent,
    on_print_sync,
};
use monty_types::{DEFAULT_MAX_PRINT_COLLECT_BYTES, MontyException, NameLookupResult, PrintStream};
use serde_json::Value;

use super::{SCRIPT_NAME, value};
use crate::backend::{Ending, Progress, Streams, sealed};
use crate::host;
use crate::sandbox::Limits;

/// How long a new session's first script or a restore waits for a worker when every worker the
/// pool allows is held, before it fails.
const CHECKOUT_TIMEOUT: Duration = Duration::from_secs(5);

/// Runs each session's scripts in its own worker process from a pool of `monty` workers that
/// [`WorkerOptions`] describe. Clones share the pool's workers, at most one per core of the
/// machine's [available parallelism]. Each sandbox's session checks out a worker at its first
/// script and keeps it, even while it runs nothing, until the session drops. [`Sandbox::reset`]
/// and dropping the sandbox both drop the session, which ends its worker. With every worker
/// held, a new session's first script or a restore waits a few seconds for a session to drop and
/// then fails, saying no worker became available.
///
/// Build it, and await every `execute`, `poll`, `cancel`, `dump` and `restore` of its sandboxes,
/// inside a Tokio multi-thread runtime. Awaiting them outside Tokio panics.
///
/// ```no_run
/// use ghostmode::backend::{MontyPool, WorkerOptions};
///
/// # async fn build() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// let mut options = WorkerOptions::new("/usr/local/bin/monty");
/// options.min_workers = 0;
/// let backend = MontyPool::new(options).await?;
/// # Ok(())
/// # }
/// ```
///
/// A worker that crashes takes down only itself, never the caller's process. The script's run
/// fails with an error that says so, and the next status reports `restarted`, with no globals.
/// The same holds when the sandbox stops a run at a tool call: at
/// [`Limits::calls_per_execute`], [`Limits::call_timeout`] or [`Limits::idle_timeout`], or with
/// [`Sandbox::cancel`]. A stopped run ends its worker, and the session's globals with it. A
/// script that goes past [`Limits::memory_bytes`], which a worker enforces on its whole memory,
/// often fails with `MemoryError` and leaves its worker running, and later scripts in that
/// session can keep failing until [`Sandbox::reset`].
///
/// The worker runs the script, but the thread that polls `execute` or `poll` still converts
/// values between JSON and Python and truncates output to [`Limits::output_chars`]. The thread
/// that polls `Builder::restore` checks a dump's signature.
///
/// [available parallelism]: std::thread::available_parallelism
/// [`Sandbox::cancel`]: crate::Sandbox::cancel
/// [`Sandbox::reset`]: crate::Sandbox::reset
#[derive(Clone)]
pub struct MontyPool(Arc<Pool>); // repeats module: pairs with Monty, the in-process backend

/// The `monty` worker processes that a [`MontyPool`] starts. Build it with [`WorkerOptions::new`],
/// then set its fields.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct WorkerOptions {
    /// The full path of the `monty` worker binary. Workers start with an empty environment, so
    /// a bare file name isn't looked up on `PATH`.
    pub binary_path: PathBuf,
    /// How many workers the pool keeps running, counting the ones that open sessions hold. With
    /// one session open and `min_workers` at 1, a new session's first script or a restore
    /// starts a new worker. The pool never runs more workers than the machine has cores, however
    /// high this is. The default is 1.
    pub min_workers: usize,
}

/// A Python session in [`MontyPool`], whose globals live in one worker process.
pub struct Session {
    config: ReplConfig,
    /// The session's worker, or `None` before its first script and after its worker ended.
    checkout: Option<Checkout>,
}

/// A script suspended at a tool call in [`MontyPool`], with what it has printed so far.
pub struct Suspension {
    config: ReplConfig,
    checkout: Checkout,
    streams: Streams,
    /// Set once a piece of a print would pass the 10 MiB collect cap, so stdout and stderr stay a
    /// prefix of what the script printed.
    print_cap_reached: bool,
}

impl fmt::Debug for MontyPool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MontyPool").finish_non_exhaustive()
    }
}

impl fmt::Debug for Session {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Session")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for Suspension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Suspension")
            .field("config", &self.config)
            .field("streams", &self.streams)
            .field("print_cap_reached", &self.print_cap_reached)
            .finish_non_exhaustive()
    }
}

impl WorkerOptions {
    /// Workers started from the `monty` binary at `binary_path`, with every other setting at its
    /// default.
    pub fn new(binary_path: impl Into<PathBuf>) -> Self {
        Self {
            binary_path: binary_path.into(),
            min_workers: 1,
        }
    }
}

impl MontyPool {
    /// A backend whose sessions each check out one of the workers that `options` describe. It
    /// starts [`WorkerOptions::min_workers`] workers before it returns. It fails if one of those
    /// can't start from [`WorkerOptions::binary_path`], or if `min_workers` is more than the pool
    /// allows, which is the machine's [available parallelism]. With `min_workers` at 0 it starts
    /// none, so a bad `binary_path` fails each session's first script instead.
    ///
    /// [available parallelism]: std::thread::available_parallelism
    pub async fn new(options: WorkerOptions) -> Result<Self, Box<dyn error::Error + Send + Sync>> {
        let config = PoolConfig {
            min_processes: options.min_workers,
            checkout_timeout: Some(CHECKOUT_TIMEOUT),
            ..PoolConfig::subprocess(options.binary_path)
        };
        Ok(Self(Arc::new(Pool::new(config).await?)))
    }

    /// The worker in `checkout`, or a new one checked out under `config` if there is none.
    async fn take_worker(
        &self,
        checkout: Option<Checkout>,
        config: &ReplConfig,
    ) -> Result<Checkout, PoolError> {
        match checkout {
            Some(checkout) => Ok(checkout),
            None => self.0.checkout(config).await,
        }
    }

    /// Runs the script on from `turn` until it calls one of the host's tools, which are
    /// `tools`, with keyword arguments, or ends. Every other suspension is answered here as
    /// `backend::Monty` answers it. What the script prints is added to the suspension's streams.
    async fn run(
        &self,
        mut suspension: Suspension,
        mut turn: Result<TurnEvent, PoolError>,
        tools: &[host::Tool],
    ) -> Progress<Self> {
        loop {
            let event = match turn {
                Ok(event) => event,
                Err(error) => {
                    return Progress::Ended(suspension.into_ending(Err(error.to_string())));
                }
            };
            let checkout = &mut suspension.checkout;
            let mut on_print =
                collect_prints(&mut suspension.streams, &mut suspension.print_cap_reached);
            turn = match event {
                TurnEvent::Complete(value) => {
                    drop(on_print);
                    return Progress::Ended(suspension.into_ending(value::to_json(value.as_ref())));
                }
                TurnEvent::FunctionCall {
                    function_name,
                    args,
                    ..
                } if tools.iter().any(|tool| tool.id == function_name) => {
                    match value::to_call(function_name, &args) {
                        Ok(call) => {
                            drop(on_print);
                            return Progress::Call { call, suspension };
                        }
                        Err(error) => checkout.resume(ResumeValue::Error(error), &mut on_print),
                    }
                    .await
                }
                TurnEvent::FunctionCall { .. } => {
                    checkout.resume(ResumeValue::NotFound, &mut on_print).await
                }
                TurnEvent::NameLookup { .. } => {
                    let answer = NameLookupResult::Undefined;
                    checkout.resume_name_lookup(answer, &mut on_print).await
                }
                TurnEvent::OsCall { .. } => {
                    checkout
                        .resume(ResumeValue::NotHandled, &mut on_print)
                        .await
                }
                TurnEvent::ResolveFutures { .. } => {
                    drop(on_print);
                    let message = super::TOOLS_NOT_AWAITABLE.to_string();
                    return Progress::Ended(
                        sealed::Backend::abort(self, suspension, message).await,
                    );
                }
            };
        }
    }
}

impl sealed::Backend for MontyPool {
    type Session = Session;
    type Suspension = Suspension;

    async fn new_session(&self, limits: &Limits) -> Session {
        Session {
            config: to_repl_config(limits),
            checkout: None,
        }
    }

    async fn feed_start(
        &self,
        session: Session,
        code: &str,
        tools: &[host::Tool],
    ) -> Progress<Self> {
        let Session { config, checkout } = session;
        let mut checkout = match self.take_worker(checkout, &config).await {
            Ok(checkout) => checkout,
            Err(error) => {
                return Progress::Ended(Ending {
                    result: Err(error.to_string()),
                    streams: Streams::default(),
                    session: Session {
                        config,
                        checkout: None,
                    },
                    lost_globals: false,
                });
            }
        };
        let mut streams = Streams::default();
        let mut print_cap_reached = false;
        let turn = checkout
            .feed(
                code,
                Vec::new(),
                Vec::new(),
                true,
                &mut collect_prints(&mut streams, &mut print_cap_reached),
            )
            .await;
        let suspension = Suspension {
            config,
            checkout,
            streams,
            print_cap_reached,
        };
        self.run(suspension, turn, tools).await
    }

    async fn resume(
        &self,
        mut suspension: Suspension,
        answer: Result<Value, host::Error>,
        tools: &[host::Tool],
    ) -> Progress<Self> {
        let answer = value::from_answer(answer)
            .map(ResumeValue::Return)
            .unwrap_or_else(ResumeValue::Error);
        let mut on_print =
            collect_prints(&mut suspension.streams, &mut suspension.print_cap_reached);
        let turn = suspension.checkout.resume(answer, &mut on_print).await;
        drop(on_print);
        self.run(suspension, turn, tools).await
    }

    /// Ends the script by ending its worker, so the session loses its globals.
    async fn abort(&self, suspension: Suspension, message: String) -> Ending<Self> {
        suspension.kill_worker(Err(MontyException::runtime_error(message).to_string()))
    }

    /// Ends the script's worker, so the session loses its globals.
    async fn abandon(&self, suspension: Suspension, message: String) -> Ending<Self> {
        suspension.kill_worker(Err(message))
    }

    /// A session with no worker yet checks one out to dump. Bytes the worker can't write are an
    /// `Err` that says why. A worker that ends while it dumps takes the session's globals with it.
    async fn dump(
        &self,
        session: &mut Session,
    ) -> (Result<Vec<u8>, Box<dyn error::Error + Send + Sync>>, bool) {
        let mut checkout = match self
            .take_worker(session.checkout.take(), &session.config)
            .await
        {
            Ok(checkout) => checkout,
            Err(error) => return (Err(error.into()), false),
        };
        let bytes = checkout.dump().await;
        let alive = checkout.worker_id().is_some();
        if alive {
            session.checkout = Some(checkout);
        }
        (bytes.map_err(Into::into), !alive)
    }

    /// Bytes the worker can't load are an `Err` that says why. Bytes that crash or hang the
    /// worker harm only that worker.
    async fn restore(
        &self,
        bytes: &[u8],
        limits: &Limits,
    ) -> Result<Session, Box<dyn error::Error + Send + Sync>> {
        let config = to_repl_config(limits);
        let mut checkout = self.0.checkout(&config).await?;
        let mut on_print = on_print_sync(|_, _| {});
        let (suspension, _) = checkout
            .restore(bytes.to_vec(), Vec::new(), &mut on_print)
            .await?;
        if suspension.is_some() {
            return Err(super::DUMP_HOLDS_RUN.into());
        }
        Ok(Session {
            config,
            checkout: Some(checkout),
        })
    }
}

impl Suspension {
    /// How the script ended with `result`. The session keeps the worker if it is still alive,
    /// and otherwise has none and says the session lost its globals.
    fn into_ending(self, result: Result<Value, String>) -> Ending<MontyPool> {
        let alive = self.checkout.worker_id().is_some();
        Ending {
            result,
            streams: self.streams,
            session: Session {
                config: self.config,
                checkout: alive.then_some(self.checkout),
            },
            lost_globals: !alive,
        }
    }

    /// Ends the script with `result` by ending its worker, so the session it gives back has no
    /// worker and says it lost its globals. Dropping the checkout kills the worker process and
    /// frees its place in the pool.
    fn kill_worker(self, result: Result<Value, String>) -> Ending<MontyPool> {
        drop(self.checkout);
        Ending {
            result,
            streams: self.streams,
            session: Session {
                config: self.config,
                checkout: None,
            },
            lost_globals: true,
        }
    }
}

/// The worker session settings that stop a script at `limits`' run time, memory and recursion
/// depth, name the session [`SCRIPT_NAME`] and return from `time.sleep` at once.
fn to_repl_config(limits: &Limits) -> ReplConfig {
    ReplConfig {
        script_name: SCRIPT_NAME.to_string(),
        limits: Some(super::to_resource_limits(limits)),
        os_policy: super::build_os_policy(),
        ..ReplConfig::default()
    }
}

/// A print callback that adds what the script prints to `streams`. The worker sends a print in
/// pieces, and the first piece that would take both streams together past 10 MiB sets
/// `print_cap_reached`, so it and every later piece are dropped and the output stays a prefix of
/// what the script printed.
fn collect_prints<'out>(
    streams: &'out mut Streams,
    print_cap_reached: &'out mut bool,
) -> impl FnMut(PrintStream, &str) -> PrintFuture + Send + 'out {
    on_print_sync(|stream, text| {
        let printed_bytes = streams.stdout.len() + streams.stderr.len();
        *print_cap_reached =
            *print_cap_reached || printed_bytes + text.len() > DEFAULT_MAX_PRINT_COLLECT_BYTES;
        if *print_cap_reached {
            return;
        }
        match stream {
            PrintStream::Stdout => streams.stdout.push_str(text),
            PrintStream::Stderr => streams.stderr.push_str(text),
        }
    })
}