monocore 0.2.1

`monocore` is a secure MicroVM provisioning system for running untrusted code in isolated environments.
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
<div align="center">
  <a href="https://github.com/appcypher/monocore" target="_blank">
    <img src="https://raw.githubusercontent.com/appcypher/monocore/main/assets/monocore-thick-line-purple-gradient.svg" alt="monocore logo" width="100"></img>
  </a>

  <h1>monocore</h1>

  <p>
    <a href="https://discord.gg/T95Y3XnEAK">
      <img src="https://img.shields.io/static/v1?label=Discord&message=join%20us!&color=mediumslateblue" alt="Discord">
    </a>
    <a href="https://github.com/appcypher/monocore/actions?query=">
      <img src="https://github.com/appcypher/monocore/actions/workflows/tests_and_checks.yml/badge.svg" alt="Build Status">
    </a>
    <a href="https://crates.io/crates/monocore">
      <img src="https://img.shields.io/crates/v/monocore?label=crates" alt="Monocore Crate">
    </a>
    <a href="https://docs.rs/monocore">
      <img src="https://img.shields.io/static/v1?label=Docs&message=docs.rs&color=blue" alt="Monocore Docs">
    </a>
    <a href="https://github.com/appcypher/monocore/blob/main/LICENSE">
      <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
    </a>
  </p>
</div>

**`monocore`** is the engine behind the monocore platform, providing a robust foundation for running AI workloads in isolated microVMs. It handles everything from VM lifecycle management to OCI image distribution, making it easy to deploy and orchestrate code sandboxes securely.

> [!WARNING]
> This project is in early development and is not yet ready for production use.

## Table of Contents

- [Overview]#overview
- [Library Usage]#library-usage
- [Getting Started]#getting-started
- [Features]#features
- [Architecture]#architecture
- [Development]#development
- [License]#license

## Overview

When developing AI agents that execute code, you need a fast development cycle:

- Docker containers? Limited isolation for untrusted code
- Traditional VMs? Minutes to start up, heavy resource usage
- Direct execution? Risky for your development machine
- Cloud sandboxes? Great for production, but slow for rapid iteration

monocore provides:
- 🔒 True VM-level isolation
- âš¡ Millisecond startup times
- 🎯 Simple REST API
- 📦 Works with standard container images
- 🔧 Full resource control
- 💻 Perfect for local development

## Library Usage

### Basic MicroVM
```rust
use monocore::vm::MicroVm;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Build the MicroVm
    let vm = MicroVm::builder()
        .root_path("/path/to/rootfs")  // Path to rootfs
        .ram_mib(512)
        .exec_path("/bin/true")  // Simple no-op command
        .build()?;

    // Start the MicroVm
    tracing::info!("Starting MicroVm...");
    vm.start()?;
    Ok(())
}
```

### Service Orchestration
```rust
use monocore::{
    config::{Group, Monocore, Service},
    orchestration::Orchestrator,
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create a simple service
    let service = Service::builder_default()
        .name("app")
        .base("alpine:latest")
        .ram(512)
        .group("main")  // Group name is required
        .command("/bin/sleep")  // Example command
        .args(["infinity"])     // Run indefinitely
        .build();

    // Create the main group
    let main_group = Group::builder()
        .name("main")
        .build();

    let config = Monocore::builder()
        .services(vec![service])
        .groups(vec![main_group])
        .build()?;

    // Create orchestrator with log retention
    let mut orchestrator = Orchestrator::with_log_retention_policy(
        "/path/to/oci_dir",
        "/path/to/supervisor",
        LogRetentionPolicy::with_max_age_weeks(1),
    ).await?;

    // Start the service
    orchestrator.up(config).await?;

    Ok(())
}
```

## Getting Started

### Installation

**Quick Install:**
```bash
curl -sSfL https://install.monocore.dev | sh
```

This will install both the `monocore` command and its alias `mc`.

**System Requirements:**

<details>
<summary><b>Linux</b></summary>

- KVM-enabled Linux kernel (check with `ls /dev/kvm`)
- User must be in the `kvm` group (add with `sudo usermod -aG kvm $USER`)
</details>

<details>
<summary><b>macOS</b></summary>

- Apple Silicon (ARM64) only
- macOS 10.15 (Catalina) or later for Hypervisor.framework support
</details>

<details>
<summary><b>Windows</b></summary>

> Coming soon!
</details>


**Manual Build:**
```bash
# Clone the repository
git clone https://github.com/appcypher/monocore.git
cd monocore

# Build and install (installs to /usr/local/bin)
make monocore && sudo make install
```

### Basic Usage

1. Create a configuration file:
```toml
# monocore.toml
[[service]]
name = "sh-counter"
base = "alpine:latest"
ram = 256
cpus = 1
group = "demo"
command = "/bin/sh"
args = ["-c", "for i in $(seq 1 10); do echo $i; sleep 2; done"]

[[service]]
name = "python-counter"
base = "python:3.11-slim"
ram = 256
cpus = 1
group = "demo"
command = "/usr/local/bin/python3"
args = [
    "-c",
    "import time; count=0; [print(f'Count: {count+1}') or time.sleep(2) or (count:=count+1) for _ in range(10)]",
]

[[group]]
name = "demo"
local_only = true
```

2. Manage your services:
```bash
# Start services
monocore up -f monocore.toml

# View status
monocore status

# Stop services
monocore down

# Remove services
monocore remove -g main
```

3. Run in server mode:
```bash
# Start the REST API server (default port: 3456)
monocore serve --port 3456

# Or use the default port
monocore serve
```

