amux-runtime 0.1.0

Persistent process and TTY runtime for AI agents, with durable logs and human attach
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
use std::{
    fs::{self, File, OpenOptions},
    io::{BufReader, Write},
    os::unix::fs::{OpenOptionsExt, PermissionsExt},
    path::{Path, PathBuf},
    sync::Mutex,
};

use anyhow::{Context, Result, anyhow, bail};
use chrono::Utc;
use regex::Regex;
use serde::{Serialize, de::DeserializeOwned};

use crate::model::*;

pub struct Store {
    root: PathBuf,
    lock: Mutex<()>,
}

impl Store {
    pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
        let root = root.into();
        let store = Self::deferred(root);
        store.ensure_schema()?;
        Ok(store)
    }

    pub(crate) fn deferred(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            lock: Mutex::new(()),
        }
    }

    pub(crate) fn ensure_schema(&self) -> Result<()> {
        let _guard = self.lock.lock().unwrap();
        let root = &self.root;
        if root.exists() {
            let valid = read_json::<serde_json::Value>(root.join("schema.json"))
                .ok()
                .and_then(|v| v.get("schema_version").and_then(|v| v.as_u64()))
                == Some(SCHEMA_VERSION as u64);
            if !valid {
                fs::remove_dir_all(root).context("reset incompatible amux schema")?;
            }
        }
        fs::create_dir_all(root.join("workspaces"))?;
        fs::set_permissions(root, fs::Permissions::from_mode(0o700))?;
        atomic_json(
            &root.join("schema.json"),
            &serde_json::json!({"schema_version": SCHEMA_VERSION}),
        )?;
        Ok(())
    }

    pub fn root(&self) -> &Path {
        &self.root
    }
    pub fn workspace_dir(&self, id: &str) -> PathBuf {
        self.root.join("workspaces").join(id)
    }
    pub fn process_dir(&self, wid: &str, pid: &str) -> PathBuf {
        self.workspace_dir(wid).join("processes").join(pid)
    }

    pub fn create_workspace(&self, req: CreateWorkspaceRequest) -> Result<Workspace> {
        let _guard = self.lock.lock().unwrap();
        if !valid_name(&req.name) {
            bail!("invalid name")
        }
        if self
            .list_workspaces_unlocked()?
            .iter()
            .any(|w| w.name == req.name)
        {
            bail!("name conflict")
        }
        let runtime = if req.runtime.is_empty() {
            "host".to_owned()
        } else {
            req.runtime
        };
        if runtime != "host" {
            bail!("runtime not supported")
        }
        let now = Utc::now();
        let workspace = Workspace {
            schema_version: SCHEMA_VERSION,
            id: id("ws"),
            name: req.name,
            runtime,
            root_dir: req.root_dir,
            env: req.env,
            state: WorkspaceState::Idle,
            created_at: now,
            updated_at: now,
        };
        let group = Group {
            id: id("grp"),
            workspace_id: workspace.id.clone(),
            name: "default".into(),
            placement: Default::default(),
            created_at: now,
        };
        let environment = Environment {
            id: id("env"),
            workspace_id: workspace.id.clone(),
            group_id: group.id.clone(),
            name: "host".into(),
            image: String::new(),
            env: Default::default(),
            mounts: vec![],
            runtime_data: Default::default(),
            created_at: now,
        };
        let dir = self.workspace_dir(&workspace.id);
        fs::create_dir_all(dir.join("processes"))?;
        atomic_json(&dir.join("metadata.json"), &workspace)?;
        atomic_json(&dir.join("group.json"), &group)?;
        atomic_json(&dir.join("environment.json"), &environment)?;
        Ok(workspace)
    }

    pub fn list_workspaces(&self) -> Result<Vec<Workspace>> {
        let _guard = self.lock.lock().unwrap();
        self.list_workspaces_unlocked()
    }

    fn list_workspaces_unlocked(&self) -> Result<Vec<Workspace>> {
        let mut out: Vec<Workspace> = Vec::new();
        for entry in fs::read_dir(self.root.join("workspaces"))? {
            let entry = entry?;
            if entry.file_type()?.is_dir()
                && let Ok(value) = read_json(entry.path().join("metadata.json"))
            {
                out.push(value);
            }
        }
        out.sort_by_key(|w| w.created_at);
        Ok(out)
    }

    pub fn find_workspace(&self, target: &str) -> Result<Workspace> {
        self.list_workspaces()?
            .into_iter()
            .find(|w| w.id == target || w.name == target)
            .ok_or_else(|| anyhow!("workspace not found"))
    }

    pub fn defaults(&self, wid: &str) -> Result<(Group, Environment)> {
        let dir = self.workspace_dir(wid);
        Ok((
            read_json(dir.join("group.json"))?,
            read_json(dir.join("environment.json"))?,
        ))
    }

    pub fn save_workspace(&self, workspace: &mut Workspace) -> Result<()> {
        let _guard = self.lock.lock().unwrap();
        workspace.updated_at = Utc::now();
        atomic_json(
            &self.workspace_dir(&workspace.id).join("metadata.json"),
            workspace,
        )
    }

    pub fn create_process(
        &self,
        workspace: &Workspace,
        req: RunRequest,
        boot_id: String,
    ) -> Result<Process> {
        let _guard = self.lock.lock().unwrap();
        if !valid_name(&req.name) || req.command.is_empty() {
            bail!("invalid process")
        }
        if self
            .list_processes_unlocked(&workspace.id)?
            .iter()
            .any(|p| p.name == req.name)
        {
            bail!("name conflict")
        }
        let (group, env): (Group, Environment) = (
            read_json(self.workspace_dir(&workspace.id).join("group.json"))?,
            read_json(self.workspace_dir(&workspace.id).join("environment.json"))?,
        );
        let now = Utc::now();
        let (rows, cols) = if req.io_mode == IoMode::Tty {
            (
                if req.initial_rows == 0 {
                    40
                } else {
                    req.initial_rows
                },
                if req.initial_cols == 0 {
                    120
                } else {
                    req.initial_cols
                },
            )
        } else {
            (0, 0)
        };
        let process = Process {
            schema_version: SCHEMA_VERSION,
            id: id("proc"),
            workspace_id: workspace.id.clone(),
            group_id: group.id,
            environment_id: env.id,
            name: req.name,
            parent_process_id: req.parent_process_id,
            command: req.command,
            cwd: req.cwd,
            env: req.env,
            io_mode: req.io_mode,
            runtime: "host".into(),
            pid: 0,
            process_group_id: 0,
            runtime_handle: String::new(),
            state: ProcessState::Starting,
            exit_code: None,
            exit_signal: String::new(),
            error: String::new(),
            execution: 1,
            initial_rows: rows,
            initial_cols: cols,
            boot_id,
            created_at: now,
            started_at: None,
            finished_at: None,
        };
        let dir = self.process_dir(&process.workspace_id, &process.id);
        fs::create_dir_all(&dir)?;
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?;
        atomic_json(&dir.join("metadata.json"), &process)?;
        Ok(process)
    }

    pub fn save_process(&self, process: &Process) -> Result<()> {
        let _guard = self.lock.lock().unwrap();
        let path = self
            .process_dir(&process.workspace_id, &process.id)
            .join("metadata.json");
        let current = read_json::<Process>(&path).context("update existing process")?;
        if current.execution > process.execution
            || (current.execution == process.execution
                && current.state.terminal()
                && !process.state.terminal())
        {
            return Ok(());
        }
        atomic_json(&path, process)
    }

    pub fn save_runtime_env(
        &self,
        process: &Process,
        env: &std::collections::BTreeMap<String, String>,
    ) -> Result<()> {
        let _guard = self.lock.lock().unwrap();
        atomic_json(
            &self
                .process_dir(&process.workspace_id, &process.id)
                .join("runtime-env.json"),
            env,
        )
    }

    pub fn list_processes(&self, wid: Option<&str>) -> Result<Vec<Process>> {
        let _guard = self.lock.lock().unwrap();
        if let Some(wid) = wid {
            return self.list_processes_unlocked(wid);
        }
        let mut out = vec![];
        for workspace in self.list_workspaces_unlocked()? {
            out.extend(self.list_processes_unlocked(&workspace.id)?);
        }
        Ok(out)
    }

    fn list_processes_unlocked(&self, wid: &str) -> Result<Vec<Process>> {
        let dir = self.workspace_dir(wid).join("processes");
        let Ok(entries) = fs::read_dir(dir) else {
            return Ok(vec![]);
        };
        let mut out = vec![];
        for entry in entries {
            let entry = entry?;
            if entry.file_type()?.is_dir()
                && let Ok(process) = read_json(entry.path().join("metadata.json"))
            {
                out.push(process);
            }
        }
        Ok(out)
    }

    pub fn find_process(&self, target: &str) -> Result<Process> {
        let processes = self.list_processes(None)?;
        if let Some(process) = processes.iter().find(|p| p.id == target) {
            return Ok(process.clone());
        }
        if let Some((workspace, name)) = target.split_once('/') {
            let workspace = self.find_workspace(workspace)?;
            if let Some(process) = processes
                .into_iter()
                .find(|p| p.workspace_id == workspace.id && p.name == name)
            {
                return Ok(process);
            }
        } else {
            let mut named = processes
                .into_iter()
                .filter(|process| process.name == target);
            if let Some(process) = named.next() {
                if named.next().is_some() {
                    bail!("process name is ambiguous; use workspace/name")
                }
                return Ok(process);
            }
        }
        bail!("process not found")
    }

    pub fn remove_process(&self, process: &Process) -> Result<()> {
        let _guard = self.lock.lock().unwrap();
        fs::remove_dir_all(self.process_dir(&process.workspace_id, &process.id))?;
        Ok(())
    }

    pub fn remove_workspace(&self, workspace: &Workspace) -> Result<()> {
        let _guard = self.lock.lock().unwrap();
        fs::remove_dir_all(self.workspace_dir(&workspace.id))?;
        Ok(())
    }
}