For more CLI options:
```bash
monocore --help
```

### Configuration Schema

The `monocore.toml` configuration file supports the following structure:

```toml
# Service Definition
[[service]]
name = "service-name"          # Required: Name of the service
base = "image:tag"             # Optional: Base OCI image to use
group = "group-name"           # Optional: Group this service belongs to
command = "/path/to/binary"    # Optional: Command to run
args = ["arg1", "arg2"]        # Optional: Arguments for the command
cpus = 1                       # Optional: Number of vCPUs (default: 1)
ram = 1024                     # Optional: RAM in MiB (default: 1024)
workdir = "/app"               # Optional: Working directory
port = "8080:80"               # Optional: Port mapping (host:guest)
volumes = ["/host:/guest"]     # Optional: Volume mappings
envs = ["KEY=value"]           # Optional: Environment variables
depends_on = ["other-service"] # Optional: Service dependencies
group_envs = ["prod"]          # Optional: Environment variables for the group
group_volumes = [              # Optional: Volume mappings for the group
  {
    name = "shared-data",      # Required: Name of the volume
    path = "/data:/data"       # Required: Path mapping (host:guest)
  }
]

# Group Definition
[[group]]
name = "group-name"            # Required: Name of the group
local_only = true              # Optional: Restrict connection to local network (default: true)

# Group volume definition
[[group.volume]]
name = "shared-data"           # Required: Name of the volume
path = "/data"                 # Required: Base path on host system

# Group environment variables
[[group.env]]
name = "prod"                  # Required: Name of the environment group
envs = ["API_KEY=value"]       # Optional: Environment variables
```

#### Volume Mappings
Volumes can be specified in two formats:
- Single path (`/data`): Uses the same path on both host and guest
- Path pair (`/host:/guest`): Maps host path to a different guest path

#### Port Mappings
Ports can be specified in two formats:
- Single port (`8080`): Uses the same port on both host and guest
- Port pair (`8080:80`): Maps host port to a different guest port

#### Service Groups
Services can be organized into groups for:
- Shared volume definitions
- Common environment variables
- Network isolation (when `local_only = true`)
- Resource management

#### Dependencies
- Services can specify dependencies using `depends_on`
- Maximum dependency chain length is 32
- Services are started in dependency order

### REST API

When running in server mode, monocore provides a REST API for managing services:

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/up`    | POST   | Start services defined in config |
| `/down`  | POST   | Stop running services |
| `/status`| GET    | Get status of all services |
| `/remove`| POST   | Remove service files |

Example API usage:

```bash
# Start services
curl -X POST http://localhost:3456/up \
  -H "Content-Type: application/json" \
  -d @monocore.json

# Get service status
curl http://localhost:3456/status

# Stop services in a group
curl -X POST http://localhost:3456/down \
  -H "Content-Type: application/json" \
  -d '{"group": "main"}'

# Remove services
curl -X POST http://localhost:3456/remove \
  -H "Content-Type: application/json" \
  -d '{"services": ["counter", "date-service"]}'
```

## Features

### Secure Isolation
- Isolated microVM environments for each service
- Resource constraints and limits enforcement
- Network isolation between service groups
- Perfect for running untrusted AI-generated code
- Full system call isolation

### Efficient Runtime
- Fast microVM provisioning and startup
- Millisecond-level boot times
- Minimal resource overhead
- Optimized layer caching and sharing
- Memory-efficient design

### OCI Integration
- Pull images from any OCI-compliant registry
- Smart layer management and deduplication
- Local image caching for faster startups
- Support for standard container images
- Seamless Docker compatibility

### Service Orchestration
- Dependency-aware service scheduling
- Health monitoring and automatic recovery
- Log rotation with configurable retention
- Resource usage tracking
- Group-based service management

## Architecture

### Directory Structure

Monocore maintains its state in `~/.monocore`:

```mermaid
graph TD
    monocore_root[~/.monocore] --> monoimage[monoimage/]
    monoimage --> monoimage_repo[repo/]
    monoimage_repo --> monoimage_cid["[repo-name]__[tag].cid"]
    monoimage --> monoimage_layer[layer/]

    monocore_root --> oci[oci/]
    oci --> oci_repo[repo/]
    oci_repo --> oci_tag["[repo-name]__[tag]/"]
    oci_tag --> oci_config[config.json]
    oci_tag --> oci_manifest[manifest.json]
    oci_tag --> oci_index[index.json]
    oci --> oci_layer[layer/]
    oci_layer --> oci_layer_hash["[hash]"]

    monocore_root --> rootfs[rootfs/]
    rootfs --> rootfs_service[service/]
    rootfs_service --> rootfs_service_rootfs["[service-name]/"]
    rootfs --> rootfs_ref[reference/]
    rootfs_ref --> rootfs_ref_repo["[repo-name]__[tag]/"]
    rootfs_ref_repo --> rootfs_ref_repo_merged[merged/]

    monocore_root --> service[service/]
    service --> service_info["[service-name]/"]
    service_info --> service_json[service.json]
    service_info --> group_json[group.json]

    monocore_root --> run[run/]
    run --> run_service["[service-name]__[pid].json"]

    monocore_root --> log[log/]
    log --> log_stderr["[service-name].stderr.log"]
    log --> log_stdout["[service-name].stdout.log"]
```

## Development

For development setup and building from source, please visit the [root of the project repository](https://github.com/appcypher/monocore).

## License

This project is licensed under the [Apache License 2.0](./LICENSE).