pub fn atomic_json(path: &Path, value: &impl Serialize) -> Result<()> {
    let parent = path.parent().context("path has no parent")?;
    fs::create_dir_all(parent)?;
    let temp = parent.join(format!(".tmp-{}", uuid::Uuid::new_v4()));
    let mut file = OpenOptions::new()
        .create_new(true)
        .write(true)
        .mode(0o600)
        .open(&temp)?;
    serde_json::to_writer_pretty(&mut file, value)?;
    file.write_all(b"\n")?;
    file.sync_all()?;
    fs::rename(&temp, path)?;
    Ok(())
}

pub fn append_line(path: &Path, bytes: &[u8]) -> Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .open(path)?;
    file.write_all(bytes)?;
    file.write_all(b"\n")?;
    file.sync_data()?;
    Ok(())
}

pub fn append_raw(path: &Path, bytes: &[u8]) -> Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .open(path)?;
    file.write_all(bytes)?;
    file.sync_data()?;
    Ok(())
}

pub fn read_json<T: DeserializeOwned>(path: impl AsRef<Path>) -> Result<T> {
    Ok(serde_json::from_reader(BufReader::new(File::open(path)?))?)
}

pub fn valid_name(value: &str) -> bool {
    Regex::new(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$")
        .unwrap()
        .is_match(value)
}

fn id(prefix: &str) -> String {
    format!("{prefix}_{}", uuid::Uuid::new_v4().simple())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn store_round_trip() {
        let temp = tempfile::tempdir().unwrap();
        let store = Store::open(temp.path()).unwrap();
        let workspace = store
            .create_workspace(CreateWorkspaceRequest {
                name: "dev".into(),
                ..Default::default()
            })
            .unwrap();
        assert_eq!(store.find_workspace("dev").unwrap().id, workspace.id);
        let process = store
            .create_process(
                &workspace,
                RunRequest {
                    name: "api".into(),
                    command: vec!["true".into()],
                    ..Default::default()
                },
                "boot".into(),
            )
            .unwrap();
        assert_eq!(store.find_process("dev/api").unwrap().id, process.id);
        assert_eq!(store.find_process("api").unwrap().id, process.id);

        let other = store
            .create_workspace(CreateWorkspaceRequest {
                name: "other".into(),
                ..Default::default()
            })
            .unwrap();
        store
            .create_process(
                &other,
                RunRequest {
                    name: "api".into(),
                    command: vec!["true".into()],
                    ..Default::default()
                },
                "boot".into(),
            )
            .unwrap();
        assert!(store.find_process("api").is_err());
    }

    #[test]
    fn removal_releases_the_name_and_updates_cannot_recreate_the_record() {
        let root = tempfile::tempdir().unwrap();
        let store = Store::open(root.path()).unwrap();
        let workspace = store
            .create_workspace(CreateWorkspaceRequest {
                name: "dev".into(),
                ..Default::default()
            })
            .unwrap();
        let request = || RunRequest {
            name: "worker".into(),
            command: vec!["true".into()],
            ..Default::default()
        };
        let mut process = store
            .create_process(&workspace, request(), "boot".into())
            .unwrap();
        process.state = ProcessState::Exited;
        store.save_process(&process).unwrap();
        assert!(
            store
                .create_process(&workspace, request(), "boot".into())
                .is_err()
        );
        store.remove_process(&process).unwrap();
        assert!(store.save_process(&process).is_err());
        assert!(!store.process_dir(&workspace.id, &process.id).exists());
        assert!(
            store
                .create_process(&workspace, request(), "boot".into())
                .is_ok()
        );
    }
}